Hi @android10,
I have a couple of questions regarding how to pass an object from the presentation layer to the domain layer and then to the data layer.
I have a use case when a user signs up within my app.
This is the interface (in the domain layer) between the domain and the data layer:
java
public interface UserRepository {
//The User class belongs to the Domain Layer
Observable<User> signUp(User user);
}
...and this is the UseCase subclass:
``` java
public class SignUpUseCase extends UseCase {
// Members set up in the SignUpUseCase constructor
private User user;
private UserRepository userRepository;
@Override
protected Observable buildUseCaseObservable() {
return userRepository.signUp(user);
}
}
```
Now, in the data layer, the implementation of the UserRepository interface (of the domain layer) is defined as follows:
``` java
public class UserDataRepository implements UserRepository {
private final UserEntityDataMapper userEntityDataMapper;
public Observable<User> signUp(User user){
final UserDataStore userDataStore = userDataStoreFactory.createCloudDataStore();
// Declared variable to make this code easier to read
UserEntity transformedUserEntity = userEntityDataMapper.transform(user)
return userDataStore.signUp(transformedUserEntity)
.map(userEntity -> this.userEntityDataMapper.transform(userEntity));
}
}
```
This takes me to define 2 methods in the UserEntityDataMapper class as follows:
``` java
public User transform(UserEntity userEntity) {
...
}
public UserEntity transform(User user) {
...
}
```
**Is this a correct implementation on how to pass objects from the domain to the data layer?**
For the SignUpUseCase use case, I need a User (defined in the domain layer) to be supplied via it's constructor in the UserModule.
``` java
@Module
public class UserModule {
//The UserModel class belongs to the Presentation Layer
private UserModel userModel;
@Provides
@PerActivity
@Named("signUp")
UseCase provideSignUpUseCase(UserRepository userRepository, ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread){
return new SignUpUseCase(userModel, userRepository, threadExecutor, postExecutionThread);
}
}
```
But then, I'd need a User mapper to transform a UserModel (defined in the presentation layer) to a User (defined in the domain layer)
Where should I place this User mapper, in the UserModule or in the SignUpUseCase class?
This is correct, Data receives an object from Domain and maps it to whatever Entity the data implementation expects.
If I am reading it correctly, UserModule is the Dagger Injection Module for the User scope, so you should not hold instances of other classes in that UserModule. It exists purely to provide instances to inject.
You are not obliged to keep to the protected Observable buildUseCaseObservable() format, since this makes it hard to use when you have dynamic objects that need to be passed to a UseCase. What i would do is have a method which takes a User from the Presentation Layer and have a UserMapper declared in the Presentation Layer which would transform the UserModel to a User and pass that on to the Domain Layer.
So the flow would be
Presentation layer
UserModelUserModel is passed to a mapper to convert it to a UserSignUpUseCase.signUp(user) is calledDomain layer
SignUpUseCase receives the User UserModel to User and passes it to your ServiceData layer
UserService receives the UserUser is used to sign up in the cloud via the ServiceSignUpUseCase is notifiedDomain layer
SignUpUseCase processes the result and applies any business logic (let's assume the signup was a success)User locally, so we pass it to the UserRepositoryData layer
UserRepository receives the processed UserUser is transformed to UserEntity ( this could be implementation specific )UserEntity is saved locally in cache to be retrieved later.edit was to reflect remark from @lalongooo made below.
Thanks @Trikke , I'll give it a try later today and let you know the results.
@lalongooo I have made an example for your need. Hope giving you some help. #55
@johnwatsondev It's a nice approach when passing a couple of params, but...what if you need to pass an object with a lot of properties/members..?
@Trikke If I let the SignUpUseCase to receive the Usermodel...wouldn't this be breaking the dependency rule?
I mean, the domain layer would be depending on a class of the presentation layer.

@lalongooo yes, i have made a mistake as was a bit too quick and forgot about the boundaries. In the Presentation Layer, you could have a mapper (something like UserModelMapper), which takes a UserModel from the Presenter and maps it to a User which the Domain will understand. This User is then passed as an argument to the UseCase. This way the Domain doesn't know about the data from Presentation, which is correctly converted at the boundary.
I'll adjust my comment above to reflect your correct remark.
@Trikke @lalongooo @android10 Hi everyone, IMO the implementation doesn't need the UserModel (Presentation layer) and it's mapper. The dependency rule states that nothing in an inner circle can know anything at all about something in an outer circle, but, the opposite is possible. I think it's possible to call the User (Domain layer) inside the presentation layer.
Plus, the UserModel and User have the same attributes. Technically, it's a dupicate and this is a violation of DRY. please correct me if i'm wrong.
The only thing I would add here is that a UserRepository should not know anything about signing up users, it is a repository and its responsibility is to work with data sources. The login process is part of your domain and the repository will "save" user session.
I think the UserModel and mapper is mechanical and dogmatic. If the user's data has changed(eg: add age attribute), you must change your user(UserMode-Presentation、User-Domain、UserEntity-Data) and its mapper in three layers,its unacceptable!
In MVP pattren, the model is an interface defining the data to be displayed or otherwise acted upon in the user interface. (Considering the layered architecture) Model is the embodiment of the data and business, and from the next layer of dependence. We can make it simple and dependency rules are correct, not so many template code(“user” and its "mapper").
@android10 You mean with "save" user session the request to the cloud but the domain model would create for example the preferences session for the user (login process)
@spirosoik yes. My comment was mostly a naming convention. A repository abstracts the origin of your data and should not know anything about login any user :)
@android10 exactly. Thanks great :+1: . By the way frodo rocks
@spirosoik :smile: Thank you!
@spirosoik I would like to add that the repository pattern uses a metaphor of a Collection. When it comes to naming conventions, use add/remove/etc. methods. It's like you're dealing with a Collection.
Never pass id as int because this is not DAO, pass an object instead.
@RamiJemli Yes I am following the same.
@RamiJemli @spirosoik I probably understand this abstract strategy.
So the data layer method will not same as domain layer method naming.
Never pass id as int because this is not DAO, pass an object instead.
Your meaning is data layer never know the param's logic meaning. So id is not always int.
It will clarify if there is a sample of this topic about _User Login Process_.
Thanks for giving advice.
@johnwatsondev
The flow on the topic about "User Login Process" ( or any other action on an external service) is very broad depending on implementation requirements, but usually boils down to something like this :
As @android10 remarked, the Repository pattern is just a way to abstract data/loading saving. So we need a separate Service ( or Service Agent ) to implement the logic for "User Login" (usually, talk to an api and get a response back). Where this Service should exists largely depends on your architecture, but in this github repository, i'd wager to just put it in the Data Layer. And then the following generalisation happens :
Domain layer
SignUpUseCase receives the User UserModel to User and passes it to your ServiceData layer
UserService receives the UserUser is used to sign up in the cloud via the ServiceSignUpUseCase is notifiedDomain layer
SignUpUseCase processes the result and applies any business logic (let's assume the signup was a success)User locally, so we pass it to the UserRepositoryData layer
UserRepository receives the processed UserUser is transformed to UserEntity ( this could be implementation specific )UserEntity is saved locally in cache to be retrieved later.@johnwatsondev I absolutely agree. Basically in this resository Service (API) is coupled with data layer as a CloudDatastore.
@Trikke Thanks for your comment! Is is really helpful and clear.
@android10 what do you think about @zhengxiaopeng 's comment? Even when you have said...
It is worth mentioning that each layer uses its own data model so this independence can be reached (you will see in code that a data mapper is needed in order to accomplish data transformation, a price to be paid if you do not want to cross the use of your models over the entire application).
Here is an schema so you can see how it looks like:
@zhengxiaopeng what is your solution then?
@android10 :-) I am cognizing this question. The following is my view now:
"The models are likely just data structures that are passed from the controllers to the use cases, and then back from the use cases to the presenters and views." - The Clean Architecture, and Request model、Response model - Robert C Martin - Clean Architecture(42:46). So, remove the user's classes in presentation layer and then put them into domain layer. Mostly, one user model is enough.Other reference:
Entity Translator
Using the Entity Framework in n-Tier Client-Side Applications
Using the Entity Framework in n-Tier ASP.NET Applications
mobile application development architecture
I'm a strong believer of having View Models and each layer should have its model to deal with. So I avoid coupling between layers. If you share Domain models with UI models, you are breaking the dependency rule because Domain knowing something about outer layers in the circle:

