I understand "how packages should be structured" is very opinion based. But java contains a rule for default package visibility, so it implies that there is a specific reason or pattern, thought in the creation of Java, of how packages should be structured in an object oriented environment using object oriented principles.
I will use the Car Example, starting with methods using the default visibility:
com.company.car.Startup#main (public)
com.company.car.engine.CoreEngine#rotate (default)
At first glance, all methods are semantically supposed to be initially declared as default (in this case except the main()
which is the point of entry and should be public).
Ok, now Startup#main
need to call the CoreEngine#rotate
method when I start the car. But I don't want to expose that rotate()
method publicly when somebody uses the CoreEngine
for things other than internal purposes (like calling CoreEngine#turnEngineLightOn
from a remote control device outside the car).
But... the rotate()
method has a default visibility which is package restricted, It is inaccessible from main()
method too!
In this case, I have few options:
- Turn the
CoreEngine#rotate
method public and rely on duck typing - Change the package of the Engine class
I understand in practice that this is not how a real life project should consider the packages role in the design of a project. So does it mean that default visibility is something practically useless semantically? Is this a language failure or there is a design pattern to handle a project structure that solves this semantics problem?
Does a pattern like this really exist? If so, is it documented? Can you provide some real life examples using object oriented code?