Extend-ed class being aware of extend-ee properties

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By emilianop

If I have a class defining a somewhat complex behaviour, something like:

#complexMovement.gd

func _on_some_event(e):
    if e is my_event:
        run_some_logic()
        100s_lines_of_code...

and I’m inheriting this in a bunch of other classes, like:

#first.gd

extends "complexMovement.gd"
 
func do_something_here():
     blabla

and

#second.gd

extends "complexMovement.gd"
 
func do_something_special():
    blabla

Is there any way for me to implement some specific logic inside “complexMovement.gd” so that I can specify some custom logic only in the case where it gets extended inside “second.gd” and not “first.gd”?
Basically something along the line of:

#complexMovement.gd
 
if this.has_method("do_something_special"):
    this.do_something_special()

which of course wouldn’t work using this, but I hope you get the idea…

:bust_in_silhouette: Reply From: zhyrin

In GDScript, there is the self keyword instead of this.
For this example, you don’t even need self:

if has_method("method_in_derived_class"):
    call("method_in_derived_class")

But this approach breaks OOP principles, I would recommend you rather define the function in the base class (without implementation), and override it in derived classes.

call("method_in_derived_class")

Good to know, I’ll try that!

I would recommend you rather define the function in the base class (without implementation), and override it in derived classes.

Well, that’s what I’m currently doing, but because the behaviour on the overridden function is really intertwined with the original function, I have to re-write the entire function inside the derived class. This equates to code duplication, and I really hate that.

Another option would be to implement both behaviours in the source class, implementing some high level logic like

var is_second = false

and setting is_second to true only inside second.gd…

I’m still unsure of which one is better…

emilianop | 2023-03-06 21:30