Clean Architecture – Should Users Be in the Use Case Layer or Domain Layer?

Architectureclean codedomain-model

I recently read this article about Clean Architecture, as I'm trying to get out of some usual OO habits (interface design everywhere, but what does it do???), and program something that describes what the system does instead of how the system is built (to paraphrase "Uncle" Bob).

Once that article gets to the use case layer, the author mentions he left users until that layer because users are specific to the application, then makes a reference (that I really don't think I got) to how if it were a board game it wouldn't have users, but it would still have all the domain objects, in his case orders and products.

But the way I see it, in a web app (some light SaaS) users are part of the domain. Imagine a cloud document store like Dropbox: they store documents, so it seems a document is definitely a domain object. But they also have users don't they? Their business involves storing documents for users, and without users wouldn't that violate an aspect of their business?

I just don't get why users aren't considered part of the system in the same way documents or other things are. Can someone clarify this principle and the reasons behind it for me?

Best Answer

The author makes the distinction between what is in the "board game" or not with the following example:

eBay the website and eBay the board game both need buyers, sellers, items, and bids – but only eBay the website needs users, sessions, cookies, login/logout etc.

See how he mentions "buyers" and "sellers"? These are just different names for "users", but put in the context of the business.

The main point of the separation is that your business model (or as Uncle Bob puts it, "application agnostic business rules") do not need to know about the current user's authentication and authorization methods, or that it has a password, or uses Facebook or Google. Back to the eBay example, the business only needs to know that, in the context of the Order X, user Y is the buyer while user Z is the seller. This is what's important to make the business run - this is what the application does.

Always remember that the idea is to make the business rules completely agnostic of the delivery mechanism. You may have Users as part of your business model, there is nothing bad about it - Dropbox certainly needs, as you pointed out. But be sure to strip away anything related to how the user interacts with the system. This level of detail can be dealt with mostly by the delivery mechanism, and in some part by the application-specific business rules.

For instance, in some apps I've made, I check the user's authorizations within my use-cases, but the authentication methods are decoupled as plugins to be implemented from outside the applications. This has allowed me to easily add login options such as Faceebok, Twitter and Google, without affecting the structure of the applications.