My application has a utility class with static methods which are responsible for showing notifications and optionally sending emails when something bad happens:
public static void sendEvent(final String description, final String name) {
....
SmtpParms smtpParams = readSmtpParms();
....
}
private static SmtpParms readSmtpParms() {
// read from properties file
....
}
Our codebase is shared between two applications. Application A reads SMTP parameters from a properties file. I work primarily on Application B. Application B had not been using this email functionality but had still been making calls to show event notifications on our GUI. Now Application B needs to read the SMTP parameters from the database.
I want to reuse the existing code, but since the methods are static, I cannot just subclass this utility class and point all of the Application B code to the subclass. This utility is referenced in multiple JARs and I would prefer a solution which alters the code as little as possible.
I think if I can separate out readSmtpParms into a separate class, that might help. But I cannot think of a way to pass the source (properties file vs. database) to the utility class instance without changing the method signature of sendEvent. I guess an alternative would be to create another method sendEventUsingDatabase but then I still have to update all of the references to sendEvent in the Application B code.
Is there a solution which does not alter the original code but also does not duplicate code? Does this code match a design pattern or an anti-pattern? Thanks.
The static utility method isn’t a good fit for the “send email” case.
I suggest you refactor the code into a class that can be properly instantiated and takes the email configuration parameters as input.
To make sure not to break existing code, you then rename the class and wrap it, along with code for reading config from property file, in a class with the original name.
Now you have one class you can use, and load with config retreived from db, and one wrapper conforming to the static utility method signature used in legacy code.