DEV Community

Discussion on: What is Defensive Coding?

Collapse
 
acroynon profile image
Adam Roynon

I believe this can be argued either way. I didn't want to get into exceptions and what they are in this post, as I wanted to concentrate on just defining what defensive coding is and how it looks.

Returning a valid value is a good way to avoid returning null values and therefore littering your code with null checks. It can also prevent increasing the cyclomatic complexity of your code.

Throwing an exception would require a new code path to be created. If you just threw the exception without handling it then your program would exit immediately, making the code brittle and therefore not 'defended'. In the example of the 'multiply' function you either put a try/catch in this function and still have to return a value, or put a try/catch higher up and have to define a new code path.

Both ways are completely fine, but depending on the context of the surrounding code/functionality one may be a better choice.

Thank you for the feedback and comment, I really appreciate it.