2021年1月4日星期一

JavaScript Switch/Case Best Practices for Complex Logic Trees

I've recently been in a code syntax formatting debate and would like to get the opinion of the broader JavaScript community. I personally prefer this switch/case structure for complicated condition trees but other developers seem to dislike it. Below I will post my preferred switch/case structure and the if/else equivalents.

Rather than debate preferences, why is this switch/case code acceptable or unacceptable and the specific reasons? If the other alternatives are better, why?

// My preferred switch/case block    switch (true) {    case testA()              : return 'A';    case testB() || testG()   : return 'B';    case testC()              : return 'C';    case testA() && !testB()  : return 'ZETA';    case a === b && c !== d   : return 'foo';    default                   : return 'bar';  }    // if-else alternate #1    if (testA()) {    return 'A';  }  if (testB() || testG()) {    return 'B';  }  if (testC()) {    return 'C';  }  if (testA() && !testB()) {    return 'ZETA';  }  if (a === b && c !== d) {    return 'foo';  }  return 'bar';    // if-else alternate #2    if (testA())               return 'A';  if (testB() || testG())    return 'B';  if (testC())               return 'C';  if (testA() && !testB())   return 'ZETA';  if (a === b && c !== d)    return 'foo';  return 'bar';  
https://stackoverflow.com/questions/65572220/javascript-switch-case-best-practices-for-complex-logic-trees January 05, 2021 at 09:58AM

没有评论:

发表评论