1

StringBuilders are meant to be used whenever large amounts of string concatenation occurs. In other words, when you have a lot of this

while(condition){
    s+="42";
}

or this

s = "1" + "a" + "unicorns"...;

Which gives us very clean and easily understandable code. So why aren't the same operators overloaded for StringBuilder? Is there a technical reason, or was it just a matter of style?

David says Reinstate Monica
  • 19,209
  • 22
  • 79
  • 122
  • 2
    Those operators don't really make sense for a mutable object – Tyler Jul 24 '14 at 19:28
  • 2
    Not sure why there are down-votes. It's a valid question. – TheBuzzSaw Jul 24 '14 at 19:28
  • @Tyler Can you expand on that... – David says Reinstate Monica Jul 24 '14 at 19:28
  • This is not a question that is suited for SO. It can be answered by the authors of the language/framework or nobody. Thus it is opinion based and not constructive. – Kirk Woll Jul 24 '14 at 19:29
  • @KirkWoll Tyler seems to be hinting at some sort of concrete reason, not an opinion. – David says Reinstate Monica Jul 24 '14 at 19:29
  • The `+` operator constructs a new object based on the two operands. You shouldn't generally be constructing a new string builder based on two different operands, you should be mutating the string builder based on a single operand. – Servy Jul 24 '14 at 19:29
  • @Servy, it doesn't *have* to return a new string builder, though that would be a weird design to return one of the operands. – Kirk Woll Jul 24 '14 at 19:30
  • 1
    @Dgrin91 He's hinting at why it would be poor design, which is inherently an opinion, not a matter of fact. – Servy Jul 24 '14 at 19:30
  • 1
    @Servy Fair point for the `+`, but what about the `+=`. Its designed to mutate to object. – David says Reinstate Monica Jul 24 '14 at 19:31
  • 4
    @Dgrin91, no it's not. `foo += bar` is equivalent to `foo = foo + bar`. That doesn't mutate the contents of `foo`, but rather assigns it to a new value. – Kirk Woll Jul 24 '14 at 19:33
  • @KirkWoll Thanks. If someone would have just put this in an answer I would have accepted. – David says Reinstate Monica Jul 24 '14 at 19:34
  • 2
    @Dgrin91 No, it's not. First off, one can never overload the `+=` operator. The `+=` operator is dependent on the implementation of the `+` operator, so overriding the `+` operator changes the behavior of the `+=` operator. The `+=` operator *doesn't mutate a value, it mutates a variable*. The `+=` operator evaluates the value of a variable, pass it along with the right hand side to the definition of the `+` operator, and then *mutates the variable to be the result of that operator*. – Servy Jul 24 '14 at 19:35

0 Answers0