47

Some might like to argue that this is a candidate for the least important issue of all times. Yet code style is a very important topic for me, and I want to ensure that I write code in a readable way - for me and the majority of developers.

That's why I'm wondering where you guys are declaring your inner classes.

I'm following the following method ordering scheme, because it is quite common:

public void foo() {
    usedByFoo();
}

private void usedByFoo() {
}

public void bar() {
}

I order them from top to bottom, every method as close to where it is used.

Now I could do the same with inner classes, like this:

class Outer {
    private Inner inner;

    private class Inner {};

    public Outer() {
    }

    ...
}

I think this is the most consistent style to follow for me, but I've also often seen people declare all inner classes either at the top or at the bottom of the file.

Which style should I follow, given my way of ordering methods? What is the most common way to do this?

Etienne Neveu
  • 12,604
  • 9
  • 36
  • 59
Jason Noack
  • 475
  • 1
  • 4
  • 6

2 Answers2

66

I would declare inner-classes in the bottom of the file - usually you're not interested in their implementations and just want to get to your main class' methods, so they shouldn't get in the way.

Amir Rachum
  • 76,817
  • 74
  • 166
  • 248
  • 9
    I'd add to this that if there are so many inner classes that it becomes confusing, it's time to factor some of them out into top level classes. – biziclop Jan 18 '11 at 23:37
  • Pretty much upvotes and no other answer, guess that's the way to go then, thanks! – Jason Noack Jan 19 '11 at 00:19
11

My preferred style is to put them wherever they seem to make most sense. Usually this is at the bottom so they're out the way, but sometimes I find it makes more sense to put them before a certain group of methods (if these are the methods that use the inner class.)

If the class gets too unwieldy with loads of methods and inner classes though, it's probably a bad design choice (cohesion is too low.) I've sometimes let classes get this way by accident and they're horrible to deal with later - these days if I can see one going that way I'll generally refactor it out, perhaps even into its own package. If you get to the point where you've got so many inner classes you don't know what to do with them, I'd take this approach. There's even some that advise against using inner classes at all for this reason (though I disagree - they're a valuable resource when used properly, you just need to take care they don't get out of hand.

Michael Berry
  • 70,193
  • 21
  • 157
  • 216