re: A simple tip for cleaner code VIEW POST

re: Looks like the simplicity of my example stands in the way of the message I'm trying to convey. If we take the examples literally there is no issu...

Yes your example was a simple one, though simplicity is not a factor as any program can be expressed as a single expression, regardless of the simplicity. Therefore any example can be converted into a conditional ternary. Though it may is possible not look the cleanest or be the best solution.

But if we have code between the condition and the return statement, you cannot use a ternary oh enlightened one ;)

☝️ This statement can be proven false with this block of code:

const foo = bar =>
  bar > 0 ? (
    console.log('Execute some code here for YES'),
  ) : bar === 0 ? (
    console.log('Execute some code here for MAYBE'),
  ) : (
    console.log('Execute some code here for NO'),

To demonstrate my point that you can write any application as a single expression, you can read my article where I have written a fully functional Promise library, a fairly complex program, as a single function expression. dev.to/joelnet/challenge-program-w...

The good thing about using a ternary operator is that when the operator becomes complicated, it is a signal that your function needs to be broken down into smaller pieces. Where as with the if statement, you can easily add too many statements without receiving this signal and end up with a function that breaks the Single Responsibility rule.

  • The Enlightened One

mic drop

Just because you can do something does not mean you should, have fun maintaining your library :)

Just because you shouldn't do something it doesn't mean you can't ;)

code of conduct - report abuse