2016-09-23 59 views
2

我已經閱讀了幾本OOP書,其中強調了定義具有重點責任集合的類的規則。在我工作過的大量應用程序中,大部分時間都在遵守。然而,我看到很多情況下,很多邏輯被傾倒到一個單一的方法中,很難理解/單元測試。定義方法時需要遵循的最佳實踐是什麼?方法的重點責任

+1

當我讀完'清潔代碼,作者 - 羅伯特馬丁'後,我完全檢查了我的代碼。閱讀它很容易和快速。重點在於重構,保持代碼清潔,如何組織結構以及如何不重複自己。 –

+0

謝謝@AndriiAbramov –

+0

也稱爲單一職責原則,SOLID的S:一個班級應該只有一個理由來改變(Robert C. Martin)。 – sp00m

回答

1

作爲例子,讓我們來看看下面的方法:

public static void printDetails() { 
    System.out.println("Current time: " + LocalTime.now()); 
    System.out.println("Current date: " + LocalDate.now()); 

    System.out.println("Available processors: " + Runtime.getRuntime().availableProcessors()); 
    System.out.println("Max memory: " + Runtime.getRuntime().maxMemory()); 
    System.out.println("Free memory: " + Runtime.getRuntime().freeMemory()); 
} 

一些重構之後,我們有更多的可讀性和可維護性的版本:

public static void printDetails() { 
    printDateTimeDetails(); 
    printProcessorDetails(); 
    printMemoryDetails(); 
} 

更容易閱讀。而更重要的是 - 測試更容易。 當你閱讀這個方法的主體時,你清楚地知道它的目的。如果你需要更多的細節,你可以在代碼中更深入地看看每種方法的作用。

public static void printProcessorDetails() { 
    System.out.println("Available processors: " + getAvailableProcessors()); 
} 

public static int getAvailableProcessors() { 
    return Runtime.getRuntime().availableProcessors(); 
} 

public static void printMemoryDetails() { 
    System.out.println("Max memory: " + getMaxMemory()); 
    System.out.println("Free memory: " + getFreeMemory()); 
} 

public static long getFreeMemory() { 
    return Runtime.getRuntime().freeMemory(); 
} 

public static long getMaxMemory() { 
    return Runtime.getRuntime().maxMemory(); 
} 

private static void printDateTimeDetails() { 
    System.out.println("Current time: " + LocalTime.now()); 
    System.out.println("Current date: " + LocalDate.now()); 
} 

而且這樣的代碼也是可重複使用的。

童子軍有一條規則:「永遠不要讓露營地比你找到的地方清潔。」實際上,這個規則的最初形式是由偵察之父羅伯特·斯蒂芬森·史密斯·巴登 - 鮑威爾寫的,「試着讓這個世界比你找到的好一點。」

當然這一切都在我看來。

+0

非常感謝@Andrii –

2

普遍的共識是決定什麼方法應該做的最好的方法是遵循Do One Thing哲學。

每種方法都應該只做一件事和一件事。

+0

謝謝,請看鏈接! –