It is said that visitor pattern is applicable to problems where objects rarely change but we add actions on those objects more frequently.
What if the objects are changing too though? For example we might have a NotificationSource
class where it can have many children such as EmailNotificationSource
or SmsNotificationSource
or whatever. For any incoming messaging system we might want to add another source and extend our notification system.
We can imagine actions on these models or classes may add rapidly too. NotificationSerializer
or NotificationSender
or whatever functionality we might define on these classes to name a few.
Using switch-cases on each of these to find which NotificationSource
object we are deadling with is discouraged and I understand why. It's not much maintainable.
Visitor pattern is not working well too because I don't like a NotificationSender
class with endless methods for each child like handleSendingEmailNotification
. I don't like the idea of adding accept
method to each of the NotificationSource
child either. I feel like it's cheating and it violates SRP (And also what is we don't have access to NotificationSource
classes? Maybe it's a installed dependency.)
I don't have any scalable (on both children and actions) and maintainable solution to this problem. Can anyone help me with this?
I don't have any scalable (on both children and actions) and maintainable solution to this problem.
Maybe because you are skipping the main problem. Flawed abstraction inNotificationSource
. I say this because you already pointed thatUsing switch-cases on each of these to find which NotificationSource object we are dealing with is discouraged.
why do you have to check children's type? Why don't treat them all the same way? Then it replaces a switch with a loop. If for any reason you can'tNotificationSource
it's already violating SRP.send
method to eachNotificationSource
. Then we add aserialize
method to the same class with the same reason. Then we addrenderToString
. And so on. All of a sudden we have a class with so many unrelated behaviour violating the SRP principle. Am I right? @LaivAnd so on. All of a sudden we have a class with so many unrelated behaviours violating the SRP principle. Am I right?
yes, but encapsulating features into classes results in the same problem. It just decouples it. So, why do you needNotificationSource
capable of so many different things? Are these features configurable in runtime? What motivation took you to the Visitor pattern?