Optimize ternary operator

后端 未结 6 1977
野的像风
野的像风 2021-02-03 18:49

I came across this code written by someone else. Is this usage of the conditional operator recommended or commonly used? I feel it is less maintainable - or is it just me? Is th

6条回答
  •  一向
    一向 (楼主)
    2021-02-03 19:45

    Others already said how awful that code excerpt is, with nice explanations. I will just provide few more reasons why that code is bad :

    1. if you consider one "if-else" to implement exactly one feature, then it is clear how complex that code is. In your case, I can not even count number of ifs.

    2. It is obvious that your code is breaking breaking the single responsibility principle, which tells :

      ...a class or module should have one, and only one, reason to change.

    3. unit testing that would be a nightmare, which is another red flag. And I bet that your colleague didn't even try to write unit tests for that piece of code.

提交回复
热议问题