开发者

Apply new function on an object

I have a string, and I want to do a bunch of things on it at once (it will be a bunch of replacements) in a function. I want to do something to the degree of string.color() if the string is called string and the function I make is color(). How should I declare color()? Should I do 开发者_运维问答it in a class extending String or an interface? Should I just give that up and do color(string) instead?


Just do public String color(String) { ... }.

Since you can't change a String (i.e. they're immutable), you're going to end up returning a new String from either approach. Might as well take the more straightforward one until circumstances justify using something more complex like inheritance or composition.


Just a note - neither of your suggestions (class extending String, or an interface) would let you avoid color(String):

  • String is a final class, so you can't define a subclass of it with your own operations on.
  • You can create any interfaces you like, but you can't make String implement them - so the method on the interface would need to take a String as an argument, and then you're back to color(String) again.


Consider composition (e.g. a simple wrapper for String):

public class EnhancedString {
    private String str;
    public EnhancedString(final String str) {
        this.str = str;
    }
    public EnhancedString color() {
        // do some stuff and return the result
        return this;
    }
    public EnhancedString anotherReplacement() {
        // more stuff
        return this;
    }
}

What's nice about this approach is that it allows you to chain method invocations later (jQuery-style):

EnhancedString estr = new EnhancedString("testing");
estr.color().anotherReplacement();


String is a final class in java and so you cannot extend and add method to String class
You should do color(String) instead.
If you're dealing with bunch of replacement in String consider StringBuilder instead.


String is final so you can't extend it.

Just do color(String).


String is final and immutable so you will not be able to extend it and make a subclass that has new methods on it such as color.

One approach is to create a StringUtil class that has the method color defined, i.e.

public static String color(String someString) {
    // Your logic that creates a new "colored" String and returns this new String
}

You can then just call:

String coloredString = StringUtil.color(someString);

As an aside, every time you perform any operation on a String a new String object is returned so it is more efficient to use something like a StringBuilder if you are performing many operations (such as concatenation) on the String in your color method and the you can just return the result of the StringBuilder's toString() method.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