What is the best way to handle the coexistence of the "int enum" template with java enums as the API evolves?

Suppose you support an API that was originally released several years ago (before java got support enum), and it defines a class with enumerated values ​​as ints:

public class VitaminType {
 public static final int RETINOL = 0;
 public static final int THIAMIN = 1;
 public static final int RIBOFLAVIN = 2;
}

Over the years, the API has developed and acquired features specific to Java 5 (advanced interfaces, etc.). Now you are going to add a new enumeration:

public enum NutrientType {
 AMINO_ACID, SATURATED_FAT, UNSATURATED_FAT, CARBOHYDRATE;
}

There is no type security in the old-style int-enum template, there is no way to add behavior or data, etc., but it is published and used. I am worried that mixing the two enumeration styles is inconsistent for API users.

I see three possible approaches:

  • (NutrientType ) int, VitaminType. , .

  • API: VitaminType NutrientType enum. , VitaminType, - int, , NutrientType, .

  • VitaminType VitaminType2 . NutrientType .
    , 2-3 , , , VitaminType int foo(VitaminType2 v) . foo(int v), foo(VitaminType2 v), .

?

+5
5

, , , . -, " " , , JDK. , ints, , , , , , , , - , (

class A
   {
       public static final int MY_CONSTANT=1
   }

   class B
   {
           ....
           i+=A.MY_CONSTANT; 
   }

i+=1

, A, , , , B , B .

, , , , , .

+3

, API VitaminType NutrientType? , , , API, , /, . , NutrientType , , .

; , int enum:

public enum Vitamin {

    RETINOL(0), THIAMIN(1), RIBOFLAVIN(2);

    private final int intValue;

    Vitamin(int n) {
        intValue = n;
    }

    public int getVitaminType() {
        return intValue;
    }

    public static Vitamin asVitamin(int intValue) {
        for (Vitamin vitamin : Vitamin.values()) {
            if (intValue == vitamin.getVitaminType()) {
                return vitamin;
            }
        }
        throw new IllegalArgumentException();
    }

}

/** Use foo.Vitamin instead */
@Deprecated
public class VitaminType {

    public static final int RETINOL = Vitamin.RETINOL.getVitaminType();
    public static final int THIAMIN = Vitamin.THIAMIN.getVitaminType();
    public static final int RIBOFLAVIN = Vitamin.RIBOFLAVIN.getVitaminType();

}

API , , .

, , , , .

+6

, "make" , Make , , , 10 .

, , - . SO , , .

, ​​ , .

+1

, script (sed, perl, Java, Groovy,...) .

, :

  • . , , .
  • . , .

ints.

+1

, , . , , . , . , , . , , int, - .

, , . , , , - , ... , .

, - . , , , , . , , , .

0

All Articles