Search This Blog

Friday, August 24, 2012

Interfaces, Abstract classes and Implementations

Usually you create class hierarchies like this in order to prepare for future changes:

interface -> abstract class with some implementation -> fully usable class


but if you have only one class extending the abstract one you might get rid of the abstract class and use something like this:

(marker) interface -> implementing class

Why you should get rid of the abstract class:
  • less code to maintain
  • simpler hierarchy design
  • still have the interface to use when referencing implementing classes
  • should the time come for more implementations you can refactor your class but that time:
    • you will better know what to generalize and what not to
    • you will have used the interface so clients no need to be changed
    • you saved some time not creating middle classes

But remember this works only if you have clean, well-separated and easy to understand classes. If your class is so complex that takes weeks to understand then:
  • you should not have those kind of classes at the 1st place
  • but if you have, it's probably better to refactor while you're at it

It seems tempting to create fully generalized implementations but unfortunately you usually don't know how your classes will be used in the future, so skip it - if you can't at least wait for some time before doing so. Sadly I still fell sometimes :(

Of course, if you create a framework or 3rd party library there might be other factors limiting you choices so decide wisely.

More info:
http://www.codinghorror.com/blog/2004/10/kiss-and-yagni.html
http://en.wikipedia.org/wiki/You_ain't_gonna_need_it


No comments:

Post a Comment