Handling New Requirements
After writing this application, suppose I receive a new requirement to change the way I have to handle taxes. For example, now I have to be able to handle taxes on orders from customers outside the United States. At a minimum, I will need to add new rules for computing these taxes.
What approaches are available? How can I handle these new rules?
Before looking at this specific situation, allow me to take a slight detour. In general, what are ways for handling different implementations of tasks that are pretty much conceptually the same (such as handling different tax rules)? The following alternatives jump quickly to my mind:
- Copy and paste
- Switches or ifs on a variable specifying the case we have
- Use function pointers or delegates (a different one representing each case)
- Inheritance (make a derived class that does it the new way)
- Delegate the entire functionality to a new object
The old standby. I have something that works and need something close. So, just copy and paste and then make the changes. Of course, this leads to maintenance headaches because now there are two versions of the same code that I — or somebody else — has to maintain. I am ignoring the possibility of how to reuse objects. Certainly the company as a whole ends up with higher maintenance costs.
A reasonable approach. But one with serious problems for applications that need to grow over time. Consider the how coupling and testability are affected when one variable is used in several switches. For example, suppose I use the local variable myNation to identify the country that the customer is in. If the choices are just the United States and Canada, then using a switch probably works well. For example, I might have the following switches:
But what happens when there are more variations? For example, suppose I need to add Germany to the list of countries and also add language as a result. Now the code looks like this:
This still is not too bad, but notice how the switches are not quite as nice as they used to be. There are now fall-throughs. But eventually I may need to start adding variations within a case. Suddenly, things get bad in a hurry. For example, to add French in Quebec, my code looks like this:
The flow of the switches themselves becomes confusing. Hard to read. Hard to decipher. When a new case comes in, the programmer must find every place it can be involved (often finding all but one of them). I like to call this “switch creep.”
Function pointers in C++ and delegates in C# can be used to hide code in a nice, compact, cohesive function. However, function pointers/delegates cannot retain state on a per-object basis and therefore have limited use.
The new standby. More often than not, inheritance is used incorrectly and that gives it a bad reputation. There is nothing inherently wrong with inheritance (sorry for the pun). When used incorrectly, however, inheritance leads to brittle, rigid designs. The root cause of this misuse may lie with those who teach object-oriented principles.
When object-oriented design became mainstream, “reuse” was touted as being one of its primary advantages. To achieve “reuse,” it was taught that you just take something you already have and make slight modifications of it in the form of a derived class.4
In our tax example, I could attempt to reuse the existing SalesOrder object. I could treat new tax rules like a new kind of sales order, only with a different set of taxation rules. For example, for Canadian sales, I could derive a new class called CanadianSalesOrder from SalesOrder that would override the tax rules. I show this solution in Figure 9-2.
Figure 9-2 Sales order architecture for an e-commerce system.
The difficulty with this approach is that it works once but not necessarily twice. For example, when we have to handle Germany or get other things that are varying (for example, date format, language, freight rules), the inheritance hierarchy we are building will not easily handle the variations we have. Repeated specialization such as this will cause either the code not to be understandable or result in redundancy. This is a consistent complaint with object-oriented designs: Tall inheritance hierarchies eventually result from specialization techniques. Unfortunately, these are hard to understand (have weak cohesion), have redundancy, are hard to test, and have concepts coupled together. No wonder many people say object-orientation is overrated—especially since it all comes from following the common object-orientation mandate of “reuse.”
How could I approach this differently? Following the rules I stated earlier, attempt to “consider what should be variable in your design,” “encapsulate the concept that varies,” and (most importantly) “favor object-aggregation over class inheritance.”5
Following this approach, I should do the following:
- Find what varies and encapsulate it in a class of its own.
- Contain this class in another class.
In this example, I have already identified that the tax rules are varying. To encapsulate them would mean creating an abstract class that defines how to accomplish taxation conceptually, and then deriving concrete classes for each of the variations. In other words, I could create a CalcTax object that defines the interface to accomplish this task. I could then derive the specific versions needed. Figure 9-3 shows this.
Figure 9-3 Encapsulating tax rules.
Continuing on, I now use aggregation instead of inheritance. This means, instead of making different versions of sales orders (using inheritance), I will contain the variation with aggregation. That is, I will have one SalesOrder class and have it contain the CalcTax class to handle the variations. Figure 9-4 shows this.
Figure 9-4 Favoring aggregation over inheritance.
Example 9-1 Java Code Fragments: Implementing the Strategy Pattern
public class TaskController { public void process () { // this code is an emulation of a // processing task controller // . . . // figure out which country you are in CalcTax myTax; myTax= getTaxRulesForCountry(); SalesOrder mySO= new SalesOrder(); mySO.process( myTax); } private CalcTax getTaxRulesForCountry() { // In real life, get the tax rules based on // country you are in. You may have the // logic here or you may have it in a // configuration file // Here, just return a USTax so this // will compile. return new USTax(); } } public class SalesOrder { public void process (CalcTax taxToUse) { long itemNumber= 0; double price= 0; // given the tax object to use // . . . // calculate tax double tax= taxToUse.taxAmount( itemNumber, price); } } public abstract class CalcTax { abstract public double taxAmount( long itemSold, double price); } public class CanTax extends CalcTax { public double taxAmount( long itemSold, double price) { // in real life, figure out tax according to // the rules in Canada and return it // here, return 0 so this will compile return 0.0; } } public class USTax extends CalcTax { public double taxAmount( long itemSold, double price) { // in real life, figure out tax according to // the rules in the US and return it // here, return 0 so this will compile return 0.0; } }
I have defined a fairly generic interface for the CalcTax object. Presumably, I would have a Saleable class that defines saleable items (and how they are taxed). The SalesOrder object would give that to the CalcTax object, along with the quantity and price. This would be all the information the CalcTax object would need.
Another advantage of this approach is that cohesion has improved. Sales tax is handled in its own class. Another advantage is that as I get new tax requirements, I just need to derive a new class from CalcTax that implements them.
Finally, it becomes easier to shift responsibilities. For example, in the inheritance-based approach, I had to have the TaskController decide which type of SalesOrder to use. With the new structure, I can have either the TaskController do it or the SalesOrder do it. To have the SalesOrder do it, I would have some configuration object that would let it know which tax object to use (probably the same one the TaskController was using). Figure 9-5 shows this.
Figure 9-5 The SalesOrder object using Configuration to tell it which CalcTax to use.
Most people note that this approach also uses inheritance. This is true. However, it does it in a way different from just deriving a CanadianSalesOrder from SalesOrder. In the strict inheritance approach, I am using inheritance within SalesOrder to handle the variation. In the approach indicated by design patterns, I am using an object aggregation approach. (That is, SalesOrder contains a reference to the object that handles the function that is varying; that is, tax.) From the perspective of the SalesOrder (the class I am trying to extend), I am favoring aggregation over inheritance. How the contained class handles its variation is no concern of the SalesOrder.
One could ask, “Well, aren’t you just pushing the problem down the chain?” There are three parts to answering this question. First, yes I am. But doing so simplifies the bigger, more complicated program. Second, the original design captured many independent variables (tax, date format, and so on) in one class hierarchy (SalesOrder), whereas the new approach captures each of these variables in its own class hierarchy. This allows them to be independently extended. Finally, in the new approach, other pieces of the system can use (or test) these smaller operations independently of the SalesOrder. The bottom line is, the approach espoused by patterns will scale, whereas the original use of inheritance will not.
This approach allows the business rule to vary independently from the SalesOrder object that uses it. Note how this works well for current variations I have as well as any future ones that might come along. Essentially, this use of encapsulating an algorithm in an abstract class (CalcTax) and using one of them at a time interchangeably is the Strategy pattern.