Why avoid sharing models between architectural layers?

Kiran Bablani
3 min readJan 27, 2023

--

First of all, let’s talk a little bit about Clean Architecture.
Clean architecture is a way of separating different layers concerning their responsibilities and functionalities. This mainly consists of 3 layers

  • Presentation Layer
  • Domain Layer
  • Data Layer

Now, whenever we are defining these layers we also use the Models. Defining models is easy once you structure the data contained in those models precisely. You might share the same model among all the layers.

It is easier that way, same data all across. Now let’s consider some scenarios and validate if it still stands correct.
Let’s take a problem statement where we fetch employee data and display them in a list. So our abstract layers would look like

It is simple enough and would work for the scenario we are considering. Let’s build over some simple use cases.

  • What if we were to add one more field to our data class like ‘position_level’? This means now we have to update the model and its consumption all inside the application.
  • Let us assume we have to show the employee's name and salary in the list. To show the full name we must be writing logic like :

name_textview.text = “${model.firstName} ${model.lastName}”

Now, what if the new model would return fullName instead of separate firstName and lastName? This would break the presentation logic.

  • What if we were to perform some calculations on the salary(eg: adding bonus) of employees and display the newly calculated salary? Now we have to have one more property as “newSalary”. Isn’t it going to populate more and more of the model and add fields that may not be required in a particular layer?
  • What if I want to add the model to local database. I have to mark it as Entity. Now the model is connected to Android Component as well and goes well from data layer up to UI layer. This same case goes for if you want to annotate any field or maybe whole model.
  • What if we were to add a way to select/deselect an employee? Do we add a selected flag to it again and model grows in complexity ?

The more the conditions the more complex the model becomes and hence difficult to manage and track updates.

To resolve this what if we create models as

Now we have different models for different layers but how do we use them?
Well, obviously we need some kind of transformer to transform one input into another output.

The benefit of transformers is that it is easily testable on how you apply operations on input and get the expected output.

The advantage of having models dedicated to each layer provides flexibility. It provides a clear layer of separation between the responsibilities of each component. It also reduces dependency on a single model hence easy to update.

Pretty neat, isn’t it?

Suggestions are always invited!! Happy Coding

--

--