Fail-Fast Pattern/Policy – Fail early with context

How often have you had to fix a run-time error and taken hours or even days to track down the root cause? Using the Fail-Fast policy can all but eliminate such troubles.

The key concept is to fail early, that is as soon as you can programmatically detect bad data exists throw an exception reporting useful contextual information.

e.g.
using System.Reflection;
…..
DataRow drWorkingData = someoneElseClass.FindTheRow(iPrimaryKey);
if (drWorkingData == null)
 throw new ApplicationException(
  “Failed to find data for Primary Key >” + iPrimaryKey + “<“ +
  “[“ + MethodInfo.GetCurrentMethod().DeclaringType.FullName +
“.” +  MethodInfo.GetCurrentMethod().Name + “()]”);

In this example had we not used a Fail-Fast policy the code would have continued until drWorkingData was referenced, at which point the run-time would automatically throw a null object exception. If you have debugged much code in your life, you will realize that this error could be thrown quite a distance from the original source of the error.

Note the use of reflection to obtain the location of the error. This is my most prevalent cut-and-paste reuse. An obvious improvement would be to encapsulate it in a utility class, and walk a step up the call-stack to report the method’s class and name. That is beyond my knowledge of .Net Reflection.

Also note that instead of using ApplicationException I always use a custom Exception called FailFastException which makes it very easy to trap such errors in a central location and report/ log them in a consistent fashion.

This entry was posted in Uncategorized. Bookmark the permalink.