Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Why you should never have to call super.Foo() in an Foo overload.

This is a classic example of poorly structured points of customisation.

For example, when you have:

class Base
{
  virtual void Foo();
}

And in subclasses you find you need to do:

class Sub : Base
{
  virtual void Foo() {
    super.Foo();
    // And now do my extra stuff
  }
}

A better design (for Base) might have been:

class Base
{
  void Foo(); // Foo does Base.Foo work, then calls PostFoo();
  virtual void PostFoo();
}

Likewise, where you find yourself doing this in subclasses:

class Sub : Base
{
  virtual void Foo() {
    // Do my extra stuff, then
    super.Foo();
  }
}

A better design (for Base) might have been:

class Base
{
  void Foo(); // Foo calls PreFoo(), then does Base work
  virtual void PreFoo();
}

This better identifies in the base class what the safe/legitimate points of customisation are for sub classes.

See also: http://en.wikipedia.org/wiki/Template_method_pattern

@codemonkey_uk

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment