2 ms·
That's one useful case, but the primary use case is keeping your code clean. If it isn't keeping your code cleaner, you're probably doing it wrong. Serializat
by bunderbunder 14y ago
That's one useful case, but the primary use case is keeping your code clean. If it isn't keeping your code cleaner, you're probably doing it wrong.
Serialization, for example, is a spot where the visitor pattern is useful. Take the example of a fairly complex hierarchical document - maybe something like a Word document. You need to support being able to save it to a whole bunch of different formats, and you want to do it as simply as possible.
- Hard-coding the save functionality for every possible format into the document classes themselves would be a mess, and would quickly pollute the data structures with a whole bunch of clutter. That violates the single-responsibility principle.
- Writing completely independent serializers for each format would be somewhat cleaner, but the serializers would end up containing a mess of repetitive code. That violates the DRY principle.
The Visitor pattern is nothing more complicated than a way to keep the code cleaner and more maintainable by factoring all the common elements of the task (saving, in this case), so that your code doesn't end up littered with a bunch of unmaintainable copypasting.
This shouldn't be anywhere near as difficult as what the grandparent suggests. In an object-oriented language, just create an abstract "DocumentSaver" class that has concrete implementations of all the common stuff, and abstract methods for all of the stuff that needs to be different for each file format. Then create subclasses for each of the save formats and voila, you're done.
I think the grandparent is absolutely correct that this is a pattern that is probably unnecessary in a language with algebraic data types and pattern matching. But to say that this means a pattern like Visitor is therefore a hallmark of being a bad programmer is unfair, if not downright risible. Most of us work in mainstream languages - and mainstream languages just don't have those features. For us, Visitor is an easy idiom for reclaiming some of the benefits of that functionality. And frankly, it should barely take more code to whip up a Visitor than it takes to pattern match your way through the problem.