avoiding if statements

前端 未结 24 1089
心在旅途
心在旅途 2021-01-30 08:39

I was thinking about object oriented design today, and I was wondering if you should avoid if statements. My thought is that in any case where you require an if statement you ca

24条回答
  •  悲&欢浪女
    2021-01-30 09:19

    It depends on what the original statement is comparing. My rule of thumb is that if it's a switch or if testing equality against an enumeration, then that's a good candidate for a separate method. However, switch and if statements are used for many, many other kinds of tests -- there's no good way to replace the relational operators (<, >, <=, >=) with specialized methods, and some kinds of enumerated tests work much better with standard statements.

    So you should only replace ifs if they look like this:

    if (obj.Name == "foo" || obj.Name == "bar") { obj.DoSomething(); }
    else if (obj.Name == "baz") { obj.DoSomethingElse(); }
    else { obj.DoDefault(); }
    

提交回复
热议问题