Home > Net >  Removing duplicate code from overriden enums
Removing duplicate code from overriden enums

Time:10-08

I have an enum with the following format. Enum A and B initially implemented someMethod differently but are now the same. Ideally we'd consolidate all the enum B's to become A's but for business reasons that's not possible. I'm trying to figure out a way to make enum A and B the same without duplication and I've been stuck.

public enum DP{
   A{
      @Override
      public someMethod(){
         Duplicate Code
      }
   }

   B{
      @Override
      public someMethod(){
         Duplicate Code
      }
   }


   C{
      @Override
      public someMethod(){
         Different Code
      }
   }

public abstract someMethod();

}

CodePudding user response:

If I understood your question correctly, instead of an abstract method, you can add duplicate code in the method and override the method only in C:

public enum DP {
    A,
    B,
    C {
        @Override
        public void someMethod() {
            // Different code
            System.out.println("C");
        }
    };
    
    public void someMethod() {
        //Duplicate code
        System.out.println("AB");
    }
}

Then:

DP.A.someMethod();
DP.B.someMethod();
DP.C.someMethod();

Output:

AB
AB
C

CodePudding user response:

Well, if you are using Java 8 or above, you can solve this with default interface methods.

Define an interface with your someMethod, and add a default implementation:

interface SomeInterface {
    default void someMethod() {
        System.out.println("Some default method");
    }
}

Then let the enum implement the interface:

public enum DP implements SomeInterface { ... }

Voila. You can just use it like you'd expect:

DP.A.someMethod();
DP.B.someMethod();
DP.C.someMethod();

Online demo

  • Related