Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

5
  • 4
    Thank you. But, isn't such a solution more complex, unreadable and unmaintainable than the version with only an instanceof? Especially, if we assume the validation is something related to repository and its validation logic and not to the domain itself. Isn't the point of not using instanceof to improve readability and maintainability? Commented Aug 2, 2021 at 12:40
  • 2
    @Shayan If you just have one instanceof, I'd probably agree with you – the occasional “unclean” code is much better than an overcomplicated workaround. But the tricky aspect of an instanceof is that if you ever add another ParentEntity subclass, the instanceof check might no longer be correct. In contrast, the visitor pattern will prevent the code from compiling until the accept() method has been implemented. That safety can be valuable. Only you know what's best for your particular codebase – either alternative can be fine. Commented Aug 2, 2021 at 13:43
  • Good points. But is putting a void accept(EntityVisitor v); there which may be used for different purposes in different parts of the code base a good practice? From a logical perspective, in our domain, for example, does an Apple has an accept behavior? So, is it a good practice to put an accept for its corresponding class? Commented Aug 3, 2021 at 5:23
  • 1
    @Shayan The accept/Visitor boilerplate is not really entity behaviour, it is just boilerplate to make the entity's behaviour extensible. It is agnostic to what actual behaviour you'll route through it. In some languages this pattern is unnecessary, e.g. in Java 15 we could just use Sealed Classes in order to do instanceof safely. Should an Apple entity have an accept() method? Only if its part of the ParentEntity hierarchy that you want to make visitable. Commented Aug 3, 2021 at 11:06
  • Shayan: remember not to trust anyone who calls himself “uncle”. In other words, don’t take all this “clean” nonsense as gospel. Use your own brain. And if you use a modern language, like Swift, lots of his “clean” code looks very clumsy and outdated. Commented Aug 3, 2021 at 21:29