What is the best way to replace or substitute if..else if..else trees in programs?

后端 未结 21 1126
迷失自我
迷失自我 2020-11-28 06:23

This question is motivated by something I\'ve lately started to see a bit too often, the if..else if..else structure. While it\'s simple and has its uses, somet

21条回答
  •  清酒与你
    2020-11-28 07:22

    The Map method is about the best there is. It lets you encapsulate the statements and breaks things up quite nicely. Polymorphism can complement it, but its goals are slightly different. It also introduces unnecessary class trees.

    Switches have the drawback of missing break statements and fall through, and really encourage not breaking the problem into smaller pieces.

    That being said: A small tree of if..else's is fine (in fact, i argued in favor for days about have 3 if..elses instead of using Map recently). Its when you start to put more complicated logic in them that it becomes a problem due to maintainability and readability.

提交回复
热议问题