.net, C#,ASP.net

Thsi is my 2 cents on C#,.net programming

defensive coding

Defensive coding is bundling of known programming best practices so as the software works as expected even under unforeseen circumstances.

The basis of defensive coding are clean code and testable code. “Separation of Concerns” and unit tests or following TDD creates a good base for defensive coding.  Even small but significant stuff like using named arguments (C#)  goes a long way towards clean and defensive code.

A key aspect of defensive coding is validating the input parameters of methods and throwing appropriate exceptions if they are not as expected.

On the other hand, presence of a suitable mechanism to notify the calling method whether the call to a method succeeded or otherwise is equally important. This mechanism can be different for different family of methods.

  • We only want to know whether the call to a method succeeded or failed then it is fine that the method returns “Boolean.
  • We also want to know the reason for failure then a good technique is to return a custom object which has two properties a) Success = true/false  b) List<string> = failure messages.
  • Also returning null or use of “NULL Object”  design pattern is also an option (I prefer the later)

Avoid nested if statements, proper switch case (use enum and appropriately handle default case)  and cast operations will do no harm

Last but not the least, do catch only expected exceptions, have a global exception handler (technology specific) and perform logging as when needed.

A good starting point for Defensive Coding is http://www.pluralsight.com/courses/defensive-coding-csharp

References :

  1. http://en.wikipedia.org/wiki/Defensive_programming
  2. http://danielroop.com/blog/2009/10/15/why-defensive-programming-is-rubbish/
  3. http://geekswithblogs.net/sdorman/archive/2008/07/04/what-is-ldquodefensive-programmingrdquo.aspx
  4. http://blog.ploeh.dk/2013/07/08/defensive-coding/