do this without using an “if” | if(s == “value1”){…} else if(s == “value2”) { …}

前端 未结 18 2237
温柔的废话
温柔的废话 2021-01-30 09:36

According to anti-if campaign it is a best practice not to use ifs in our code. Can anyone tell me if it possible to get rid of the if in this piece of code ? (switch is also

18条回答
  •  爱一瞬间的悲伤
    2021-01-30 10:02

    i'd like to point out that so far, every answer to this question with a code example has a solution that is far more complicated than the original code, and likely much slower.

    this is a classic case of an optimization being performed in entirely the wrong context. in some cases, code will become clearer through using OO properly, such as eliminating long chains of type checks. however, simply removing all if statements for the sake of removing them only serves to obfuscate your code.

    the if statements (conditional jumps) are still going to happen, be it in your code or the interpreter. keeping them lexically close has many readability and maintenance advantages that are lost through excessive OO use. there is a balance that must be struck between local vs distant logic, but it should never spill over into obfuscation.

    for the question at hand, the clearest construct that will avoid the if is probably a hash table / associative array containing anonymous functions, which, for a small number of keys, is effectively just a slow switch statement.

提交回复
热议问题