DEV Community

Discussion on: Why you should avoid package-private scope in Java

Collapse
 
darkknightpl profile image
Marcin Jarząbek • Edited

I don't think I'd agree with title statement - of course it's important to choose apropriate scope to specific case we're dealing with, but package scope is definetely being used too rarely.
Devs, left with choice either public or private tend to choose public to make things easier. But making class or method public it means it is part of your contract - functionality your package expose to other parts of code. If another part is using this class/method it's much harder to change/refactor it and code becomes tightly coupled.

An alternative is to make only one class in package public - and this class, facade, becomes your contract. All other classes can be package private. Then you test your package behaviour via facade class and refactoring is much easier.
Following this pattern makes also reading code easier - if you need only some functionality from package you only need to read facade class - and it's immediately visible - because it's public. Only if you need to change sth inside you need to go deeper and read another classes.

Architecture pattern that adapts this package-private style easily is hexagonal architecture, or ports-adapters architecture. You expose functionality of domain via public port, and rest of it is hidden with package-private scope. Following BDD you test domain via ports - like a black box.

Good talk about hex architecture and package scope :)
youtube.com/watch?v=sOaS83Ir8Ck

Collapse
 
cauchypeano profile image
Igor Konoplyanko

thank you for your reply!
Regarding your comment: I am generally agree with you, especially that I am also fan of hexagonal architecture. But in my opinion packages+package scope is very constrained and rigid mechanism to do so.

For example if you have more than 20 classes - you can't split them into subpackages so easily. Subpackages do not see package-private classes above them! For me the better way will be going with modularized application, especially with project jigsaw on top of it. In this way we will be really in control what part of our module we can expose and what part we want to hide as internal implementation details.

Collapse
 
darkknightpl profile image
Marcin Jarząbek • Edited

Thanks for replying for my comment :)

My concern is that many other developers don't have much experience with jigsaw, or maybe won't use it because project isn't especially big. Therefore I think package scope shouldn't end up on the scrap heap yet ;) If used properly can be very helpful in maintaining project architecture clean and modules loosely coupled.