Where to put inner classes? [closed]

♀尐吖头ヾ 提交于 2019-12-03 14:25:32

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4730126/where-to-put-inner-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!