Note that there are some explanatory texts on larger screens.

plurals
  1. POWhen to use interfaces or abstract classes? When to use both?
    primarykey
    data
    text
    <p>While certain guidelines state that you should use an interface when you want to define a contract for a class where inheritance is not clear (<code>IDomesticated</code>) and inheritance when the class is an extension of another (<code>Cat : Mammal</code>, <code>Snake : Reptile</code>), there are cases when (in my opinion) these guidelines enter a gray area.</p> <p>For example, say my implementation was <code>Cat : Pet</code>. <code>Pet</code> is an abstract class. Should that be expanded to <code>Cat : Mammal, IDomesticated</code> where <code>Mammal</code> is an abstract class and <code>IDomesticated</code> is an interface? Or am I in conflict with the <a href="http://en.wikipedia.org/wiki/KISS_principle" rel="nofollow noreferrer">KISS</a>/<a href="http://en.wikipedia.org/wiki/YAGNI" rel="nofollow noreferrer">YAGNI</a> principles (even though I'm not sure whether there will be a <code>Wolf</code> class in the future, which would not be able to inherit from <code>Pet</code>)?</p> <p>Moving away from the metaphorical <code>Cat</code>s and <code>Pet</code>s, let's say I have some classes that represent sources for incoming data. They all need to implement the same base somehow. I could implement some generic code in an abstract <code>Source</code> class and inherit from it. I could also just make an <code>ISource</code> interface (which feels more "right" to me) and re-implement the generic code in each class (which is less intuitive). Finally, I could "have the cake and eat it" by making both the abstract class and the interface. What's best?</p> <p>These two cases bring up points for using only an abstract class, only an interface and using both an abstract class and an interface. Are these all valid choices, or are there "rules" for when one should be used over another?</p> <hr> <p>I'd like to clarify that by "using both an abstract class and an interface" that includes the case when they essentially represent the same thing (<code>Source</code> and <code>ISource</code> both have the same members), but the class adds generic functionality while the interface specifies the contract.</p> <p>Also worth noting is that this question is mostly for languages that do not support multiple inheritance (such as .NET and Java).</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload