Skip to content

Defensive coding

von Schappler edited this page Oct 18, 2024 · 1 revision

What is defensive coding?

Sometimes when inspecting a TypeScript error, it's possbile to see a message saying that Object can possibly be undefined.

This is then a good opporunity to explain two premises that are common when working with code:

  • The "Happy path"

    This path assumes that everything will aways work perfectly. This tends to be the code that new developers will write.

    This is the easiest code to write, and so, it comes with the temptation of simply moving on, because "everything will work" after we push the code to production.

  • The "Sad path"

    This path will always assume that problems may occur - which forces developers to think aread and prepare their code for situations in which errors can happen on the procution version of their codes.

    So this is a way of writing "defensive" code bases - but keep in mind that this path is not as easy to follow because the developr must really thing about ALL the possible cases where an error may occur as well as think about all the possible "weird" ways in which the users can interact with our application.

We as developers should always follow the "sad path" when writing our code and a good way to start writing defensive code can be done by simply adding error check helper functions, so always consider this when writing your code!

Clone this wiki locally