Video in progress
What is the difference between package-by-layer and package-by-feature structures? Which one improves cohesion?
Package-by-layer splits code by technical layer (controller, service, repository), while package-by-feature splits it by business capability (order, payment, course). The feature structure increases cohesion and lets you hide classes that don't need to be public.
📖 Answer
By layer:
controller/ OrderController, UserController, CourseController ...
service/ OrderService, UserService, CourseService ...
repository/ OrderRepository, UserRepository ...
dto/ ... 80 files
A single "add a promo code to an order" feature is spread across four packages. All the classes have to be public, because they are called from other packages. As a result, CourseController can freely inject OrderRepository, and nothing stops it.
By feature:
order/ OrderController, OrderService, OrderRepository, Order, OrderDto
payment/ PaymentController, PaymentService, ...
course/ ...
What you gain:
- one change usually stays inside one package: high cohesion;
- the internal classes are package-private (
class OrderRepository), so other features see only the public methods ofOrderService, and coupling is low; - it is easy to split the package into a separate module or service later;
- a new developer finds the answer to "where is the order code?" right away.
What to watch for:
- if you draw the boundary between features wrongly, circular dependencies appear;
- for shared things (
config,security,common) you still need a separate place.
A hybrid is common too: feature at the top, layers inside (order/api, order/domain, order/infra). You can check the boundaries with Spring Modulith or ArchUnit, which forbid access to another module's internal package at the test level.
Sign up to mark studied questions and save your progress.