开发者

Java Utility Classes and Extension through Inheritance

I have a utility class with some static methods which I use in some places around my code. I am facing a problem now. I want to replace the func开发者_开发百科tions in this utility class in order to provide better implementation. Obviously this cannot be achieved directly without some serious hacking.

My question is: what is the best way to solve this problem. How can someone still use utility classes in such a way that they can still be extended upon. I am thinking around the idea of wrapping the particular utility function for each class that makes use of them so that even if the actual utility method cannot be replaced at least it is possible to replace the class method that calls it. Still, I am curious to know about what are the best practices.


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

As long as you don't change the method signatures, the users wont get affected.


While not an exact duplicate, an answer to this can be found in the following question:

calling a super method from a static method

Personally, I would make them not be static methods, but make them relate to whatever they manipulate instead. If you post an example or two of your current utility methods, I can tell you how I'd 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>


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