DEV Community

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

Collapse
 
snuk87 profile image
Dennis

I don’t share your view. In my opinion package private should be used frequently and should always be used if you don't have to make a class public.

The more restricted your access level the less chances to create unnecessary dependencies that will end up in a big ball of mud. In a lot of architectural styles like clean architecture, layered architecture, hexagonal architecture and domain driven design (DDD) it is important to have clean boundaries between your modules. In case of DDD you have different contexts and you only want to provide access to a domain through a well defined interface. The simplest way to achieve this is with package private scope.

It's also important to organize your packages in a proper way. I have seen a lot of people tend to create too many packages and sub packages but a java package should contain all classes of a specific domain/context. E.g. the web interface, business logic / service layer, DAO layer of one domain should be in one package and only provide functions to other packages through interfaces.

Collapse
 
cauchypeano profile image
Igor Konoplyanko

My position here is that to avoid unnecessary dependencies we need to use better mechanism as we have with Package scopes. It's too poor and will not help us to achieve hexagonal architecture/DDD but will annoy us during refactoring.

That's also reason why java got jigsaw - to overcome those issues in much nicer way.

So far all reasons I've heard in favor for package-private - is to achieve DDD/Hexagonal architecture based on package scopes.

Collapse
 
snuk87 profile image
Dennis

Can you give me an example of anything that becomes annoying when you use package private?
I never faced any problems ... quite the contrary, it showed me when my domain design wasn't good.

In your blog post you said that you agree with oracles recommendation on using the most restrictive access level but in the next sentence you say Life will be much easier for your project if everything will be public/private. So you say it's better to use public instead of package private. Those two sentences are a contradiction.

The main reason why JAVA got jigsaw was to modularize the JDK. That you can use it for your projects is just a nice side effect. I totally agree that jigsaw is a much cleaner solution than using package scopes but in reality jigsaw is mostly used for green field projects and old projects are rarely refactored to use jigsaw. So I think it will take a few more years that the majority of JAVA applications will shift to jigsaw.

That's why package private is so important. You need a clean architecture when you have a project with 1M+ lines of code and working with 20 other developers. Also it's much easier to slice your application into micro services when you have a clean architecture.