5

到目前为止,我的平均类包含大约 500 行代码和大约 50 个方法。IDE 是 Eclipse,我在其中打开了“保存操作”,以便方法按字母顺序排序,首先是公共方法,然后是私有方法。要在代码中查找任何特定方法,我使用“快速大纲”。如果需要,“Open Call Hierarchy”会显示方法的序列,因为它们一个一个地调用。

这种方法具有以下优点:

  • 我可以开始输入新方法而无需考虑将其放置在代码中的何处,因为保存后它将由 Eclipse 自动放置到适当的位置。
  • 我总是在代码的上部找到公共方法(不必在整个类中搜索它们)

但是也有一些缺点:

在将大方法重构为更小的方法时,我不太满意新的私有方法被放置在代码的不同部分,因此很难遵循代码概念。为了避免这种情况,我以一些奇怪的方式命名它们以使它们靠近每个,例如:showPageFirst()、showPageSecond() 而不是 showFirstPage()、showSecondPage()。

可能有一些更好的方法吗?

4

4 回答 4

4

Organize your code for its audiences. For example, a class in a library might have these audiences:

  1. An API client who wants more detail on how a public method works.
  2. A maintainer who wants to find the relevant method to make a small change.
  3. A more serious maintainer who wants to do a significant refactoring or add functionality.

For clients perusing the source code, you want to introduce core concepts. First we have a class doc comment that includes a glossary of important terms and usage examples. Then we have the code related to one term, then those related to another, then those related to a third.

For maintainers, any pair of methods that are likely to have to change together should be close by. A public method and its private helper and any constants related to it only should show up together.

Both of these groups of users are aided by grouping class members into logical sections which are separately documented.

For example, a collection class might have several mostly orthogonal concerns that can't easily be broken out into separate classes but which can be broken into separate sections.

  1. Mutators
  2. Accessors
  3. Iteration
  4. Serializing and toString
  5. Equality, comparability, hashing
于 2012-08-23T08:18:40.683 回答
3

Don't worry about physically ordering your methods inside the class, if you can't see it just use Ctrl-O and start typing the method name and you will jump straight to it.

Having self-describing method names results in more maintainable code than artificially naming them to keep them in alphabetical order.

Hint: learn your shortcut keys and you will improve your productivity

于 2012-08-23T08:15:55.240 回答
3

好吧,命名您的方法以便它们更容易在您的 IDE 中发现确实不好。他们的名字应该反映他们所做的,仅此而已。

作为对您问题的回答,最好的办法可能是将您的类拆分为多个类,并隔离在每个此类中具有共同点的方法组。例如,如果您有

public void largeMethodThatDoesSomething() {
 //do A
 //do B
 //do C
}

然后你已经重构了:

public void largeMethodThatDoesSomething() {
 doA();
 doB();
 doC();
}

private void doA() {};
private void doB() {};
private void doC() {};

您可以创建一个名为 SomethingDoer 的类,在其中放置所有这 4 个方法,然后在原始类中使用该类的实例。

于 2012-08-23T08:14:59.027 回答
1

组织你描述的方式听起来比我目前看到的 99% 的 Java 代码要好。但是,另一方面,请确保您的类不要增长太多并且方法不要太大。

类通常应少于 1000 行,方法应少于 150。

于 2012-08-23T08:09:37.913 回答