1.1.1. Favor placing API and implementation into separate packages

Note: I’ve picked this Java API Design Checklist item as an illustrative example, not because it is of a particular importance. I’ve added similar details to other checklist items as well and will add more in the future. To see such details, open the list (also available from the main menu at the top of the page) and click on [explain] where available.

Rationale:

Simplicity, Consistency, Safety and Evolution. Java only supports public and package scoped classes. You should obviously never mix public implementation classes with APIs (see checklist item). You can only place package scoped classes into API packages if you are certain they will be never needed in any other (implementation) package. Otherwise developers may inadvertently change their access to public, breaking the encapsulation of the API.

More importantly, Java module systems like OSGi use package boundaries for additional class loader isolation, dependency management and versioning. You won’t be able to take advantage of it if you combine API and implementation into one package.

Do this:

package com.company.product;

public class ApiClass {
   private ImplementationClass m;
}

package com.company.product.internal;

public class ImplementationClass {...}

Don’t do this:

package com.company.product;

public class ApiClass {

   private ImplementationClass m;
}

class ImplementationClass {...} //package scoped

Exceptions:

Very rarely, a small number of package scoped classes are useful when a separate implementation package adds no benefits, only complexity.

 

Creative Commons Licence
This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 Canada License.

Advertisements

About Ferenc Mihaly
Senior Software Architect at OpenText Corporation

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: