DEV Community

Discussion on: Is “Defensive Programming” actually healthy?

Collapse
 
cubiclebuddha profile image
Cubicle Buddha

How does getting rid of the chained ifs help? I’d have to see an example to understand what you mean.

As for your point about throwing an error, why would a runtime exception be a better option?

When would you identify that an error was being thrown? (My assumption is that the the error will first manifest in production when the users will suffer the consequence. As where with a compilation error you can catch the logical mistake before the code even hits production)

Collapse
 
mazentouati profile image
Mazen Touati

As I mentioned I was talking In General.

1) The if part: I meant making an early decisions may add more flexibility to your code for example

// You may use this
() => {
  if (condition1) {
    return 1;
  }

  // Maybe another logic in between

  if (condition2) {
    return 2;
  }

  return default;
}

// Instead of this
() => {
  if (condition1) {
    return 1;
  } else if (condition2) {
    return 2;
  } else {
    return default;
  }
}

Usually, it would make the code more readable and maintainable.

2) Well, my statement regarding the run-time exception was a little bit biased by the Open-Closed Principal as I mentioned. Which suggests making the code extensible without actually changing the base code itself.
Another reasons I was thinking about:

  • Not all languages are compiled.
  • May be another developer or team ( That happens he/it is not a big fan of Typescript ) try to use the JavaScript version of your code.
  • In some cases may be the user try to maliciously change the values (for example your are expecting values from a predefined select menu => the user may alter the values before sending them). As I said earlier it's a personal taste and not related exactly to your specific example.

3) I think that we have to be creative about this point, making an application that is tolerant to run-time errors is always challenging and great (Maybe for your example, you can use the previous state as a fallback when a signal is not defined or maybe you can define an emergency safe state that avoids all damage maybe a pull-over state ). Also, it totally depends on the situation for uses cases with low tolerance to errors your approach may be appropriate for extent ( still you are not dealing with unexpected run-time errors ).

I hope that you got what I'm trying to illustrate.