You will have to make changes anyway when adding new information to your UI.
Alright, I agree the dependency rule. I want to add that we(Android Dev) are just writing a single application, we don't have Front-end developer and Backend developer and so on. All codes(layers) are transparent to us。
@zhengxiaopeng I agree with you. @android10 Your great work got me interested in Clean architechture, so i looked deeper into this. When you call the domain model inside the presentation layer, it's the outer circle knowing something about the inner circle. This doesn't violate the dependency rule, but the opposite does.
@RamiJemli yup
Hello,
I don't if my question should be asked here (tell me if I'm wrong). My question is about using _dynamic parameters_ in a use case, like @lalongooo I have a SignUpUseCase, and this use case need user's email and password.
If I take UserModule that have the responsibility to create GetUserDetails an Id is needed to get a specific user, And this Id is specified when UserModule is created.
private void initializeInjector() {
this.userComponent = DaggerUserComponent.builder()
.applicationComponent(getApplicationComponent())
.activityModule(getActivityModule())
.userModule(new UserModule(this.userId))
.build();
}
In my case when SignModule is created I don't already know the user's password and email, so I can't pass it through the constructor.
So how can I proceed to pass, user's email and password to my use case when the user hit the button create an account ?
This may help you @MehdiChouag https://github.com/android10/Android-CleanArchitecture/issues/32
I'll take a look at this thank you :smile:
I had a really interesting conversation around this no long ago. I can give you an example where having mappers everywhere might not be totally correct approach.
The case is that we were working with a HATEOS type of backend on which the urls are not constructed by you, but the data flows and hrefs from where to retrieve data are given to you by the backend instead. Now the question boiled down to the following:
Imagine you only have knowledge of a single entry point to retrieve a master JSON file which contains links to perform different actions like login, register, fetch home or what ever. Imagine a case where due to a certain action of the user on an item (which remember, the collection URL was given to you by the backend previously), you want to display a full blown details page for the item selected. You have no idea how to construct the url but the URL has been given to you in the item response as a "self" attribute. You have 3 options as I see it:
I don't have a strong opinion between 1 and 2 but definitely is a problem we had to approach.
Comments/suggestions?
What do you do when you have domain specific data? For example domain level entities have some metadata, while UI level does not need it. How do you save that metadata to be able recreate entity from UI level model?
Very interesting things going here.
Although this started a couple of years ago, I hope that some of you will comment on this:
What do you thing of making the DomainUser extends DataUser, and the PresentationUser extends DomainUser. Like this the Domain Layer can add more fields and functionalities without the Data Layer knowing about these additions. Also, the Presentation Layer will add functionalities and the Domain Layer will not know about them. This will not break the Clean dependency rule as inner layers are not aware the extends made by outer layers.
@lbensaad yes it would be breaking the dependency rule. DomainUser should not know about DataUser.
@ghost I have tried all three options you have mentioned! And I realized 2 is the simplest way. but that still has problems...according to bob's clean architecture, we must create a response model for presenter not DomainModel itself. And we must not send DomainModel to UseCase but Request model...so yea...
Most helpful comment
This is correct, Data receives an object from Domain and maps it to whatever Entity the data implementation expects.
If I am reading it correctly,
UserModuleis the Dagger Injection Module for the User scope, so you should not hold instances of other classes in thatUserModule. It exists purely to provide instances to inject.You are not obliged to keep to the
protected Observable buildUseCaseObservable()format, since this makes it hard to use when you have dynamic objects that need to be passed to a UseCase. What i would do is have a method which takes aUserfrom the Presentation Layer and have aUserMapperdeclared in the Presentation Layer which would transform theUserModelto aUserand pass that on to the Domain Layer.So the flow would be
Presentation layer
UserModelUserModelis passed to a mapper to convert it to aUserSignUpUseCase.signUp(user)is calledDomain layer
SignUpUseCasereceives theUserUserModeltoUserand passes it to your ServiceData layer
UserServicereceives theUserUseris used to sign up in the cloud via the ServiceSignUpUseCaseis notifiedDomain layer
SignUpUseCaseprocesses the result and applies any business logic (let's assume the signup was a success)Userlocally, so we pass it to theUserRepositoryData layer
UserRepositoryreceives the processedUserUseris transformed toUserEntity( this could be implementation specific )UserEntityis saved locally in cache to be retrieved later.I hope this helps a bit.
edit was to reflect remark from @lalongooo made below.