Anonymous code blocks in Java

Java

Java Problem Overview


Are there any practical uses of anonymous code blocks in Java?

public static void main(String[] args) {
    // in
    {
        // out
    }
}

Please note that this is not about named blocks, i.e.

name: { 
     if ( /* something */ ) 
         break name;
}

.

Java Solutions


Solution 1 - Java

They 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 that's probably a sign that you want to refactor that block out to a method.

Solution 2 - Java

@David Seiler's answer is right, but I would contend that code blocks are very useful and should be used frequently and don't necessarily indicate the need to factor out into a method. I find they are particularly useful for constructing Swing Component trees, e.g:

JPanel mainPanel = new JPanel(new BorderLayout());
{
    JLabel centerLabel = new JLabel();
    centerLabel.setText("Hello World");
    mainPanel.add(centerLabel, BorderLayout.CENTER);
}
{
    JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0,0));
    {
        JLabel label1 = new JLabel();
        label1.setText("Hello");
        southPanel.add(label1);
    }
    {
        JLabel label2 = new JLabel();
        label2.setText("World");
        southPanel.add(label2);
    }
    mainPanel.add(southPanel, BorderLayout.SOUTH);
}

Not only do the code blocks limit the scope of variables as tightly as possible (which is always good, especially when dealing with mutable state and non-final variables), but they also illustrate the component hierarchy much in the way as XML / HTML making the code easier to read, write and maintain.

My issue with factoring out each component instantiation into a method is that

  1. The method will only be used once yet exposed to a wider audience, even if it is a private instance method.
  2. It's harder to read, imagining a deeper more complex component tree, you'd have to drill down to find the code you're interested, and then loose visual context.

In this Swing example, I find that when complexity really does grow beyond manageability it indicates that it's time to factor out a branch of the tree into a new class rather than a bunch of small methods.

Solution 3 - Java

It's usually best to make the scope of local variables as small as possible. Anonymous code blocks can help with this.

I find this especially useful with switch statements. Consider the following example, without anonymous code blocks:

public String manipulate(Mode mode) {
	switch(mode) {
	case FOO: 
		String result = foo();
		tweak(result);
		return result;
	case BAR: 
		String result = bar();	// Compiler error
		twiddle(result);
		return result;
	case BAZ: 
		String rsult = bar();	// Whoops, typo!
		twang(result);	// No compiler error
		return result;
	}
}

And with anonymous code blocks:

public String manipulate(Mode mode) {
	switch(mode) {
		case FOO: {
			String result = foo();
			tweak(result);
			return result;
		}
		case BAR: {
			String result = bar();	// No compiler error
			twiddle(result);
			return result;
		}
		case BAZ: {
			String rsult = bar();	// Whoops, typo!
			twang(result);	// Compiler error
			return result;
		}
	}
}

I consider the second version to be cleaner and easier to read. And, it reduces the scope of variables declared within the switch to the case to which they were declared, which in my experience is what you want 99% of the time anyways.

Be warned however, it does not change the behavior for case fall-through - you'll still need to remember to include a break or return to prevent it!

Solution 4 - Java

I think you and/or the other answers are confusing two distinct syntactic constructs; namely Instance Initializers and Blocks. (And by the way, a "named block" is really a Labeled Statement, where the Statement happens to be a Block.)

An Instance Initializer is used at the syntactic level of a class member; e.g.

public class Test {
    final int foo;

    {
         // Some complicated initialization sequence; e.g.
         int tmp;
         if (...) {
             ...
             tmp = ...
         } else {
             ...
             tmp = ...
         }
         foo = tmp;
    }
}

The Initializer construct is most commonly used with anonymous classes as per @dfa's example. Another use-case is for doing complicated initialization of 'final' attributes; e.g. see the example above. (However, it is more common to do this using a regular constructor. The pattern above is more commonly used with Static Initializers.)

The other construct is an ordinary block and appears within a code block such as method; e.g.

public void test() {
    int i = 1;
    {
       int j = 2;
       ...
    }
    {
       int j = 3;
       ...
    }
}

Blocks are most commonly used as part of control statements to group a sequence of statements. But when you use them above, they (just) allow you to restrict the visibility of declarations; e.g. j in the above.

This usually indicates that you need to refactor your code, but it is not always clear cut. For example, you sometimes see this sort of thing in interpreters coded in Java. The statements in the switch arms could be factored into separate methods, but this may result in a significant performance hit for the "inner loop" of an interpreter; e.g.

    switch (op) {
    case OP1: {
             int tmp = ...;
             // do something
             break;
         }
    case OP2: {
             int tmp = ...;
             // do something else
             break;
         }
    ...
    };

Solution 5 - Java

You may use it as constructor for anonymous inner classes.

Like this:

alt text

This way you can initialize your object, since the free block is executed during the object construction.

It is not restricted to anonymous inner classes, it applies to regular classes too.

public class SomeClass {
    public List data;{
        data = new ArrayList();
        data.add(1);
        data.add(1);
        data.add(1);
    }
}

Solution 6 - Java

Anonymous blocks are useful for limiting the scope of a variable as well as for double brace initialization.

Compare

Set<String> validCodes = new HashSet<String>();
validCodes.add("XZ13s");
validCodes.add("AB21/X");
validCodes.add("YYLEX");
validCodes.add("AR2D");

with

