DEV Community

John Peters
John Peters

Posted on • Updated on

Favor Composition over Inheritance

Short and simple:

Prefer this construct:

MainClass.SomeContainer.DoSomething();

To this:

MainClass.DoSomething();

Why? Because you can dump in as many SomeContainers as you want without affecting each other, if you adhere to the Single Responsibility rule.

The only time MainClass.DoSomething(); works is when MainClass does only one thing and DoSomething does something directly related to MainClass.

Follow the Single-responsibility rule as if your coding life depends on it! Never duplicate code, and while coding, continually ask yourself "is all this code doing only one thing?", if not; repeatedly split code into new functions that only do one thing.

Top comments (0)