Search code examples
javascriptdrysubclassing

Not rewriting a method just to add a single line of code?


Time and time again this has happened to me: We have class CLS with init method like this:

init {
    // do A

    // do B

    // do C
}

Now, in a certain case we need to do X exactly between B and C. Making a subclass of CLS and re-writing the whole init method with X inserted there does not seem like a good solution to me (It is the opposite of DRY), Is there a better solution that hasn't occurred to me?

Please note that A, B and C are small code fragments doing small tweaks like adjusting the UI so it is probably not a good idea to put them in separate methods. I'm currently coding in JavaScript but I think this question applies to other PLs as well.


Solution

  • We usually add hooks to the parent class, where we expect extensions. I don't remember what it is called though. Maybe it's the template method pattern?

    class Foo {
      init() {
        console.log("A");
        console.log("B");
        this.doX();
        console.log("C");
      }
      doX(){}
    }
    
    class Bar extends Foo {
      doX() {
        console.log("X");
      }
    }
    
    new Bar().init();