Set<String> validCodes = new HashSet<String>() {{
  add("XZ13s");
  add("AB21/X");
  add("YYLEX");
  add("AR5E");
}};

Solution 7 - Java

Instance initializer block:

class Test {
    // this line of code is executed whenever a new instance of Test is created
    { System.out.println("Instance created!"); }

    public static void main() {
        new Test(); // prints "Instance created!"
        new Test(); // prints "Instance created!"
    }
}

Anonymous initializer block:

class Test {
	
	class Main {
		public void method() {
			System.out.println("Test method");
		}
	}

	public static void main(String[] args) {
		new Test().new Main() {
			{
				method(); // prints "Test method"
			}
		};

		{
			//=========================================================================
			// which means you can even create a List using double brace
			List<String> list = new ArrayList<>() {
				{
					add("el1");
					add("el2");
				}
			};
			System.out.println(list); // prints [el1, el2]
		}

		{
			//==========================================================================
			// you can even create your own methods for your anonymous class and use them
			List<String> list = new ArrayList<String>() {
				private void myCustomMethod(String s1, String s2) {
					add(s1);
					add(s2);
				}

				{
					myCustomMethod("el3", "el4");
				}
			};

			System.out.println(list); // prints [el3, el4]
		}
	}
}

Variable scope restrict:

class Test {
    public static void main() {
        { int i = 20; }
        System.out.println(i); // error
    }
}

Solution 8 - Java

You can use a block to initialize a final variable from the parent scope. This a nice way to limit the scope of some variables only used to initialize the single variable.

public void test(final int x) {
    final ClassA a;
    final ClassB b;
    {
        final ClassC parmC = getC(x);
        a = parmC.getA();
        b = parmC.getB();
    }
    //... a and b are initialized
}

In general it's preferable to move the block into a method, but this syntax can be nice for one-off cases when multiple variables need to be returned and you don't want to create a wrapper class.

Solution 9 - Java

Describe a task, either with a comment or inherently due to the structure of your code and the identifiers chosen, and then use code blocks to create a hierarchical relationship there where the language itself doesn't enforce one. For example:

public void sendAdminMessage(String msg) throws IOException {
    MessageService service; {
        String senderKey = properties.get("admin-message-server");
        service = MessageService.of(senderKey);
        if (!ms.available()) {
          throw new MessageServiceException("Not available: " + senderKey);
        }
    }

    /* workaround for issue 1298: Stop sending passwords. */ {
        final Pattern p = Pattern.compile("^(.*?)\"pass\":.*(\"stamp\".*)$");
        Matcher m = p.matcher(msg);
        if (m.matches()) msg = m.group(1) + m.group(2);
    }
    ...
}

The above is just some sample code to explain the concept. The first block is 'documented' by what is immediately preceding it: That block serves to initialize the service variable. The second block is documented by a comment. In both cases, the block provide 'scope' for the comment/variable declaration: They explain where that particular process ends. It's an alternative to this much more common style:

public void sendAdminMessage(String msg) throws IOException {
    // START: initialize service
    String senderKey = properties.get("admin-message-server");
    MessageService service = MessageService.of(senderKey);
    if (!ms.available()) {
      throw new MessageServiceException("Not available: " + senderKey);
    }
    // END: initialize service

    // START: workaround for issue 1298: Stop sending passwords.
    final Pattern p = Pattern.compile("^(.*?)\"pass\":.*(\"stamp\".*)$");
    Matcher m = p.matcher(msg);
    if (m.matches()) msg = m.group(1) + m.group(2);
    // END: workaround for issue 1298: Stop sending passwords.

    ...
}

The blocks are better, though: They let you use your editor tooling to navigate more efficiently ('go to end of block'), they scope the local variables used within the block so that they cannot escape, and most of all, they align the concept of containment: You are already familiar, as java programmer, with the concept of containment: for blocks, if blocks, method blocks: They are all expressions of hierarchy in code flow. Containment for code for documentary reasons instead of technical is still containment. Why use a different mechanism? Consistency is useful. Less mental load.

NB: Most likely the best design is to isolate the initialisation of the MessageService object to a separate method. However, this does lead to spaghettification: At some point isolating a simple and easily understood task to a method makes it harder to reason about method structure: By isolating it, you've turned the job of initializing the messageservice into a black box (at least, until you look at the helper method), and to fully read the code in order of how it flows, you need to hop around all over your source files. That's usually the better choice (the alternative is very long methods that are hard to test, or reuse parts of), but there are times when it's not. For example, if your block contains references to a significant number of local variables: If you make a helper method you'd have to pass all those variables. A method is also not control flow and local variable transparent (a helper method cannot break out of the loop from the main method, and a helper method cannot see or modify the local variables from the main method). Sometimes that's an impediment.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobert MunteanuView Question on Stackoverflow
Solution 1 - JavaDavid SeilerView Answer on Stackoverflow
Solution 2 - JavaStephen SwensenView Answer on Stackoverflow
Solution 3 - JavaKevin KView Answer on Stackoverflow
Solution 4 - JavaStephen CView Answer on Stackoverflow
Solution 5 - JavaOscarRyzView Answer on Stackoverflow
Solution 6 - JavadfaView Answer on Stackoverflow
Solution 7 - JavaAniket SahrawatView Answer on Stackoverflow
Solution 8 - JavastewartbrackenView Answer on Stackoverflow
Solution 9 - JavarzwitserlootView Answer on Stackoverflow