I am thinking about posting about different principles/patterns over the next
few weeks/months. I have decided to start with Fail Fast. This is something
that I think most people over look or plain just don't do.
Although the concept of Fail Fast is easy and straight forward, in most
systems I have seen it is rarely ever used or followed. The underlying concept
of Fail Fast can be summed up as follows. Design your system or code so that it
will check for and report any possible failures and report them as soon as
possible. Testing your code for failure points will lead to better, safer, more
When adding your failure checks it is best to try to think about how the code
can fail. Think about what the error message/stack trace will look like. If by
adding the failure checks the message will become clearer and easier to debug,
add the check. If the check will not make for a better message or make
debugging simpler maybe you don't add the check.
What does a system do that does not Fail Fast? Fail often is my answer.
Most systems that don't attempt some sort of Fail Fast will work around
failures. These work around's can be as simple as 'defaulting' values from
config files if the value is missing. These could also be as outlandish as
accepting bad data via a web service, trying to fix the data, failing and not
reporting back the failure to the caller of the web service.
Few Fail Fast techniques I follow:
One of the things I like to do for my failure checking is to check parameters
on public methods. I like to add asserts to the top of my method to check to
make sure the params are valid. Valid could be Non-null (yes I know you could
let the runtime throw a NullRef Exception, but I like constancy), valid string
lengths, numeric's are within valid ranges, etc. By performing these checks
before I perform a single line of code, I feel safe that my code will execute
later on in the method.
Example 1 on checking params:
Example 2 on checking params:
Another thing I like to do is check values that are returned from outside
calls from within my methods. Lets say I have a method that calls out to
another method to return me an object. I like to make sure that the object
returned is valid, and if not throw a failure exception.
Example on checking return values:
If you try to follow Fail Fast you will find that your system may 'fail' more
during the initial development, but as you move forward your application should
be cleaner and more stable.
Martin Fowler on Fail Fast - Here
Wikipedia on Fail Fast - Here
06-08-2007 1:08 PM