Re: Blocks for scope control
Arved Sandstrom wrote:
for a general discussion.
I'm talking specifically about the block by itself: a pair of braces by
themselves, enclosing some code in a method. On occasion I do run across
situations where a judicious use of such a block inside a method, to
restrict variable visibility, is handy.
I almost never see anyone else using these things this way. A block in a
method always seems to be associated with a control construct or
exception handling. As any number of references point out, you wouldn't
expect to see many usages of local blocks, mainly because 99 times out
of 100 that situation is probably handled best by a new method. But in
my years of looking at Java it occurs to me that I barely see any use of
this at all...even where it wouldn't be a bad idea.
You see it standardly in initialization blocks, especially static, though I
often (more often than not) find myself refactoring static initialization
blocks to private static methods. For instance initialization they're
extremely useful for blocks that multiple constructors must share.
Within methods I use them as well, to enforce temporariness of variables.
This is very handy to prevent re-use of a variable whose usefulness has
expired. The need is rare, but like the legendary left-handed stembolt, if
you don't have it when you need it, that's a worry.
This idiom is also valid in other languages (e.g., C).
Calling such code blocks "anonymous" doesn't make sense. Code blocks aren't
named in the first place.
There are many, many idioms in Java that are woefully underused. 'assert' is
the prime example. People don't understand it, even excoriate it (strange as
that seems), and it's been around about a decade, since Java 1.4. Lack of use
does not equate to lack of value.
Honi soit qui mal y pense.