Note that there are some explanatory texts on larger screens.

plurals
  1. POHow often should I check the validity of the arguments?
    text
    copied!<p>Very frequently I encounter the similar architectural problem. How often should one check for validity of entered arguments? Let's check the following example (don't care about the code correctness or compileability):</p> <pre><code>public void DoSth() { context.DbPerform((SQLiteConnection connection) =&gt; { // *** 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 } </code></pre> <p>In the previous snippet, the connection has been checked for being null or closed for three times. This seems like a little bit of overkill for me - sometimes 50% of the method's body are the security checks. I don't feel like that much security checks are necessary, but on the other hand always someone else could have used these methods and I cannot be sure if he passed valid parameters.</p> <p>So my questions are:</p> <ul> <li>How often should one write security checks regarding passed parameters?</li> <li>What techniques may be used to retain the level of security, but without often security checks?</li> <li>How paranoid should I be while checking for invalid input? Consider another example:</li> </ul> <pre><code>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? } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload