Skip to main content

Layered Architecture

When our project start growing, eventually we end up where to put my code delima. It is quite hard organize the code if we are not careful.

This is when we can use well known three-tier architecture. It helps us to divide the codebase into three separate layers with clear distinctive responsibilities.


But why?

Before taking any architectural decision we better ask the question ourself. Why do we need to do this. It is all about simplification. End of the day we need not only a working system, but we need a highly maintainable system.
Layer isolation gives us possibility to separate the concerns with clear responsibilities. But why, we can do our changes without inpacting other layers. Any new business requirement will have very small change. There will be zero breaking changes.
For an example we should never do any SQL operation in presentation layer.

  • We can build, deploy our layers separately.


Introducing our layers

  • Presentation layer - represents user interface.
  • Business logic layer - all business logics.
  • Persistance layer - handle database operations.



Pay special attention to data flow. Each layer could only call the layer below it.

Now we can put layer related logic only in that layer. For example we do not put user interface related code in business layer.


  • In a typical N-tier architecture you have any number of layers as you want.

  • It is about maintainable organized code.

Presentation layer

This is where we handle all the things related to user interface. In a typical Spring application we put Controllers here. And also, all MVC operations will be handled in this layer.


Business layer

All our business logic is implemented here. Our presentation layer call this as necessary. Business layer will call presistence layer to get data from database and do all the calculations.


Persistence layer

This is where we add our database operations. This contains all the classes required to handle database operations. We will have our entities, repositories and any other custom SQL in this layer.

As in any practise, 3-tier architecture also has many benefits as well as some drawbacks.


Benefits


  • Separation of concerns - we have clear separation between layers. 
  • Simplicity - Flow is simple.
  • Easy development - because of above, development is easy.


Drawbacks


  • Hidden use cases - most of the time we will add our logics in services which will hide many use cases.
  • High coupling - a layer is always depending on the layer below it. 
  • Not scalable - there is no clear separation between business modules.


Selecting an architecture style will depend on your project needs. For a simple CRUD like appliacations this will be a fine fit.
However when the business needs are growing, we better apply DDD principles.