Dealing with nested if then else/nested switch statements

前端 未结 7 1521
走了就别回头了
走了就别回头了 2020-12-30 08:43

Are there any design patterns/methods/ways to remove nested if then else conditions/switch statements?

I remember coming across some methods used by the Google folks

7条回答
  •  时光说笑
    2020-12-30 08:53

    I actually wrote about how to solve this issues in my blog in April of 2008. Take a look here and let me know what you think.

    I recommend you:

    1. Use polymorphism to get the correct run-time behavior you need without conditional statements.

    2. Take all your conditional statements, and move them into some sort of "factory" which will hand you the appropriate type at run-time.

    3. You're done. Wasn't that easy? :)

    If you want to see some actual code sample on how transform your code, head over to my blog.

    P.S. This is not a cheap attempt at self promotion; I've been a SO user for a long time now, and this is the first time I've linked to my blog - and I've only done so because I think it's relevant.

提交回复
热议问题