mercredi 19 septembre 2018

C# replacing huge if-else statement

let's say i have Item object witch mostly holds enum properties like this

public enum Shape
{
    square = 1,
    trangle = 2,
    any = 3
}

public enum Color
{
    blue = 1,
    red = 2,
    yellow = 3,
    green = 4
}


public enum Material
{
    glass = 1,
    wood = 2,
    metal = 3
}


public class Item
{
    public Shape ItemShape { get; set; }
    public Color ItemColor { get; set; }
    public Material ItemMaterial { get; set; }
}

What am trying to do is depends of combination of whole three properties i need to do some action later;

I was thinking to use if-else combination like:

if(item.ItemShape == Shape.square && item.ItemColor == Color.blue && item.ItemMaterial == Material.glass)
        {
            //call Action1
        }
        else if(item.ItemShape == Shape.square && item.ItemColor == Color.blue && item.ItemMaterial == Material.wood)
        {
            // action2
        }
        ......

Problem is that i have around 16 of combinations, so it will be huge if-else method to resolve what method should i call later.

enter image description here

Maybe is there any other way to replace if-else statements more readable code, design patter or something more efficient?

I was thinking to combine whole possible states as flag enum values, but not sure if i can create enum value from object property later.

Aucun commentaire:

Enregistrer un commentaire