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
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 if
s if they look like this:
if (obj.Name == "foo" || obj.Name == "bar") { obj.DoSomething(); }
else if (obj.Name == "baz") { obj.DoSomethingElse(); }
else { obj.DoDefault(); }