Search code examples
design-patternsgodotgdscript

Overriding a critical base method while preserving its functionality without making my code smelly


In Godot, it is possible to define a signal and emit it in a method, which will call all the methods connected to it. In this example, on_met_customer() is connected to signal met_customer in the class Merchant, which is responsible for detecting customers.

# Parent class
extends Merchant
class_name Salesman

func greet():
    print("Hello!")

func on_met_customer():
    greet
# Child class
extends Salesman
class_name CarSalesman

func shake_hands():
    print("*handshake*")
    
func on_met_customer():
    # .on_met_customer() I don't want to have to remember to call super
    shake_hands()
# Desired console output when calling on_met_customer() from the child class
Hello!
*handshake*

What I want to do is either:

  1. "Extend" instead of overriding on_met_customer() to preserve the parent functionality without calling super, or:
  2. Warn myself somehow when overriding on_met_customer() to not forget to call super

Solution

  • Calling the parent is a kind of habit ; it's actually (most of the time) pretty nice to have the choice.

    If you really don't want to call the parent method, an alternative would be to add your own overridable method in Merchant:

    extends Merchant
    class_name Salesman
    
    func greet():
        print("Hello!")
    
    func meet_customer():
        pass  # override me
    
    func on_met_customer():
        greet()
        meet_customer()
        rob_customer()
        # …
    

    and then override that in the child:

    extends Salesman
    class_name CarSalesman
    
    func shake_hands():
        print("*handshake*")
        
    func meet_customer():
        shake_hands()