2

Possible Duplicates:
Efficiency of Java “Double Brace Initialization”?
Meaning of new Class(…){{…}} initialization idiom

Assume I created a JMenu Bar the following way:


JMenuItem saveMenuItem = new JMenuItem("Save")
    {{
       addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e)
                {
                    String location = GUI.Custom.QuickDialogs.selectFile(false);
                    try
                    {
                        PrintWriter pw = new PrintWriter(new File(location));
                        String text = textArea.getText();
                        pw.println(text);
                        pw.flush();
                        pw.close();
                    }
                    catch(Exception ex)
                    {
                        textArea.append("Could not save this debug output");
                    }
                }
            });
    }};

    JMenu optionsMenu = new JMenu("Options")
    {{
        add(saveMenuItem);
        setVisible(true);
    }};

    private JMenuBar menuBar = new JMenuBar()
    {{
       add(optionsMenu);
       setVisible(true);
    }};

Is this a bad design pattern to create objects this way as opposed to just declaring the variable, and then creating in a constructor or something?

Community
  • 1
  • 1
user489041
  • 27,916
  • 55
  • 135
  • 204
  • possible duplicate of [Efficiency of Java "Double Brace Initialization"?](http://stackoverflow.com/questions/924285/efficiency-of-java-double-brace-initialization) and/or [Meaning of double brace initialization idiom](http://stackoverflow.com/questions/1372113/meaning-of-new-class-initialization-idiom) – BalusC Apr 04 '11 at 19:40
  • Im not really worried about the efficiency, Im more worried about this creating some corner case or some other issue that I am missing. I just figured there was a reason why I dont see this too often. – user489041 Apr 04 '11 at 19:43

5 Answers5

2

What you've done is called: "initialization block".

From doc:

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors

Example:

class A { 
    private String field1;

    {
        field1 = "example field";
        field2 = getstaticResult();
    }

}

But in my opinion we shouldn't use this very often and especially in your case it's very unusual to use it.

lukastymo
  • 26,145
  • 14
  • 53
  • 66
1

You seem to be asking (at least) two different things here. The double-bracket idiom is known and often used as a shorthand for creating anonymous inner classes, replacing the explicit constructor with an initializer block. Usually this makes the code more readable, so I would say it's OK.

OTOH since (nonstatic) initializer blocks are a relatively recent addition to the language, some developers may not be familiar with them though, which may create confusion. And of course, as with almost any techniques, when overused, it can create more problems than it solves.

Péter Török
  • 114,404
  • 31
  • 268
  • 329
1

Nothing actually wrong with Double Brace Initialization; I often use it for maps and lists.

It maybe depends on who your audience is -- do the other people on your team understand what you're doing here? Remember that someday, somebody is going to have to read this code.

dustmachine
  • 10,622
  • 5
  • 26
  • 28
0

Like most questions of this nature, I unfortunately must say "it depends". When you do it this way, you're actually creating a new anonymous class, so there is an ever-so-slight performance hit in terms of memory and CPU, but under most circumstances I would say that it is insignificant enough to ignore. If doing it this way makes your code more readable, and if it is the style the rest of your team is using, I would say to go with it.

Tony Casale
  • 1,537
  • 8
  • 7
  • Additionally, you say: "These are all created statically in the class". This isn't true as the initializer is not static, but is called on the anonymous class instance. – Tony Casale Apr 04 '11 at 19:42
0

Two problems

  • Leaking References: Since these are anonymous inner classes they keep a reference to the surrounding object which will keep them from being collected. This could cause hard to find memory leaks.

  • Anonymous Types: For anything that relies on the exact class this can cause problems. For example Serialisation and some implementations of equals may not work as expected.

If you know that the above wont be a problem there is nothing wrong with using this syntax.

josefx
  • 15,506
  • 6
  • 38
  • 63