سؤال

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é

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top