有解決這裏有兩個問題:可讀性和可理解
的「可讀性」的解決方案是一個風格問題,因此有不同的解釋。我的選擇是這樣的:
if (var1 == true && // Explanation of the check
var2 == true && // Explanation of the check
var3 == true && // Explanation of the check
var4 == true && // Explanation of the check
var5 == true && // Explanation of the check
var6 == true) // Explanation of the check
{ }
或本:
if (var1 && // Explanation of the check
var2 && // Explanation of the check
var3 && // Explanation of the check
var4 && // Explanation of the check
var5 && // Explanation of the check
var6) // Explanation of the check
{ }
這就是說,這種複雜的檢查可以說是相當困難的,而掃描碼(在精神上解析,特別是如果你是不是原作者)。考慮創建一個輔助方法,以抽象的一些複雜性遠:
/// <Summary>
/// Tests whether all the conditions are appropriately met
/// </Summary>
private bool AreAllConditionsMet (
bool var1,
bool var2,
bool var3,
bool var4,
bool var5,
bool var6)
{
return (
var1 && // Explanation of the check
var2 && // Explanation of the check
var3 && // Explanation of the check
var4 && // Explanation of the check
var5 && // Explanation of the check
var6); // Explanation of the check
}
private void SomeMethod()
{
// Do some stuff (including declare the required variables)
if (AreAllConditionsMet (var1, var2, var3, var4, var5, var6))
{
// Do something
}
}
現在,當視覺掃描「的someMethod」方法,測試邏輯的實際複雜性是隱藏的,但語義是保存人類在理解一個高層次。如果開發人員真的需要了解詳細信息,可以檢查AreAllConditionsMet方法。
這正式被稱爲「分解有條件」重構模式,我認爲。像Resharper或Refactor Pro這樣的工具!可以使這種重構變得容易!
在所有情況下,具有可讀性和可理解性代碼的關鍵是使用現實的變量名稱。雖然我明白這是一個人爲的例子,「var1」,「var2」等是而不是可接受的變量名稱。他們應該有一個反映他們所代表的數據的潛在性質的名字。
簡單,容易做的,有效的。 – 2010-05-13 11:12:20