Optional method in base class

1.9k views Asked by At

basically I want to have a method that is optional on the base class, and the inherited classes may or not implement that method.

class One
{
method()
    {
        // optional
    }
}

class Two extends One
{
    // some classes don't implement it
}

class Three extends One
{
    // others do
method()
    {
        // doStuff();
    }
}

Then I would figure out if the method exists or not.

if ( object.method )
    {
    object.method();
    }

The idea is that the method isn't called for every object (not calling empty functions), but only when there's something defined.

I could do like this, but if there's some nicer way I'm missing..

class One
{
method: () => any;

constructor()
    {
    this.method = null;
    }   
}

class Two extends One
{
constructor()
    {
    super();

    this.method = this._method;
    }

_method()
    {
        // doStuff();
    }
}

Thanks.

3

There are 3 answers

1
Bathsheba On

Use composition. Define an interface which contains the method. Only certain classes implement that interface.

You can check at runtime if an object implements that interface.

1
basarat On

You've made your life slightly painful by assiging it to null in the base class. If you don't do that the code becomes much simpler:

class One {
    method: () => any;

    constructor() {        
    }
}

class Two extends One {
    constructor() {
        super();
    }

    method = () => {
        // doStuff();
    }
}

By default it is undefined anyways and assigning it to null gives no special value.

0
Urrri On

In Typescript:

class One {
    method?(whatever:any):any; // optional
}

class Two extends One {
    // some classes don't implement it
}

class Three extends One {
    // others do
    method(whatever:any):any {
        // doStuff();
    }
}