DEV Community

Discussion on: Defensive programming – Code Craft

Collapse
 
loki profile image
Loki Le DEV

Thanks that's a lot of rules and terms to learn.

Working on a medical exoskeleton we had a lot of discussions and tried several methods on how to apply offensive/defensive programming.

For example we can't afford to just "let it crash" in case of bad food (invalid input values in methods) or invalid state because the device should keep working in all situations.
So we have fallbacks to put the exoskeleton in a safe mode when an unrecoverable error is detected.

Collapse
 
10xlearner profile image
10x learner

Indeed 😄, it depends on what your program does and the risks that having it crash involve.

For example, if your program is a simple calculator, it won't cause any harm if it crashes from a bad input. In that case, you can be more offensive, with a good test suite.

But if a bug in your program can cause some big material or financial damages or hurt people because of a bug, you should definitely use a lot of guards and defensive mechanisms to be sure to never encountered such bad case.

I will add that this idea can be applied to sub part of a program. For example, having the part of your program which handle the logs doesn't necessary need to be as much guarded as the part which make an exoskeleton move.

Moreover, if your system is really critical, you can double check the behavior.
To go back on the exoskeleton example, you could imagine having a chip with a captor on each articulation, looking at the angle performed by the exoskeleton, and if the angle start to become to wide for a human, the chip could force the articulation to go back to a safe state, overwriting orders from the main program of the exoskeleton.