Wednesday, March 27, 2013

O is for...

O is for Open/Closed Principle.

This principle states that classes, modules, functions, etc. should be "open for extension, but closed for modification." In order to add new functionality to the software, one should not have to change the existing code. One should only need to add the new code with the desired functionality.

One way this principle manifests is with interfaces. Defining an interface and using that, instead of the implementations directly, allows the code that uses the interface to remain unchanged when new implementations are added. This is much easier to visualize in Java, where interfaces are explicitly defined, than in Ruby.

An example of where I have used this principle in my code is in the responders in my Java http server. Credit must go to Rick for our talk that moved me in this direction. In my server, there is a responder interface that defines a single respond method, which all responders must implement. The respond method takes in a request and returns a response. Each responder processes the requests differently. This allows me to have a FileSystemResponder, a RedirectResponder, or any kind of responder I want.

Adding these new responders does not change my existing code. The code depends on the responder interface and, as long as that interface doesn't change, my code doesn't care what kind of new responder I add. Because of this, my server can be made to respond in a new way with relatively little work. If I didn't use the interface, then my server might be limited to responding in a single way or require code changes for every responder.

Following this principle has made my server much more flexible and easily extendable.


No comments:

Post a Comment