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: 152
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
anddog
, which extend the classmammal
and have a single methodpet()
. We then add the classalligator
, which doesn't extend anything and has a single methodslither()
.Now, we want to add an
eat()
method to all of them.If the implementation of
eat()
method will be exactly the same forcat
,dog
andalligator
, 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 anIEat
interface and makemammal
andalligator
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