Problem:
There are certain java code refactoring in the long-running applications, that are due to deprecated legacy APIs, that needs to be replaced with latest APIs/libraries.
For example, when we upgrade AEM server from 6.2 to 6.3, Apache Sling Commons JSON libraries are deprecated and we may need to replace its references with newer Gson or org.json library API calls.
These scenarios, involve a full-fledged code-refactoring, touching all layers of classes, to remove the references of deprecated API and replace it with the new one.
Solution:
Such problems can be handled in a more elegant way, with a new pattern of code-refactoring, as detailed below.
Steps:
- List down all the deprecated API references across the projects.
- Create a new set of API classes, with the same class names and method names, but with a new package structure- mostly as a separate common package in the project.
- Change all the import statements of the deprecated classes, to the newly created package in the commons package.
- In the new library created, write your logic referencing to the new API. In few cases, it would be a direct call to the new library, but in few cases, we may need to deal with some conversions between the classes.
Example:
- To replace references of “apache.sling.commons.json.JSONObject” classes.
- Create a new util package.
- Create methods with same name as in deprecated library.
- Change Import statements in the existing code base, removing apache sling commons class and importing the newly added utility class. This would be the only change in the application classes.
Advantages
- Ease of coding
- No duplication of code across the project.
- More elegant
- Ease of review
- Ease of unit testing
- Ease of debugging/maintenance
- This new API can be built as a separate common jar file and imported to other projects also.
Challenge:
Due to time constraint, it may not be possible to collect all the reference at a single go. This can be addressed if we have the common new library open for adding new methods, as and when we come across the old references.
Alternatively, we can go with a phased approach for refactoring to address this challenge. In this, we will be anyways creating a new library in the first phase, and in the later, will be adding new classes and methods as required and identified.