非常に頻繁に、同様のアーキテクチャの問題に遭遇します。入力された引数の妥当性をどのくらいの頻度でチェックする必要がありますか? 次の例を確認してみましょう (コードの正確性やコンパイル可能性は気にしないでください)。
public void DoSth()
{
context.DbPerform((SQLiteConnection connection) =>
{
// *** 1 ***
if (connection == null)
throw new ArgumentNullException("connection");
if (!connection.IsOpen)
connection.Open();
try
{
Data.Insert(data, connection);
}
finally
{
connection.Close();
}
});
}
// ----
public static void Insert(Data data, SQLiteConnection connection)
{
// *** 2 ***
if (data == null)
throw new ArgumentNullException("data");
if (connection == null)
throw new ArgumentNullException("connection");
if (!connection.IsOpen)
connection.Open();
try
{
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = SQL.InsertData;
FillParameters(data, connection, cmd);
cmd.ExecuteNonQuery();
}
}
finally
{
connection.Close();
}
}
// ----
public static void FillParameters(Data data,
SQLiteConnection connection,
SQLiteCommand cmd)
{
// *** 3 ***
if (connection == null)
throw new ArgumentNullException("connection");
// And so on, you get the idea
}
前のスニペットでは、接続が null またはクローズされているかどうかが 3 回チェックされています。これは私には少しやり過ぎのように思えます。メソッド本体の 50% がセキュリティ チェックである場合もあります。それほど多くのセキュリティチェックが必要だとは思いませんが、一方で、他の誰かが常にこれらのメソッドを使用する可能性があり、彼が有効なパラメーターを渡したかどうかはわかりません.
だから私の質問は:
- 渡されたパラメーターに関するセキュリティチェックをどのくらいの頻度で作成する必要がありますか?
- セキュリティのレベルを維持するために使用できる技術は何ですか?
- 無効な入力をチェックしている間、どの程度偏執的である必要がありますか? 別の例を考えてみましょう:
class C
{
private Obj obj;
public C (Obj newObj)
{
if (newObj == null)
throw new ArgumentNullException("newObj");
obj = newObj;
}
public void DoSth()
{
// Should I check, whether obj is not null?
}
}