考虑一下:
在其中的例子你能马上告诉什么代码是应该做的?
实施例1
public static void main(String... args) {
A a = new A();
// CODE
// CODE
// CODE
// CODE
// ... 100 lines of setting up A
B b = new B(a);
// CODE
// CODE
// CODE
// CODE
// ... 100 lines of setting up B
// CODE
// CODE
// CODE
// CODE
// ... 500 other lines of code using a and b
}
实施例2
public static A setupA() {
A a = new A();
// CODE
// CODE
// CODE
// CODE
// ... 100 lines of setting up A
return a;
}
public static B setupB() {
B b = new B();
// CODE
// CODE
// CODE
// CODE
// ... 100 lines of setting up B
return b;
}
public static void doFancyAlgorithm(A a, B b) {
// CODE
// CODE
// CODE
// CODE
// 500 other lines of code using a and b
}
public static void main(String... args) {
A a = setupA();
B b = setupB();
doFancyAlgorithm(a, b);
}
显然,实施例2将是更容易阅读和理解,因为它由只有3条线和因为不同的责任被封装成不同的方法。通过查看方法序列,您将能够理解主要功能的作用,而无需了解所述方法的实际执行情况。而在示例1中,您需要遍历每行代码才能理解。
此外,还应考虑增加了一些新的功能,以您的代码:
public static void main(String... args) {
A a = setupA();
B b = setupB();
doFancyAlgorithm(a, b);
A a2 = setupA(); // new instance of a because we absolutely need that
C c = setupC();
doAnotherAlgorithm(a2, c);
}
现在设立的A
一个新实例的情况下,我们可以简单重用这让一切更容易的方法setupA()
。否则,我们需要重新编写整个100行的设置A.
这有另一个巨大的好处。如果您需要更改代码中的某些行,则只需将其更改为一个位置(即一次进入方法而不是代码发生的任何位置),这样可以防止疏忽,复制粘贴错误和等等。
谁说你必须? –
您应该问问编写该代码的人。 –
我认为最好的答案是获得Robert Martin的“Clean Code”的副本并阅读它。这应该解释为什么这是一个好主意。对于这样的非常小的方法,将所有内容都放入新方法可能并不值得,但这是一个很好的习惯。 – ajb