Question Refactor horrible nested loop advice

ColinMay80

Member
Joined
Sep 27, 2021
Messages
10
Programming Experience
3-5
Im refactoring some legacy code and came across a function which takes in a dictionary and an object to update. The method is in a base class and consists of nested For each loop and a switch with prob 10+ cases. Basically the outer loop iterates through the items and inner loop checks each item key. The switch statement checks for a given property on the passed in object and then updates it with the value in the case statement or calls another method to do it. This is definitely bad design and code smell. Whilst I usually use polymorphism to remove switch statements but I‘m wondering if I should as in this case. This base class method merely updates properties of a passed in object from a dictionary of values. Any suggestions for better OO design and more maintainable code?

thanks
 
Yes, apply polymorphism. You've identified the correct code smell and the appropriate way to address it. The cost of doing the polymorphism is usually code bloat, as well as a performance hit. On the other hand, developer time is supposedly more expensive than CPU or RAM nowadays, so more often than not, it's worth the cost to make things easier for the human to maintain, and harder for the machine to run. Even if you didn't go for a straight out Strategy pattern to try to solve this problem, and opted for using some kind of Visitor or Flyweight pattern, you would still end up needing some kind of common interface to expose the different cases, and that interface would be using polymorphism.
 
Last edited:
Back
Top Bottom