6

Any recommendations on how to use anonymous classes while staying consistent with Allman indent style? I don't really like anything I've come up with, e.g.

// Pass as parameter.
foo(new Clazz( )
    {
       // Do stuff.
    });

// Assign to variable.
Clazz bar = new Clazz( )
            {
               // Do stuff.
            };
gdejohn
  • 7,451
  • 1
  • 33
  • 49
  • 1
    whats wrong with what you have posted? why don't you like it? – luke Dec 21 '10 at 00:12
  • 1
    Line terminators end up in arbitrary positions, and brackets aren't vertically aligned (the parentheses enclosing the method call's arguments, for example), which defeats the purpose of Allman style. – gdejohn Dec 21 '10 at 00:20

3 Answers3

2

The best compromise I came up with for my own code, is indenting the anonymous class a single tabbing level, and putting the closing parentheses on a new line.

// Pass as parameter.
foo(new Clazz( )
    {
       // Do stuff.
    }
);

void func () {
    foo(new Clazz( )
        {
           // Do stuff.
        }
    );
}

// Assign to variable.
Clazz bar = new Clazz( )
    {
        // Do stuff.
    };
Zaven Nahapetyan
  • 1,259
  • 1
  • 10
  • 15
1

Allman style is really about aligning the {braces}, not all the (brackets). I suppose you are free to do both if you want, but it looks like a source of problems (like this one) to me, without a clear payback in readability. In other words, a logical fetish :-)

You could follow the guide at http://mbreen.com/javastyle.html: "A statement containing a declaration with a code block is indented first as a statement." I think that would change your examples to

foo (new Clazz( )
    {
        // Do stuff.
    });

Clazz bar = (
    new Clazz( )
    {
        // Do stuff.
    });
0

This is what I've settled on.

Foo foo = new Foo()
{
    // Do stuff.
};

And I just don't define anonymous classes inside method calls anymore.

gdejohn
  • 7,451
  • 1
  • 33
  • 49