3

Possible Duplicate:
What does two consecutive blocks of code {}{} do?

I am reworking a very old Java application and have observed that the original developer used a lot of compound statements within methods that are not part of any conditional or looping logic.

Example pseudocode:

{
Object a = new Object();
a.setAttribute();
}

{
Object b = new Object();
b.setAttribute();
}

Is this just a style preference or am I missing something?

Community
  • 1
  • 1
  • 2
    It contains the variable name within the scope of the braces. It can't hurt and may help avoid name collisions. – Marko Topolnik Nov 16 '12 at 14:42
  • 3
    @MarkoTopolnik: I'd suggest that if it's overused, it could hurt readability very considerably. Used sparingly and only when actually useful, it would be fine. – Jon Skeet Nov 16 '12 at 14:43
  • 1
    @CAMOBAP: That is different from what OP is asking for. – kosa Nov 16 '12 at 14:46
  • @JonSkeet I've actually seen it used only in GUI-building code, and mostly it was generated code. The code generation tool makes its life easier if it doesn't have to account for duplicate names. In a human-written method having a huge number of variables in a single method is a code smell all on its own. – Marko Topolnik Nov 16 '12 at 14:47
  • Am I missing something or does the code as is become a waste of CPU cycles? That is unless the methods are static... – Germann Arlington Nov 16 '12 at 14:47
  • @GermannArlington This has nothing to do with runtime. Even at the bytecode level it cannot be observed anymore. – Marko Topolnik Nov 16 '12 at 14:47
  • Bhavik - Just trying to confirm that in this case, it is rather useless. – user1011251 Nov 16 '12 at 14:50

2 Answers2

2

It adds additional scoping, which can occassionally be useful if you work with a lot of disjoint local variables in the same method.

jtahlborn
  • 52,909
  • 5
  • 76
  • 118
2

Local variables declared inside one block are not visible in any others, so it's handy for things like code generation where you don't need to worry about name clashes between different blocks of code. I wouldn't generally use this technique in hand-written code.

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183