loading...

re: Nested Conditional Operators VIEW POST

FULL DISCUSSION
 

I think the fact that the design of a conditional (especially ternary) is not restrictive says nothing of how it is used. I find in most cases where I desire to write less code, that using a normal if conditional is actually better even if it promotes greater nesting.

I have been developing more classic writing habits of late though, so take that with a grain of salt? I prefer conditionals with closure to support flexible scope without rewriting anything, and they clearly define line-breaks. My writing preference of your function would look something like this (I don't fully understand Promises yet):

function(f1, f2, f3){
  if( !f1 ){ new Error('Missing field1'); }
  if( !f2.constructor.name === 'Array' ){ new TypeError('field2 not an array'); }
  if( !isValidType(f3) ){ new Error('field3 is invalid'); }
}

Taking a look at your function, for example; I would write this as separate conditional checks because they are not related to one another. This is a pattern I find useful when designing other functions, often I only want to check for a single condition, not a chain of if/else conditions. In this function, you only want to return a rejection if a field fails a conditional check. Try to think of it as 'If this is true than do this', not 'if this is true do this, otherwise check for these things and do this'.

This is what the if/else would look like using normal conditionals.

if( !f1 ){
  new Error('Missing field1');
else{

  if( !f2.constructor.name === 'Array' ){
    new TypeError('field2 not an array');
  else{

    if( !isValidType(f3) ){
      new Error('field3 is invalid');
    }
  }
}

return true; // resolve

As for ternary conditionals, I only ever write them inline for simple checks and I have read and agree that they should not be nested more than 1-2 levels.

function test( a ){
  const valueExists = a ? true : false;

  if( valueExists){ return a; }
  // otherwise...(and no need for an else{})
  return false;
}
Code of Conduct Report abuse