The Interface Segregation Principle is an incredibly useful and powerful principle of software design. The ISP basically says that you should keep relatively lightweight interfaces so that when a person implements them in order to hook into your system, they do not need to implement tons of methods that aren't relevant to their class. I usually try to have no more than five functions on an interface - that's just a rule of thumb, but I find it to be a useful one.
But it's also very important to remember that, like all principles, it can be taken too far and make your life a living hell.
In particular, the interfaces should still be large enough to define the appropriate functionality that is being replaced. If you go further than that, putting each function and/or property into its own interface, then you have the opposite problem from the ISP occurring: Implementers who want to change how your system works will likely not be able to tell which interfaces have to be implemented in order to provide a given functionality. This is especially true if you've shunned type-safety and used object/dynamic throughout your system.
Some people try to solve the above problem by building up their interfaces into one unified interface that has all of the functions/properties required. This leads to other problems, though. When I decide to use an interface, I always ask myself this question: Do I have some way in the system (at all) to change where/how that interface is instantiated, and do I have a reference explicitly to that interface anywhere that would make switching the underlying implementation useful? If that point of extensibility doesn't exist, then having an interface around it is actually not really that good of an idea. With that in mind, if you have no way to actually change which underlying implementation is used, or if you don't even have any references to an interface except in an inheritance chain, I think we can safely say that that interface is likely unnecessary.
What do you think? Do you agree? Leave some feedback.
Tuesday, January 11, 2011
Stardate 2011.11.1: Interface Segregation Principle vs Common Sense
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment