Depending on the type of software, some software has above-average requirements for availability, safety, or security. Often, in such projects, people practice pragmatic paranoia and coding styles called defensive programming.

The idea behind this approach is that your code should behave in a consistent and predictable manner — even in the case of unexpected conditions. In practice, you will need to defend against the impossible, because anything can become possible when the outside world is rapidly changing — new people join the team, code goes under maintenance, and dependencies upgrade. In fact, with humans, errors are always a possibility.

Jim Bird has gathered a set of rules on how to employ defensive programming in your codebase:

Protect your code from invalid data coming from outside, wherever you decide outside is. This could be any external system, file, or call from outside of the module/component. Because of this, it is essential to establish “trust boundaries” — everything outside of the boundary is dangerous, and everything inside of the boundary is safe. In the barricade code, validate all input data.

After you have checked for bad data, decide how to handle it. Defensive programming is NOT about swallowing errors or hiding bugs. Choose a strategy to deal with bad data, return an error, stop it right away (fast fail), return a neutral value, and, then, substitute data values. It is so important to make sure that the strategy is clear and consistent.

Don’t assume that a function call or method call outside of your code will work as advertised. Make sure that you understand and test error handling around external APIs and libraries.

Use assertions to document assumptions and to highlight “impossible” conditions. This is especially important in large systems that have been maintained by different people over time or in high-reliability code.

Next, you need to add diagnostic code, logging and tracing intelligently to help explain what’s going on at run-time, especially if you run into a problem.

It is also important to standardize error handling. You need to decide how to handle “normal errors” or “expected errors” and warnings consistently.

Such rules really work and help people craft reliable software, but when you use these approaches, your code can quickly become a mess. Sometimes, it’s hard to distinguish between verification code and underlying business logic. Check out this verification performed before transfer execution:

Verifier is built on the error handling pattern described by Rob Pike in the Go blog called Errors are values. This library is transparent and unopinionated. It is not here to handle errors for you. It won’t force you to any error handling style — you will be in control and decide what is better for your project.

If you want to learn more about it, please visit this Github page. You can also explore more thoughts on defensive and offensive programming here.