Possible Duplicate:
Anonymous code blocks in Java
I just came across the following.
if ( test ) {
{
// statements 1
}
{
// statements 2
}
}
It is the first time I've seen this. How does it work?
It's is just writing two different blocks of code in order to hide local variables.
From the answer to the question "Anonymous code blocks in Java":
Blocks restrict variable scope.
public void foo() { { int i = 10; } System.out.println(i); // Won't compile. }
In practice, though, if you find yourself using such a code block then it's probably a sign that you want to refactor that block out to a method.
Two examples of where this can be (slightly) useful - in unit tests, and in GUIs, both of which often involve repetitive code:
It's useful in GUI building, where it is incredibly easy to cut-and-paste lines relating to one component and forget to update them for the new component, leading to hard-to-find bugs, e.g.:
JButton button1 = new JButton("OK");
button1.setEnabled(false);
button1.setAlignmentX(-1);
JButton button2 = new JButton("Apply");
button1.setEnabled(false);
button1.setAlignmentX(-1);
Oops, I just configured button1
twice. If you put each button in its own block, then this mistake is picked up by the compiler. Again, you could create each button in a separate method, but that may make it hard to see what is going on (especially given the lack of keywords parameters in Java):
JButton button_ok = makeButton("OK", false, -1);
JButton button_apply = makeButton("Apply", true, 1);
// what exactly is being set here?
...
// much later:
private static JButton makeButton(String name, boolean enabled,
int alignment)
{
JButton button = new JButton(name);
button.setEnabled(enabled);
button.setAlignmentX(alignment);
return button;
}
...and you may end up with numerous methods, each handling different variations of parameters, and each only being used maybe twice.
The two blocks are independent. So, whatever variables you may have in the first block won't be accessible in the second block - or anywhere outside the first block. It's called code isolation or scoping.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With