Friday, November 23, 2007

IThis, IThat, ITheOther

I have seen projects where every class had implemented an interface by default. The interfaces always had the same names as the classes except they were prefixed with an (I). I don't call this good design. The flexibility that an interface gives you has a cost. If an interface is not paying for this cost it should be removed. Only use interfaces when the flexibility is required. It is often difficult to tell in advance where this flexibility is needed so it is usually best to add an interface when the flexibility is required. Also instead of using the (I) prefix I prefer to name the interface by how the client will use the class. So instead of creating and IBook interface for a Book class, I could create a Readable interface instead. Removing the last trace of Hungarian notation from my code.

2 comments:

Chris Barrow said...

What about always programming to an interface or super type rather than a concrete implementation?

Are you suggesting not following this when it appears at first glance using an interface will cost more than the flexibility it provides?

Nick Markovic said...

Programming to an interface is good because it increases a program’s flexibility. However unnecessary flexibly only makes an application more complex. If you use BDUF (big design up front) you often find yourself guessing where that flexibility is needed.