views:

38

answers:

2

I keep on copy-pasting the following in my programs. I'm wondering if anyone of you uses similar code, perhaps in a library to achieve the same.

@Override
public String toString() {
    String ret = prefix;
    boolean first = true;

    for (Component child : children) {
        if (!first) {
            ret += " " + separator + " ";
        } else {
            first = false;
        }
        ret += child.getName();
    }
    return ret + postfix;
}

PS: One could use StringBuilder instead of String. Got that.

A: 

Nope. The only thing I can think of is it abstract that " " away into a final field in the toString() function. The reason that we don't have anything nicer is because the foreach construct doesn't care about the position, only that it will print sequentially.

That being said, avoid copy and paste at all costs. Make your own library if need be. Allow it to take a parameter of an interface which indicates if it is the first, and go from there.

Mike
because if I've one element list I don't want the separator.
simpatico
Ah, got'cha. Misread.
Mike
+2  A: 

Apache commons provides a number of join methods in the StringUtils class.

This page also has a lot of interesting suggestions on the best way to implement such a method: http://snippets.dzone.com/posts/show/91

bemace
It's in apache commons lang. Maven: http://mvnrepository.com/artifact/commons-lang/commons-lang/2.5
simpatico
The only pity is that using it I no longer control which method is used to print. I.e. say I'm not printing the toString() of a Composite but some other String returning method, then I cannot use this.
simpatico