vendredi 29 janvier 2021

DDD - Conditional business rules without a domain service

Suppose you have a simple aggregate root like this:

Playlist {
  String name
  List<Song> songs

  add(Song song) {
    // Some business rules

    songs.add(song)
  }
}

Now suppose you want to introduce a business rule in the add(Song) method that depends on other aggregate roots. For example: A song may not appear in more than 3 playlists. One way to do this would be to fetch this information (number of playlists containing the song) in the application layer and pass it to the add(Song) method.

But now suppose furthermore that this business rule only applies under certain conditions. Imagine for example that playlists whose name starts with "M" don't have such limitation (completely arbitrary). Now fetching the information at the application layer would mean either implementing domain logic at the wrong level, or fetching data that you won't use. As business rules become more complicated this becomes more costly.

Now the obvious solution is: Use a domain service that has access to the Playlist repository and do your logic there. While this works, I was wondering if there is any pattern/architectural tip/reorganization that could be done to solve this problem without using a service to encapsulate the logic?

Thanks

Aucun commentaire:

Enregistrer un commentaire