メソッドの理想的なサイズと単一責任の原則について読んだ後、自分のコードをいくつか見ていきます。私は自分のものの多く (>90%) を小さな管理しやすいメソッドに分割できると感じていますが、その後、データまたはフォームの検証に取りかかります。それはいつも本当に大きくて肥大しているように見えます。入れ子になった if ステートメントを使用してデータを検証し、各レベルでエラーや問題を見つけようとする傾向があります。しかし、6 レベル、8 レベル、10 レベル以上の検証を取得し始めると、非常に面倒です。しかし、それをより効果的に分割する方法がわかりません。
私が面倒だと思うが、それを改善する方法がわからないものの例を以下に示します。各レベルには固有のアクションが関連付けられており、すべての条件が true に戻った場合にのみ全体が戻ることができますがtrue
、特に 1 か月ほど後にプログラムに戻った後では、これを読むのは困難です。
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");
}