0

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é

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
TungstenX
  • 830
  • 3
  • 19
  • 40

2 Answers2

2

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.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Does it use less resources to create a StringBuffer/StringBuilder than a String? StringBuffer is used because it is Thread Safe and this function is in a very "threaded" environment :) - Else I always use StringBuilder. – TungstenX Oct 29 '13 at 06:52
  • 1
    @TungstenX: using `StringBuffer` does *not* make your code thread-safe! `StringBuffer` implements each of its methods in a thread-safe manner, but since your code consists of multiple method invocations on the `StringBuffer` without any synchronization, your code still lacks thread-safety. – Holger Oct 29 '13 at 10:16
1

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

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • Thank you for the response. I agree it is subjective, just wanted to know if there is something wrong in using it like this, that is, it uses way more processing/resources etc. – TungstenX Oct 29 '13 at 07:01