What is Modularization?
It is a process of decomposing a large system into self-contained and interconnected modules.As you see above snippet, there are 4 modules M1, M2, M3 and M4. M2 depends on M1. M3 depends on M2 and M4. M4 depends on M2. At the time of writing this article, JDK is decomposed around 90 modules.
What is a module in Java?
Module is a group of packages, resources and a descriptor (module-info.java) file. Whenever you define a module, you should specify module name, dependent modules, services offered, packages that are exported from this module, services consumed, reflection permissions etc.,
Use the command ‘java --list-modules’ to list all the standard modules provided by java.
How to declare a module?
Module is defined in module-info.java file.
module ModuleName {
}
How to add dependencies to the module?
Using ‘requires’ statement, you can add dependencies to a module.
module ModuleName {
requires AnotherModuleName;
}
Principles of Module
a. Module must Encapsulate internal code
Module must encapsulate internal implementation details and expose public APIs to other modules. Doing this encapsulated/internal code can be changed anytime without affecting other modules.
As you see above image, every module has two types of APIs.
a. APIs that are available outside
b. APIs that are internal to the module itself.
Now a module can choose, what to expose to outside and what not to.
b. Module must have well-defined interfaces
Any non-encapsulated must be available via well-defined interfaces.
Some problems prior to Java9
a. How can you expose a protected class to other package of same application?
Suppose you have a protected and want to expose this class to other package of your application. Since this class is protected, you can’t do this. Only way is make this class accessible to other package is make this class Public. But since this class is Public, now any one can use this class, you can’t control who can use this class.
b. Duplicate class names
Suppose you are using gson library of two versions V1 and V2. Where one of your application class expecting class ‘X’ from version V1. But as per java class path, whichever comes first will be loaded. That is class can come from version V1 or version V2, as an application developer you do not have any control here.
What is the core module in Java SDK now?
‘java.base’ is the basic module in Java9. It exposes java.lang and java.util packages. Every other module depends on ‘java.base’ module implicitly.
No comments:
Post a Comment