Software entities (classes, modules, functions, etc.) should beEssentially, what this means is that software's design should be such that it's behavior can be modified by extending the existing source code rather than modifying it. Consider the following example: Notice that the ReceiveMoney() method of the Bank class has to determine the type of account passed in. Only based on that information it can perform the appropriate business logic. Later if we add another account type then we may need to modify this code in order for it to work properly. The above code is, hence, in violation of the Open-Closed principle. So how can we revise our code to conform to the Open-Closed Principle? Abstraction is the answer. Let's take a look: Notice how we got rid of all conditional logic in the ReceiveMoney() method. Also notice that if we later add a new account type, the ReceiveMoney() method will work without any modifications. The revised version of our code above, hence, conforms to the Open-Closed Principle. Let's now consider what happens to our code if a new business rule is added that requires an e-mail notification to be sent to the account holder whenever a deposit is made. Obviously, we'll have to modify the ReceiveMoney() method to perform that logic. Since we can't account for all possible scenarios, we can never acheive perfect closure. With that in mind, design the simplest software that will do the job, and conform to OCP or other such design principles where you see the need.
open for extension, but closed for modification.
Monday, August 21, 2006
OCP Open-Closed Principle
Another fundemental principle of object-oriented software design is the Open-Closed Principle. According to Uncle Bob (Robert Martin), this principle states that: