I very much agree with this.

I very much agree with this. If your software is going to fail, then it’s always better that it fails as quickly as possible. This principle is at the heart of defensive programming.

Originally shared by Geoffrey De Smet

The importance of Fail Fast for reusable software libraries and frameworks cannot be underestimated. With Fail Fast, invalid input/state is detected where it’s created and a clear, understandable Exception is thrown. Without it, an obscure Exception (usually NPE) is thrown later and there’s no clue as to what created the invalid state.

There are several levels of Fail Fast, from better to worse:

1) Fail Fast at compile time. For example: don’t accept an Object as parameter if it needs to be a String or an Integer.

2) Fail Fast at startup time. For example: if the configuration parameter needs to be a positive int and it’s negative, fail fast.

3) Fail Fast at runtime. For example: if the request needs to contain a double between 0.0 and 1.0 and it’s bigger than 1.0, fail fast.

4) Fail Fast at runtime in assertion mode, if the detection performance cost is high. For example: if, after every low level iteration, the variable A needs to be equal to the square root of B, check it if and only if the assertionMode flag is set to true.

The net result of this is clearer exceptions at development time, better detection in QA and less issues in production.