Does Java need friends?
One of the stumbling blocks I have run into, in my few years of using Java is Java's lack of flexible access visibility mechanisms. The access mechanisms are strictly constrained within the semantics of private, package, protected and public access modifiers. However, in ceratin scenarios this can be a bit constraining.
A good example if often when you use light-weight domain modelling using Java. You woudln't want to expose the internal state of your domain objects to external entities. However, you are forced to add the so called public getters and setters to your private instance variables so that your persistence frameworks can set them or the view framework can get them. This is indeed an anti-pattern, that breaks one of the cornerstones of object orientation, i.e data encapsulation. These getters and setters are not part of the public behaviour of the entity you are modelling.
There are two solutions that some into my mind,
- A C++ style friend access mechansim, where you can specify arbitrary visibility enablement between classes. This means you can allow the internal state of your domain classes be accessed by only persistent and domain classes.
- Allow the semantics of package and protected access to be extended to hierarchical packages. This means for example, classes in com.acme.domain.persist and com.acme.domain.view would have the same access permissions on the classes within com.acme.domain as the classes within the same package.
Note: Some persistence frameworks do enable private field level access. However, as soon as you deny ReflectPermission in a J2EE environment (recommended by the spec) you will start running into problems.