Question

To start; just because one can do it doesn't always means one should do it. I'll use a code snippet to explain my question:

private StringBuffer sb = new StringBuffer(); //Using StringBuffer because it is thread safe

... /*append to sb in methods etc*/ ...

public String getSbValue() {
    try {
        return sb.toString();
    } finally {
        sb = new StringBuffer(); //or sb.delete(0, sb.length()); ?
    }
}

Is this a good or bad practice or neither?

Or should I rather do:

public String getSbValue() {
    String ret = sb.toString();
    sb = new StringBuffer(); //or sb.delete(0, sb.length()); ?
    return ret;
}

Best regards,

André

Was it helpful?

Solution

This is clearly highly subjective. I personally find the logic of the very short method using finally hard to follow.

To my eye, the following is clearer:

public String getSbValue() {
    StringBuffer prev_sb = sb;
    sb = new StringBuffer();
    return prev_sb.toString();
}

(Your second example, while being similar to my code above is different, and has different semantics to your first example.)

P.S. You should almost certainly be using StringBuilder in place of StringBuffer.

OTHER TIPS

I think option 1 for some programmers will look like a puzzle. Option 2 is shorter and clearer

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top