Thursday, March 28, 2013

I is for...

I is for Interface Segregation Principle.

This principle states that nothing should be forced to depend on methods that it doesn't use.

To illustrate this suppose there were a humongous class that handled making sandwiches (humongous sandwiches?). Now, as everyone knows, there are many kinds of sandwiches. There are toasted ones, open-face ones, and even bread-less ones. And while I'm not here to judge each sandwich, the point is that there are many different sandwiches and they are not all made the same way. To have each sandwich hold a reference to how to make anything but itself is wasteful. The bread-less sandwiches, as the name implies, don't have bread, so why should they know how to toast a piece of it?

Instead, each sandwich should depend on a reference to a subset of the large sandwich making class. This means that changes to how toasted sandwiches are made doesn't affect the bread-less ones, unless they are somehow also being toasted. I don't know enough about the different kinds of sandwiches.

In my own code, the closest I can come to this is the responders in my http server. I know that I've used them before, but that's alright, I think. The responders implement a very small interface. In fact, there's only one method and it's called respond. That isn't the only method that each responder has though. Some of them require additional methods to process the request cleanly and avoid an overly large respond method.

If I had pushed those methods up into the responder interface, instead of keeping them in the responders that required them, I would have been in violation of this principle. The responders that didn't use those extra methods could have just returned null or done nothing, but that would have been an unexpected behavior for anything relying on my responder interface. I'm not sure what principles that violates, but it can't be a good thing to do.

Again, if you don't agree with my description of this principle, please let me know. Also, I'm hungry again.


No comments:

Post a Comment