Why modules are needed

We have already seen that there are four levels of access in Java. A method or field can be private, protected, public, or default (also known as package private) when no modifier is supplied. When you develop a complex library to be used in several projects, the library itself will contain many classes in many packages. There will certainly be classes and methods, fields in those that are used inside the library by other classes from different packages, but classes that are not to be used by the code outside the library. Making them anything less visible than public will render them unusable inside the library. Making them public will make them visible from outside.

In our code, the Maven module quick compiled to a JAR can only be used if the method sort can invoke qsort. But, we do not want qsort to be used directly from outside. In the next version, we may want to develop a version of the sort that uses qsort from the NonRecursiveQuickSort class and we do not want complaining customers whose code does not compile or work because of a minor library upgrade. We can document that the internal methods and classes are still public but not for use, but in vain. Developers using our library do not read documentation. This is also why we do not write excessive comments. Nobody will read it, not even the processor executing the code.

The most well-known and infamous example of this problem is the sun.misc.Unsafe class in the JDK. There is some really unsafe code in it, as the name implies. You can access memory out of heap, create objects without initialization, and so on. You should not. Why bother? You are a well-behaving developer and you just stick to the rules and you do not use that package. Whenever it changes in a new version of the JDK, your program is safe using only public and well-documented JDK API. Right?

Wrong! Without being aware of this, you may use some libraries that depend on other libraries that use the package. Mockito and Spring Framework are only two of the numerous in danger. In addition, Java 9 will definitely come with a new version of this package. However, it will also come with module handling. While Java 9 will provide some useful API for the libraries that were using the Unsafe package because there was no provided API for the functionality they needed, it will deliver modules not to recreate the same problem again.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.219.236.70