architecturedomain-driven-designapi-designclean-architectureuse-case

Handling Multiple Actors in a Use Case in Clean Architecture and DDD


I am doing an API for a blog site using Clean Architecture and DDD. I find myself doing a use case to get all comments for a requested article. The thing is that anonymous users can see the comments but not do any action on them like editing, liking, etc. I just realized that this is more than one actor for the same use case--public (unauthenticated) and authenticated. Should I do two different use cases for getting the comments? SRP suggests me that YES. However, since I have not being here before, I would appreciate feedback on good strategies for managing such scenarios effectively.


Solution

  • SRP suggests me that YES

    First thing when thinking about design patterns and principles to remember is that they are general guidelines, which could be applied (with care) to a specific problem. In this case one might say that 2 use cases is not enough - you might consider making a use case per action (get comments, edit comment, like comment, etc.). Or two can be considered too many, if by "reason" (from "class should have only one reason to change") you will consider the rules of working with comments.

    Should I do two different use cases for getting the comments?

    Personally I would split the use cases by functionality i.e the already mentioned get comments, edit comment, like comment, etc. But it is greatly depends on the business rules and how they can change. For example in future you might want to allow anonymous users to like the comments (for example using some identification rule based on cookies/ips etc.). Or you will have different roles which will allow you different management capabilities for the comments (i.e. user can edit/delete his own comments, moderator can delete any comment, admin can edit and delete comments etc). Creating a separate use case for any combination of allowed actions can make maintaining code and architecture cumbersome (note that single use case solves this particular problem too).

    Also check out this answer:

    The consequence is that Clean architecture use-cases tend to be more granular than traditional use-cases. They correspond to elementary business functionality at "function" or "sub-function" level (e.g. "find a customer", "find an order", "invoice order") whereas the goal-oriented use-case analysis tends to describe higher level user objectives ("Invoicing customers"). But it's mainly a matter of level of details.

    Also this blog post might be an interesting read.