Package by layer for Spring project is obsolete

twittergoogle_plusrss

Facebooktwittergoogle_plusredditlinkedinmail

I believe Spring application shouldn’t be structured in package by layer approach. In my opinion, package by feature makes much more sense.

First of all, let me describe each approach briefly.

“Package by layer” (“Folder by type” in non Java world)

This project structure groups source code files into packages/directories based on architecture layer they belong to:

.
└── net
    └── lkrnac
        └── blog
            ├── Application.java
            ├── persistence
            │   ├── ProjectRepository.java
            │   └── UserRepository.java
            ├── dto
            │   ├── ProjectDto.java
            │   └── UserDto.java
            ├── model
            │   ├── Project.java
            │   └── User.java
            ├── service
            │   ├── ProjectService.java
            │   └── UserService.java
            └── web
                ├── ProjectController.java
                └── UserController.java

“Package by feature” (“Folder by feature” in non Java world)

This approach on the other hand groups together files belonging to certain feature within the system:

.
└── net
    └── lkrnac
        └── blog
            ├── Application.java
            ├── project
            │   ├── ProjectController.java
            │   ├── ProjectDto.java
            │   ├── Project.java
            │   ├── ProjectRepository.java
            │   └── ProjectService.java
            └── user
                ├── UserController.java
                ├── UserDto.java
                ├── User.java
                ├── UserRepository.java
                └── UserService.java

Trends

This subject interested me for a long time.  When I google “package by layer” vs “package by feature” or “folder by type” vs “folder by feature”, there seem to be growing camp of proponents of “by feature” structure. I am in this camp too.

But not only application developers are proponents of it. Angular (one of the most prominent Single Page Application frameworks) is promoting such folder structure in their style guide.

Spring Project Structure

As there is plenty of reading about pros and cons of each approach out there, I will focus on implications for Spring project.

Traditional structure of laying down Spring CRUD applications (if your back-end application is not using Spring Data REST) is divided into 3 layers: web/service/persistence. Vast majority of Java/Spring projects I was working on followed this structure.

Coupling

Package by layer most probably originates in previous century, where layered architectures were used as decoupling mechanism. In fact “decoupling” was often the answer when I was challenging package by layer structure. I disagree. To me package by layer is one of the major reasons causing tight coupling.

When you are writing signature for class in package by layer structured project, what keyword is the first? I bet it is public. Does public access modifier help decoupling? I guess nobody would answer yes to this question.

Why developers are using public access modifier all over the place? It is exactly because the project is structured in by layer fashion. Repository class needs to be public, because it needs to be accessed from service package and service needs to be public because it needs to be accessed from web package. When everything is public, it is very hard to maintain the discipline which doesn’t lead to big ball of mud.

When using package by feature, package private UserRepository (it means no access modifier is specified) can’t be used by other service than UserService, because they are in same package. And if we decide that only UserController should use UserService, we just make it package private, because they share same package.  In such project structure most of the classes would be package private. Therefore developer should have very good reason to make class public.

Scaling

What happens if project starts to have 10+ classes in web/service/persistence layer? Developers tend to group classes into sub-packages. But how do they categorize them? From my experience, it is mostly based on features. So we can often find such structure in bigger projects:

.
└── net
    └── lkrnac
        └── blog
            ├── Application.java
            ├── dao
            │   ├── ...other repositories...
            │   ├── ProjectRepository.java
            │   └── user
            │       ├── UserRepository.java
            │       └── UserRoleRepository.java
            ├── dto
            │   ├── ...other DTOs...
            │   ├── ProjectDto.java
            │   └── user
            │       ├── UserDto.java
            │       └── UserRoleDto.java
            ├── model
            │   ├── ...other models...
            │   ├── Project.java
            │   └── user
            │       ├── User.java
            │       └── UserRole.java
            ├── service
            │   ├── ...other services...
            │   ├── ProjectService.java
            │   └── user
            │       ├── UserRoleService.java
            │       └── UserService.java
            └── web
                ├── ...other controllers...
                ├── ProjectController.java
                └── user
                    ├── UserController.java
                    └── UserRoleController.java

Isn’t this obvious madness?

Future proof-ness

As bunch of smart people suggest, it might not be good idea to start green field project with micro-services architecture. I agree. So it might be good idea to prepare your monolith for eventual separation into smaller projects if your application hits the growth.

Imagine you would need to extract micro-service from your monolith project. Or split whole project into micro-services. I hope everybody understands that no sane micro-services architecture is separated by architectural layers. Separation based on features is used. So which project structure will be easier to separate into micro-services? The one, where any public class can use any other public class from any package (package by layer)? Or one, separated into package private buckets (package by feature)? I believe the answer is obvious.

Conslusion

Package by feature is simple but very powerful mechanism for decoupling. So next time some layer obsessed developer will be defending package by layer project structure as decoupling mechanism, please correct her/his misunderstanding. I believe dinosaur-ness is the only reason why package by layer still exists nowadays.

twittergoogle_plusrss

6 thoughts on “Package by layer for Spring project is obsolete

  1. Nice article. Thanks. Simon Brown also talks about breaking down the layer approach in his talks. https://m.youtube.com/watch?v=0fSRadBepYk. My feeling is that many codebases have evolved this way from overly simplistic tutorials where breaking up by layer within the project has been used to demo different features rather than group by feature as you mention

  2. Bold claim, have you tried this using Jigsaw? Personally I do a “Package by module” which is both by layer, and by feature. Which allows me to … modularize? and compartmentalize dependencies. Hey, if you’re not concerned about someone writing a SQL query directly in a controller, or doing dependency inject of a service into an entity, that’s cool.

  3. Hi Lubos,

    Some time ago I wrote an article about the same topic in which I agree with most of what you write, however, it’s worth to mention that “Package by feature” isn’t the silver bullet as it also has its problems.

    For instance, based on my experience the issue of growing number of classes in a single package exists also in the “Package by feature” approach. You can start with the package private scope for feature’s classes, but when the feaure grows, you will consider creating a sub-package and then, unfortunately, you will have to make some classes public anyway.

    On the other hand, this is a more generic Java problem that from the access control point of view, there is no difference between a sub-package and just another package. Even with this limitation the “Package by feature” approach allows to greatly decrease the total number of public classes. It’s good to read the topic receives more attention.

    1. I agree with your insights. I solve such problem by identifying similar concerns (something like sub-feature) and extract package that way. One might be able to identify classes I can make package private and expose only few classes as API for that package. In fact I was able to do this in most such cases from what I remember.

      BTW, this post was re-posted on DZone and got a lot of attention there: https://dzone.com/articles/package-by-layer-for-spring-projects-is-obsolete

Leave a Reply

Your email address will not be published. Required fields are marked *