Robe Elckers
Robe Elckers

Reputation: 977

Java extendable constants

I have a software setup with 2 layers, a core layer and a customer specific layer. The core layer has defined constants which the customer specific layer should be able to extend. More specific:

public class CoreConstants
{ 
  public static long CORE_CONSTANT_1 = 1;
  public static long CORE_CONSTANT_2 = 2;
}

The customer specific layer should be able to add constants which are only used in the customer specific layer. Idea:

public class CustomerConstants extends CoreConstants
{
  public static long CUSTOMER_CONSTANT_1 = 1000; // starting range = 1000
}

Is there a more common way to handle this?

More info: The reason for inheritance is to define the starting range of the customer specific constants. In the CoreConstants class I could set the starting value for customer specific constants. Customer specific constants could then be defined like:

public static long CUSTOMER_CONSTANT_1 = customStartValue + 1;
public static long CUSTOMER_CONSTANT_2 = customStartValue + 2;

Upvotes: 0

Views: 1030

Answers (2)

ptomli
ptomli

Reputation: 11818

Integer constants are generally better replaced with enums, and you can achieve what you want using interfaces on enums.

interface CoreConstant {
    int intValue();
}

enum CoreConstants implements CoreConstant {
    CORE_CONSTANT_1(1),
    CORE_CONSTANT_2(2);
    private final int intValue;
    public CoreConstants(int intValue) { this.intValue = intValue; }
    public int intValue() { return intValue; }
}

interface CustomerConstant extends CoreConstant {}

enum CustomerConstants implements CustomerConstant {
    CUSTOMER_CONSTANT_1(1000);
    private final int intValue;
    public CustomerConstants(int intValue) { this.intValue = intValue; }
    public int intValue() { return intValue; }    
}

You could perhaps improve the design by using delegation within the enums, using an IntConstant class. Unfortunately for your case, you cannot extend an enum. The result is a bit of code duplication in the enum classes.

Otherwise, if you want to stay with the public static int model, then use an interface instead of a class, and finalize the constants.

interface CoreConstants {
    public static final int CORE_CONSTANT_1 = 1;
}

Upvotes: 3

JB Nizet
JB Nizet

Reputation: 691765

There is no reason to have an inheritance mechanism between those two classes. Inheritance is used for polymorphism, and you only have static members here. Just have two separate classes. I would even make them final and non instantiatable:

public final class CoreConstants { 
    /**
     * Private constructor to prevent unnecessary instantiations
     */
    private CoreConstants() {
    }
}

Upvotes: 1

Related Questions