Posts

Exploring the Visitor Design Pattern: A benchmark of the pattern and its alternatives

Image
The Visitor is one of those underrated Design Patterns I wish I’d see more often. I mean, if you’ve been coding for a while, surely you have come across this abomination and thought there must be a better way: 1 2 3 4 5 6 7 8 9 if (instance is ChildClassA childA) { // Do some stuff specific to class A } else if (instance is ChildClassB childB) { // Do some stuff specific to class B } // Repeat for as many classes as you have Well, there is! And it’s called the Visitor Design Pattern! I won’t explain here how to use that pattern since that’s not the purpose of this article. But should you want to find out more on the visitor, I recommend you check out this article . Like all patterns, the visitor has some pros and some cons: Pros: Adding new behaviours to a class hierarchy is a breeze and doesn’t require to modify the hierarchy. If you are a fan of the Open/Closed Principle , that’s a good thing. The same behaviours will end up in the same class...