Could Java 7 Please Add A Subpackage Access Modifier?
January 6, 2008 – 22:34 | javaAs we all know, the package hierarchy in Java is a rather superficial one. Package com.foo.pack.sub means nothing special to package com.foo.pack - no more special than com.bar.whatever. It’s something that’s seemingly trivial, but really has been discouraging proper organization of classes and more careful design practices.
As an example, say I would like to organize the interfaces/classes that constitute an order handling API into a com.foo.order package, such as:
Order- the aggregation root of the domain.LineItem- the entity class that represents each line item on an order. Each order has a list of line items.OrderService- an interface for an order handling service.OrderRepostiory- a repository interface for access the order objects.
And I’d like the implementation classes kept in a com.foo.order.impl sub-package, which would have, of course, OrderServiceImpl and OrderRepositoryImpl.
Now the problem comes. On the Order class, as part of the domain API, I have public methods controlling access to the line items by index, e.g., getLineItem(int i). In the meantime, I would like to provide a method setLineItems(List items) so that the repository implementation can efficiently set the list of line items read from the database. Obviously that method should not be public, as it defeats the purpose of any other controlled accessors. On the other hand, there is no way other than making the method public for it to be accessible to the repository implementation, due to it being in a different package.
It seems to be quite a natural thing to me for Java to support an extra level of access - the sub-package level. It would be between public and the default access - only classes in the same package or the sub-packages can access members declared at this level.

One Response to “Could Java 7 Please Add A Subpackage Access Modifier?”
Java 7 will almost certainly include JSR 294 Superpackages - you can find more info on my Java 7 page.
By Alex Miller on Jan 8, 2008