Is "If a method is re-used without changes, put the method in a base class, else create an interface" a good rule-of-thumb?

Posted by exizt on Programmers See other posts from Programmers or by exizt
Published on 2013-11-12T20:05:15Z Indexed on 2013/11/12 22:02 UTC
Read the original article Hit count: 124

A colleague of mine came up with a rule-of-thumb for choosing between creating a base class or an interface.

He says:

Imagine every new method that you are about to implement. For each of them, consider this: will this method be implemented by more than one class in exactly this form, without any change? If the answer is "yes", create a base class. In every other situation, create an interface.

For example:

Consider the classes cat and dog, which extend the class mammal and have a single method pet(). We then add the class alligator, which doesn't extend anything and has a single method slither().

Now, we want to add an eat() method to all of them.

If the implementation of eat() method will be exactly the same for cat, dog and alligator, we should create a base class (let's say, animal), which implements this method.

However, if it's implementation in alligator differs in the slightest way, we should create an IEat interface and make mammal and alligator implement it.

He insists that this method covers all cases, but it seems like over-simplification to me.

Is it worth following this rule-of-thumb?

© Programmers or respective owner

Related posts about object-oriented

Related posts about interfaces