Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is StringBuilder final - versus having all final methods?

Tags:

java

The motivation for this was my answer ("Wishful thinking") to an earlier question on StringBuilder best-practices. If StringBuilder was extensible, then domain-specific subclasses could extend its fluent interface, which would tighten up code where a StringBuilder gets passed around to a lot of methods that build parts of a larger string.

I'm considering suggesting something - maybe a StringBuilder delegate - to the Guava folks.

What additional purpose does it serve for StringBuilder to be final, as opposed to just having final methods?

like image 886
Ed Staub Avatar asked Sep 16 '11 17:09

Ed Staub


1 Answers

If all methods are final then the current behaviour of StringBuilder cannot be modified. Subclasses of it must add either unconnected behaviour (which is inherently bad design) or new functionality which uses the old, such as convenience methods. If you want to do the latter it is probably better to have a class that provides the relevant functionality but contains a StringBuilder rather than extends it. As Joshua Bloch says, "prefer containment over inheritence". In short, if all methods are final there is no good reason to extend the class, and you may as well make it final too.

like image 114
DJClayworth Avatar answered Sep 23 '22 19:09

DJClayworth