Another fundemental principle of object-oriented software design is the Open-Closed Principle. According to Uncle Bob (Robert Martin), this principle states that:

Software entities (classes, modules, functions, etc.) should be
open for extension, but closed for modification.

Essentially, 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:

[sourcecode] public abstract class Account
{
public abstract void Deposit(double amount);
}

public class CheckingAccount : Account
{
private double _currentBalance;

public override void Deposit(double amount)
{
_currentBalance += amount;
}
}

public class MortgageAccount : Account
{
private double _currentBalance;

public override void Deposit(double amount)
{
_currentBalance -= amount;
}
}

public class Bank
{
public void ReceiveMoney(Account account, double amount)
{
account.Deposit(amount);
}
}

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.

Post a Comment

Be the First to Comment!

wpDiscuz