我一直在阅读有关方法的理想大小和单一职责原则的信息,然后我去看看我的一些代码。我觉得我可以将很多(>90%)的东西分解成小的可管理的方法,然后我可以验证数据或表单。它总是看起来非常大而且臃肿。我倾向于使用嵌套的 if 语句验证我的数据,并尝试在每个级别捕获错误或问题。但是当我开始获得 6、8、10+ 级别的验证时,这非常麻烦。但我不确定如何将其分解以更有效。
下面是一个我认为很麻烦但不确定如何改进的例子。每个级别都有一个与之相关的独特动作,只有当所有条件都返回 true 时,整个事情才能返回true
,但这很难阅读,尤其是在一个月左右后回到程序之后。
if (InitialUsageSettings.zeroed || sender.Equals(btnZero))
{
if (InitialUsageSettings.StandardFilterRun || sender.Equals(btnStandard))
{
if (InitialUsageSettings.ReferenceFilterRun || sender.Equals(btnReference) || sender.Equals(btnStandard))
{
if (InitialUsageSettings.PrecisionTestRun || sender.Equals(btnPrecision) || sender.Equals(btnReference) || sender.Equals(btnStandard))
{
if (txtOperatorID.Text.Length > 0 && cboProject.Text.Length > 0 && cboFilterType.Text.Length > 0 && cboInstType.Text.Length > 0)
{
if (txtFilterID.Text.Length > 0 && txtLot.Text.Length > 0)
{
return true;
}
else
{
if (txtFilterID.Text.Length == 0)
{
//E
}
if (txtLot.Text.Length == 0)
{
//D
}
}
}
else
{
if (txtOperatorID.Text.Length == 0)
{
//A
}
if (cboProject.Text.Length == 0)
{
//B
}
if (cboFilterType.Text.Length == 0)
{
//C
}
if (cboInstType.Text.Length == 0)
{
//D
}
//return false;
}
}
else
{
outputMessages.AppendLine("Please correct the folloring issues before taking a reading: X");
}
}
else
{
outputMessages.AppendLine("Please correct the folloring issues before taking a reading: Y");
}
}
else
{
outputMessages.AppendLine("Please correct the folloring issues before taking a reading: Z");
}
}
else
{
outputMessages.AppendLine("Please correct the folloring issues before taking a reading: A");
}