dimanche 5 décembre 2021

How to avoid changing many parts of code when adding new enum value, thus providing easier extensibility?

I am trying to make my code easier to extend in terms that a little change will not affect much other code.

I have an enum MyEnum, which values might increase in future.

Then, there are classes that holds instance of it and has many behaviors affected by that enum's concrete value. In other words, there are many places where I switch over it's value.

public enum MyEnum
{
    FIRST, SECOND, THIRD, FOURTH;
}


public class A
{
    private MyEnum myEnum
    
    public A(MyEnum myEnum)
    {
        this.myEnum = myEnum;
    }
    
    // as you will see, there is a lot of switching over its value
    public void boo()
    {
        switch(myEnum)
        {
            case FIRST: // do smtng
            case SECOND: // do smthing else
            case THIRD: // do smthing else
            case FOURTH: // do nice thing
        }
    }

    public int goo()
    {
        switch(myEnum)
        {
            ...
        }
    }
   

    public AnotherObject foo()
    {
        switch(myEnum)
        {
            ...
        }
    }
}

public class B
{
    private MyEnum myEnum
    
    public B(MyEnum myEnum)
    {
        this.myEnum = myEnum;
    }
    
    public double doo()
    {
        switch(myEnum)
        {
            ...
        }
    }

    public void soo()
    {
        switch(myEnum)
        {
            ...
        }
    }
   
    public boolean xoo()
    {
        switch(myEnum)
        {
            ...
        }
    }
}

The thing here is that mostly I will need to add new case to all places where we switch over it's value => will need to do many changes to code when I add new enum value.

Did anyone else faced this problem? By now, I guess it is just downside of using enums this way.

Aucun commentaire:

Enregistrer un commentaire