Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java public classes with private dependent classes [closed]

Tags:

java

One thing that has always bothered me in Java is:

How do you create a single public class that should be used by downstream consumers but then nicely organize the classes it depends on in packages?

For example (somewhat contrived), I have a class UserDao that relies on LdapPersistenceHelper and DBPersistenceHelper. The UserDao class is sitting in a package called com.company.dao and i would like the two helpers to live in a package called com.company.dao.persistencehelper. However, I do not want to make the two helpers generic enough that they could be used by others. How do I that? If I make the helpers "protected" (really, no modifier) then I can't reach them from the UserDao. If I make them public, someone else might use them.

like image 526
silk Avatar asked Dec 17 '10 22:12

silk


2 Answers

The root problem is that you're trying to use packages to "organize things nicely." When Java packages were created, there were two design goals: (1) globally unique class naming, and (2) facilitating use of the protected/default access modifier.

The fact that you are constrained to having a folder structure of source that matches the packages inevitably leads to trying to use them to create "pretty/organized folder structure." But that's not what it was created for, and as a consequence, it doesn't work very well with the access modifiers it was created to support.

Edit: As an aside, I am not passing judgement one way or the other. I realized my first sentence may have sounded critical. Lots of projects legitimately choose an organized and maintainable structure over trying to squeeze some extra bit of perceived value out of protected access. Is it really that bad if the helper utility is public? If you don't trust the other developers with access not to misuse it, can they be trusted not to just change the access modifiers too?

like image 86
Affe Avatar answered Nov 14 '22 06:11

Affe


There is no way to enforce this, unless you place the classes in the same package. No way to define sub-package visibility.

like image 3
Bozho Avatar answered Nov 14 '22 08:11

Bozho