I've been thinking a lot lately about all of the complex business logic we have to handle at the company I work at. Sadly, we do the best we can in OO terms, much of the logic is dispersed and replicated across different applications.
Recently one of our older purchasing applications need some changes to the logic of starting an order in our system. At the same time, another developer was preparing requirements for allowing a 3rd party system to start an order over the same application. What was two page long method with logic for starting an order, now would have to bear the requirements of two different systems, our own and a 3rd party system.
While working with the monster of logic in this single method, I was thinking how horrible it's going to be to bolt in the 3rd party requirements. The developer working on the 3rd party requirements would have to probably: modify the current method, or choose the favorite practice of others-- cut'n'paste into a new method to handle 3rd party stuff. Both are ugly and don't help maintainability at all.
My solution was to refactor the method to use the chain of responsibility pattern. Basically, the request to start an order is passed through a series of rules until we can start an order. For our internal start order logic, a start order context is created and passed through steps A, B, C, D. For the 3rd party system, the start order context would be passed through E, B, C, F, D. Notice B, C, and D are reused and can be maintained in one spot for both flows.
You may be thinking that those shared steps could have just been represented as methods and coordinated by two different parent methods (one for internal logic, and one for 3rd party). This may work in many cases, but in our case, a rule may fire off a view to the user (such as selecting a ship to address for an order). When a rule would fire a user to a view, that rule would return a flag signaling the chain coordinator that a rule finished the processing for that request. Example, selecting a ship to would then fire the user back into the chain of rules from the start until the whole chain would finish and kick them out of the flow (being able to actually add line items).
It was a simple refactoring. I didn't attack it with hopes of creating a workflow system or anything, just a few simple classes and a couple interfaces. If the logic ever changes or needs to be modified, we can just add another rule to the chain.