Thursday, 11 August 2011

Replace Conditional With Polymorphism Refactoring–A Wake-up Call

One of the aspects of good object oriented design that I keep seeing mentioned is to replace complex conditional statements with polymorphism the best known source of this probably being Martin Fowler's Refactoring. This is usually called out when seeing large case statements or stacks of ifs. I’ve always had a problem understanding how polymorphic behaviour would help here, but I think that is because the only time I’ve used much in the way of conditional stuff like that has been in places like just behind the UI layer when processing user input, so there isn’t really the chance to do anything polymorphic at that stage as things are just coming in to the system in the first place.

However, I recently inherited some complex business logic code that is chock full of ifs and cases. All of a sudden I can see where the potential for polymorphising it comes in. This code is absolutely mission critical, arguably the core of our business, and we currently have no unit test coverage whatsoever, and only minimal automated integration tests that certainly won’t be covering all of the edge cases. Add to that our legacy code issues of tightly coupled code and static methods, the facts that it does actually work and is suitably performant, plus medium term business plans to do a complete overhaul of the way that it all works, and I can’t see myself being in a position to do any major refactoring any time soon. But at last I have come across a great example of where that refactoring would apply, which also makes me feel more comfortable about the places that I’ve been tending to pile conditionals as being a valid use of them.

No comments:

Post a Comment