Java Utility Classes and Extension Through Inheritance

I have a utility class with some static methods that I use in some places around my code. Now I am facing a problem. I want to replace the functions in this utility class to provide a better implementation. Obviously, this cannot be achieved directly without a serious hack.

My question is: what is the best way to solve this problem. How can someone still use utility classes so that they can be extended. I reflect on the idea of ​​packaging a specific utility function for each class that uses them, so even if the actual method of the utility cannot be replaced, at least you can replace the class method that calls it. However, I am curious to know what are the best practices.

+5
source share
3 answers

Why can't you just change the implementation of static methods in the utility class.

Until you change the method signatures, users will not be affected.

+3
source

Not being an exact duplicate, the answer to this question can be found on the following question:

calling a super method from a static method

Personally, I would not make them static methods, but make them relate to what they manipulate. If you publish an example or two of your current utility methods, I can tell you how I will handle them.

public interface HashAlgorithm {

    String hash(String s);

    String getType();

}

public class ReallyBadHashAlgorithm implements HashAlgorithm {
    public String hash(String s) {
        // really bad hash! I mean, really bad!
        return "HASH" + Integer.toString(s.hashCode()) + "HASH"; 
    }
    public String getType() {
        return "RRB"; // really really bad = RRB
    }
}

public class Hash<A extends HashAlgorithm> {

    String key;
    String value;
    A algorithm;

    public Hash(String key, A algorithm) {
       this.key = key;
       this.value = null;
       this.algorithm = algorithm;
    }

    public String getHash() {
        if(value == null) {
            value = algorithm.hash(key);
        }
        return value;
    }

    public static void main(String[] args) {
        ReallyBadHashAlgorithm alg = new ReallyBadHashAlgorithm();
        String key = "ABCDEFG";
        Hash hashThis = new Hash<ReallyBadHashAlgorithm>(key,alg);
        System.out.println(key.hashCode()); // to check it

        System.out.println(hashThis.getHash());

    }

}

And the result:

C:\Documents and Settings\mule\My Documents>java Hash
-488308668
HASH-488308668HASH

C:\Documents and Settings\mule\My Documents>
+1
source

Well, I really don't see your problem. If the new implementation of your utility class is equivalent to the old version, you can simply replace it, and if not, the existing code will still need to be able to call the old functions so that you can’t change anything. So, why not just add new methods to the Utility class that can be used by the new code?

0
source

All Articles