Using Action dictionaries instead of switch statements

后端 未结 4 1493
庸人自扰
庸人自扰 2020-12-09 03:13

I\'m just reviewing some of my old code (have some spare time), and I noticed a rather lengthy switch statement. Due to gaining new knowledge, I have since refactored it in

4条回答
  •  感情败类
    2020-12-09 03:37

    Long switch statements are a classic bad smell, and are always a target for refactoring.

    The "standard" step to perform here is Replace Conditional with Polymorphism. This was one of the steps listed in Martin Fowler's book Refactoring (published 11 years ago in 1999).

    Now that it's so easy to treat functions like objects (eg with Action) this might be just as good a solution.

    And no, I don't think you're being clever for the sake of it. If I wanted to add another option in the future, I can easily see what needs to be done.

提交回复
热议问题