I've just spent hours debugging some code because I forgot (actually never considered it) that TextView.getText()
returns CharSequence
that may be in fact a mutable class…
Shouldn't it return (immutable) String
instead? I mean I can't imagine a situation when you want to share a state with a text field, at least not by default.
Isn't that something that can be objectively called a design mistake in a library?
Best Answer
Well, most immediate justification for this design decision can be found in method javadocs:
Casts mentioned above are possible only because Spannable and Editable implement CharSequence; String wouldn't allow for that.
For a deeper understanding of the design motivation, take a look at class javadocs:
Above means that TextView object is designed to support frequent changes of its content.
If getText would return immutable String, this would mean a high chance of creating multiple objects while working with TextView. This in turn would go against general approach preferred in Android and outlined in Avoid Creating Unnecessary Objects guidelines:
For the sake of completeness, it is worth noting that reasoning in above guidance implicitly involves mobile applications specifics.
In particular, one can imagine desktop or server platforms having more sophisticated garbage collection, allowing developers to design immutable objects at their discretion, without worrying much about performance implications.
At mobile platforms, API designers have to take into account resource limitations of mobile devices (memory, processor, power consumption etc) that can block implementation of theoretically better approaches.