Refactoring code to avoid anti-pattern

I wouldn’t say that it’s an anti-pattern since an anti-pattern is supposed to be a pattern in the first place (a recognizable, widespread way of doing things) and I don’t know of any “Repository-in-the-Domain-object” pattern.

However, it’s certainly bad practice IMO because your BankAccount domain object mixes 3 responsibilities :

  • Its natural and legitimate responsibility as a Domain object to freeze itself and change its status.

  • The responsibility to update and submit changes to a persistent store (using the accountRepository).

  • The responsibility to decide how a message should be sent (in that case, an email) and send it.

As a result, your Domain object is tightly coupled to too many things, making it rigid and fragile. It could change and possibly break for too many reasons.

So no anti-pattern but a violation of the Single Responsibility Principle for sure.

The last 2 responsibilities should be moved to separate objects. Submitting changes rather belongs in an object that manages the business transaction (Unit of Work) and is aware of the right time to end the transaction and flush things. The second one could be placed in an EmailService in the Infrastructure layer. Ideally, the object that does the global Freeze operation shouldn’t be aware of the message delivery mechanism (by mail or something else) but should be injected with it instead, which would allow for more flexibility.

Leave a Comment