Java 9 Modularity

Have you ever experienced

NoClassDefFoundError
at runtime (Its because of missing dependencies) and spent hours and days trying to track down irreproducible bugs in your production environment, just to find out that somehow two versions of 3rd party dependencies have managed to sneak into your classpath. Tracking them down is a painful experience eventhough we use sophisticated IDEs.

Its time to get rid of those nasty surprises and replace the classpath with the module path.

What is a module?
A module is the collection of code. It is a holder for classes, data and other modules in the form of dependencies. It is similar to JAR files but better.  But there is one crucial difference: one of the files is called module-info.java.  As the name suggests, it declares our module. It defines

  • the unique name of our module
  • which other modules our module depends on
  • which packages are to be exported to be used by other modules

It is a new and better way to share code with programmers and collaborate without issues.

How Modules work?

A module contains a module-info.java file which contains all the settings for the module and the dependency modules.

Two main keywords to use modules are

requires
and
exports
The above snippet states that the Decoder module depends on the Reader module. The next line also exposes the com.harinathk.decoder package, which means that other modules can only access the com.harinathk.decoder package and everything within, including classes and packages.
The above snippet shows that the Reader module does not depend on any other module while other modules can only access the com.harinathk.reader package within that module.

Below are the classes for Reader and Decoder module respectively. The Decoder module requires the Reader module to retrieve the data to be decoded through the use of a scanner.

Conclusion

Modules enables to structure our code in a more modular way by providing strong encapsulation and reliable configuration, but still allows loose coupling of modules.

Modules also allows you to get away from class path issues such as those obscure bugs which turn out to be an old version of the jar already on your class path. Java finally gets the level of dependency control we now take for granted in Maven and other tools. It is time to say good bye to class path hell.

harinathk
 

Click Here to Leave a Comment Below 0 comments