'final' variables

David B. Held dheld at codelogicconsulting.com
Wed Mar 21 01:33:15 PDT 2007


Lionello Lunesu wrote:
> I've been trying to follow the thread on the const/final/invariant 
> extensions but I have to wonder: how useful are final variables?
> [...]

If you spend any amount of time writing Java code, you can appreciate 
'final' fairly easily.  In Java, String is immutable, so a final String 
is like a const std::string.  On the other hand, Java provides 
StringBuilder for mutable operations on strings.  It's a little like 
std::stringstream, but not quite.

// Create a new StringBuilder and reserve a buffer of at least 48 chars
StringBuilder s = new StringBuilder(48);
s.append("Hello,");
...
s = methodReturningNewStringBuilder();
...
s.append(" world!");
// s.toString() == "Hello, world!"?  Maybe, maybe not

final StringBuilder s = new StringBuilder(48);
s.append("Hello,");
...
s = methodReturningNewStringBuilder(); // Error
...
s.append(" world!");
// s.toString() == "Hello, world!"?  Provably!

What you can't do in Java is declare a const or invariant StringBuilder. 
  While this example is a little contrived, once you start talking about 
file streams and JDBC Statements and ResultSets, knowing whether a 
variable has been rebound becomes a very big deal.  That is, just 
declaring a few things 'final' can eliminate a whole host of potential 
bugs and let you focus on the parts of the code that really matter.

Dave



More information about the Digitalmars-d mailing list