Why Fail-fast Offensive Programming is better?

I personally prefer fail-fast (offensive) over fail-safe (defensive) programming style because it is practical and improves my code productivity.


2 min read

Why Fail-fast Offensive Programming is better?

I once had a discussion with my boss, and we never came to a conclusion because he is a fail-safe guy, and I'm a fail-fast guy. So, who is correct? Or is this merely a personal choice?

Why I Prefer Fail-fast?

In this article, I'm going to share with you 3 reasons why I prefer fail-fast offensive programming style.

1. Validate My Assumptions

Fail-fast validates my assumptions. In coding, we often make assumptions and our assumptions mostly wrong at first because we simply don't fully understand the system. Fail-fast / offensive programming style can quickly validate my assumptions. Each time my code fails, it makes me a better programmer.

2. Less Conditional Logics

Fail-safe code usually comes with more conditional logics. If this fails, do another thing and if that fails again, do something else. When proper clean architecture is NOT being done correctly, the fail-safe code could become very messy. Fail-fast simply removes this unnecessary conditional checks.

3. Pinpoint Root Cause Faster

Because fail-fast code fails the code immediately, the reported error or exception typically quite close to the actual root cause. This reduces the debugging time significantly. When fail-safe code fails, you will have a hard time finding the root cause because it is not supposed to fail in the first place.

When I Use Fail-safe?

Well, I still use a fail-safe approach only when dealing with code (e.g. external libraries) that is not within my control. You want your system to be robust to handle any errors or exceptions from this external libraries. Another example is dealing with external dependencies. For example, a network call or file system call which will throw exceptions.

Final Thoughts

In my opinion, fail-safe defensive programming style is too ideal and not practical because you can't 100% guarantee bug free and cover all scenarios. When there is a bug, it is harder to find the root cause. Have you ever work on the code base when something fails, and you have no clue at all? It takes you many hours or days to figure out the problem.

So my coding approach is I always do fail-fast first to validate all the assumptions. If the software fails, and I can't fix the issue (due to not within my control), I will convert the code to be fail-safe. Eventually, the fail-fast approach can also lead to a robust system.

Which approach do you prefer?

Did you find this article valuable?

Support Vincent Tsen by becoming a sponsor. Any amount is appreciated!