Alex Rivera | Logout

anti-if campaign

Asked 2009-07-22T19:23:09.220
35

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 someth
Edit
Report

2 Answers

37

In Java it's easy to use enums as polymorphic anti-if agents.

public class AntiIf {
    public enum WidgetTypes {
    Type1 {
        public void doSomething() {
        //...
        }},
    Type2 {
        public void doSomething() {
        //...
        }},
    Type3 {
        public void doSomething() {
        //...
        }},
    Type4 {
        public void doSomething() {
        //...
        }};

    public abstract void doSomething();
    }

    WidgetTypes _myType; // set by someone to one of the types.

    public void someFunction() {
    //...
    _myType.doSomething();
    //...
    }
}
answered 2010-03-17T11:37:04.670
6

...What?

I can't imagine how to do something like that without some kind of comparison. At all.

An anti-goto campaign I can imagine, but if seems like a pretty damn required control flow structure to me.

answered 2009-07-22T19:26:26.733

Your Answer