Changing Object Functionality in OOP Languages

Sunday, December 11, 2011

A while ago, I had a conversation with a coworker about the maintainability of code and objects aspects of software craftsmanship. Suppose I make a method and think it's perfect. Inevitably, this method will have to change its functionality, probably due to change in requirements. In cases like this, how should one approach this refactoring? I just came across the concept of the "open-closed" principle, conceived way back in 1988.
en.m.wikipedia.org/wiki/Open/closed_principle
I originally was influenced by the idea of immutable data structures, mostly due to listening to Rich Hickey praising them in his talks on Clojure and it's concepts. Immutable data structures are interesting because they can be shared among different methods and threads safely. Immutability helps remove any surprises caused by method/function side effects. Though I haven't run into this problem before, it's a bit very attractive concept because it encourages simplicity in reading and maintaining existing code. Simplicity is king in the land of software development.
The open-closed principle, on the other hand, promotes simplicity in method/API design by promising to not change the API and its implementation. This reduces the chance of creating bugs in the callers of your methods. If the implementation of a unit of code must change, the open-closed principle instructs us to subclass and override the unit of code we wish to change. This sounds great and makes our code immutable, in a sense, but it seems to be forgetting about about another core principle of programming, which is the wonderful typing system.
This improvement/customization to the open-closed principle occurred in the 1990s, according to wikipedia. The revised version of the principle instructs us to use interfaces or abstract classes and create new implementations of them, rather than directly subclassing the class to change. This is a much better solution, as interfaces are a more precise manner of expressing functionality and purpose of an object.
It may be a challenge, and but we should remember to use the tools that our languages provide us. We should remember to use interfaces where appropriate.

No comments:

Post a Comment