Inheritance Anti-patterns

suggest change

Improper Inheritance

Let's say there are two classes, Foo and Bar. Foo has two features, Do1 and Do2. Bar needs to use Do1 from Foo, but it doesn’t need Do2, or it needs a feature that is equivalent to Do2 but does something completely different.

Bad way: make Do2() on Foo virtual then override it in Bar or just throw Exception in Bar for Do2()

public class Bar : Foo
{
    public override void Do2()
    {
        //Does something completely different that you would expect Foo to do
        //or simply throws new Exception 
    }
}

Good way

Take out Do1() from Foo and put it into new class Baz then inherit both Foo and Bar from Baz and implement Do2() separately

public class Baz
{
    public void Do1()
    {
        // magic
    }
}

public class Foo : Baz
{
    public void Do2()
    {
        // foo way
    }
}

public class Bar : Baz
{
    public void Do2()
    {
        // bar way or not have Do2 at all
    }
}

Now, why the first example is bad and the second is good: when another developer changes Foo, that change can break Bar because Bar is inseparable from Foo. In the latter example, what Foo and Bar have in common has been moved to Baz, and they do not affect each other (as they shouldn’t).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents