反 - 如果运动 [英] anti-if campaign
问题描述
问题:给定一个场景,我有一个嵌套的复合IF或SWITCH语句,用于评估给定类型的事情(比如说评估一个枚举)来确定我想如何处理这个事情的枚举类型 - 有什么方法做同样的处理方式,而不使用IF或者SWITCH层次结构?
public enum WidgetTypes
{
Type1,
Type2,
Type3,
Type4
}
...
WidgetTypes _myType = WidgetTypes.Type1;
...
开关(_myType)
{
case WidgetTypes.Type1:
//做某事
break ;
case WidgetTypes.Type2:
//做某事
break;
// etc ...
}
问题不在于'if'语句,而是程序员编写错误代码。
编辑:另外,正如其他人所指出的那样当您使用if语句检查对象的类型时,您应该使用多态(如果可用),但是如果自身中的语句非常有用和基本的结构。
I recently ran against a very interesting site that expresses a very interesting idea - the anti-if campaign. You can see this here at www.antiifcampaign.com. I have to agree that complex nested IF statements are an absolute pain in the rear. I am currently on a project that up until very recently had some crazy nested IFs that scrolled to the right for quite a ways. We cured our issues in two ways - we used Windows Workflow Foundation to address routing (or workflow) concerns. And we are in the process of implementing all of our business rules utilizing ILOG Rules for .NET (recently purchased by IBM!!). This for the most part has cured our nested IF pains...but I find myself wondering how many people cure their pains in the manner that the good folks at the AntiIfCampaign suggest (see an example here) by creating numerous amounts of abstract classes to represent a given scenario that was originally covered by the nested IF. I wonder if another way to address the removal of this complexity might also be in using an IoC container such as StructureMap to move in and out of different bits of functionality. Either way...
Question: Given a scenario where I have a nested complex IF or SWITCH statement that is used to evaluate a given type of thing (say evaluating an Enum) to determine how I want to handle the processing of that thing by enum type - what are some ways to do the same form of processing without using the IF or SWITCH hierarchical structure?
public enum WidgetTypes
{
Type1,
Type2,
Type3,
Type4
}
...
WidgetTypes _myType = WidgetTypes.Type1;
...
switch(_myType)
{
case WidgetTypes.Type1:
//do something
break;
case WidgetTypes.Type2:
//do something
break;
//etc...
}
The problem is not the 'if' statement, it is the programmers who write bad code.
EDIT: Also, as others have pointed out, you should be using polymorphism (if available) when you are using if statements to check the type of an object, but if statements in and of themselves are very useful and fundamental constructs.
这篇关于反 - 如果运动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!