Skip to content

Instantly share code, notes, and snippets.

@codemonkey-uk
Last active August 29, 2015 14:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codemonkey-uk/8edab3ae727314b0f886 to your computer and use it in GitHub Desktop.
Save codemonkey-uk/8edab3ae727314b0f886 to your computer and use it in GitHub Desktop.

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