考慮一下:
在其中的例子你能馬上告訴什麼代碼是應該做的?
實施例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