有解决这里有两个问题:可读性和可理解
的“可读性”的解决方案是一个风格问题,因此有不同的解释。我的选择是这样的:
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