2

I m using C# Switch case how i can replace using inheritance. case is like 1,2,3,4 so how i can implement it.

for eg:

    public Blocks(int code)
    {
         bool[,] shp1;

        switch (code)
        {
            case 1:
                this._Width = 4;
                this._Height = 1;
                this._Top = 0;
                this._Left = 4;

                shp1 = new bool[_Width, _Height];
                shp1[0, 0] = true;
                shp1[1, 0] = true;
                shp1[2, 0] = true;
                shp1[3, 0] = true;
                this.Shape = shp1;
                break;

            case 2:
                this._Width = 2;
                this._Height = 2;
                this._Top = 0;
                this._Left = 4;

                shp1 = new bool[_Width, _Height];
                shp1[0, 0] = true;
                shp1[0, 1] = true;
                shp1[1, 0] = true;
                shp1[1, 1] = true;
                this.Shape = shp1;
                break;


            default:
                throw new ArgumentException("Invalid Block Code");
        }
    }
Jitendra Jadav
  • 603
  • 3
  • 10
  • 20

3 Answers3

9

The basic idea is that instead of having a method that decides what to do based on state, you have different types of objects that have different implementations of the same method that do the right thing for that type of object.

Let's say that you now have a Car class and the values (1, 2, 3, ...) refer to various brake configurations. In your current Brake() method you have code that looks like:

public class Car
{
    public void Brake()
    {
          switch (this.BrakeType)
          {
              case 1:  // antilock brakes
                ....
              case 2:  // 4-wheel disc brakes, no antilock
                ....
              case 3:  // rear-drum, front-disc brakes
                ....

          }
     }
}

What you really would like to to do is have different classes that implement the Brake method. In this case, I'd have a BrakeStrategy for each of the brake types. Assign the car object the correct BrakeStrategy for it's configuration, then simply call the strategy method from the Brake method.

public class Car
{
     public BrakeStrategy BrakeStrategy { get; set; }

     public void Brake()
     {
         this.BrakeStrategy.Brake();
     }
}

public class ABSBrakes : BrakeStrategy
{
     public void Brake()
     {
        ... do antilock braking...
     }
}

var car = new Car { BrakeStrategy = new ABSBrakes(), ... };
car.Brake();  // does ABS braking
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • Thx for the example ! But could you please tell me where and how we move the decision making (i.e. how do we know we have to do BrakeStrategy = ABSBrakes(), and not = ReadDrunBrakes() ? ) Has the switched now moved here ? Does my question make any sense ? – Preets Sep 10 '09 at 12:27
  • 2
    You must indeed have some kind of decision structure to create the brake-strategy that you want to use. This can be moved to a factory pattern where you indeed use a switch statement, but, this statement will be far less complex then the original one. Next to that, it is far easier to introduce a new braking-strategy when needed. – Frederik Gheysels Sep 10 '09 at 12:30
  • 2
    @Preets - @Frederik is correct -- you do need some method to determine what type of thing to create. This could be done via configuration with a factory -- factory reads configuration, configuration specifies what type (by name) of strategy to create. Even if you end up using a decision tree - this can be put into a class dedicated to the creational aspects of the object, rather than spreading the operational logic throughout the class. That is, the switch statement is localized where the object is created and not used in every method to determine how to operate for this object. – tvanfosson Sep 10 '09 at 12:40
  • The fog has cleared ! Thanks tvanfosson ! SO owes it success to guys like you'll. – Preets Sep 10 '09 at 12:55
4

You can apply a Strategy pattern.
But, you must make sure that you're not trying to kill a fly with a gun, if you see what I mean. Make sure that you do not introduce more complexity then you're trying to remove. In some cases, replacing your switch statement with a strategy is a good solution, in other cases, it is not.

As I see your code now, I think I would opt for some kind of factory pattern ...

Frederik Gheysels
  • 56,135
  • 11
  • 101
  • 154
  • Frederik, do you understand the question ? – Preets Sep 10 '09 at 12:09
  • 1
    Yes I do. You can use polymorphism to execute different functionality based on a certain condition. For every condition that exists, you could create a class (which inherits from a same base-type) and encapsulate the logic in to the class, instead of putting it in one switch statement. See my link regarding the strategy pattern. – Frederik Gheysels Sep 10 '09 at 12:12
  • that is i understand but i don't want to switch case it's still use switch.. thanks ... – Jitendra Jadav Sep 11 '09 at 08:53
1

If you use inheritance, you can still change the implementation dynamically, but without using a switch statement.

Taking the above BrakeType example:

Dictionary<BrakeType, BrakeStrategy> strategyList = new Dictionary<BrakeType, BrakeStrategy>();

strategyList.Add(BrakeType.ABS, new ABSBrakes());
strategyList.Add(BrakeType.Disc, new DiscBrakes());
strategyList.Add(BrakeType.RearDrum, new RearDrumBrakes());

public class Car
{
    public BrakeType TypeOfBrake {get; set;}

    public void Brake()
    {
        strategyList[TypeOfBrake].Brake();
    }
}

So instead of a large switch statement cluttering the logic of the class, it's a simple dictionary lookup.

Dr Herbie
  • 3,930
  • 1
  • 25
  • 28