Spring is like onion - about layers

Spring has a lot of standards and share knowledge about good practice for using it. One of these is chop your application for layers.

Three layers of your application

The good practices tell us, we should create three or more layers of our enterprise application. Those layers are controllers, services and repositories. In my opinion, this is very good practices, because we are separate three things communication with client, business logic and communication with other systems. I think this is a reason why spring promote this solution. If you want a proof that spring prefer a layers take a look at the specific annotation for the components we have three predefined: @Service, @Controller and @Repository. This is the same like @Component, but we have a marker for that.

This is ok, but...

This is very problematic, when we use this solution without thinking. We can put all services in one package. A lot of tutorials do that. If you do that you will have a problem with relations between your components. We need separate our code per functionality, because if you have too many relations between your classes, your code will be unusable.

Summary, I prefer before create packages for layers, create upper that package with a functionality name like:

App
--buy
----controllers
----services
----repositories
----entities
--global
----functions
--sell
----controllers
----services
----repositories
----entities

This is easier for managing. Of course, if someone should use a service from another package, it is possible, but we never change systems to better without change us.

The solution for this problem is using ports and adapters architecture patterns, but this is a topic for another time.

Comments

Popular posts from this blog

Why TDD is bad practice?

How correctly imitate dependencies?

Software development using Angular 5 with Spring Boot