0

I am sorry if this question was asked before, but I need a good suggestion to solve next design problem:

Task: given that we have a base service that operates with data of given set of types, we need to design support of extensions for that service that has extended type set.

Bad Solution:

class BaseServiceType {
    public static final int TYPE_A = 0;
    public static final int TYPE_B = 1;
    public static final int LAST_USED_BASE_TYPE_INDEX = TYPE_B;
}

And its extension

class ExtendedServiceType extends BaseServiceType {
   public static final int TYPE_E = LAST_USED_BASE_TYPE_INDEX + 1;
   public static final int TYPE_F = LAST_USED_BASE_TYPE_INDEX + 2;
}

My task is fairly simple that has only one extension. I am not trying to solve more general problem with multiple independent extensions.

I have a feeling that enum would work here, but no idea if it feasible.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
acm0x
  • 775
  • 6
  • 14
  • the question is not fully clear :( – stinepike Dec 31 '13 at 10:59
  • Check [this discussion](http://stackoverflow.com/questions/1414755/java-extend-enum) about extending enums. I think it will be helpful for your situation. –  Dec 31 '13 at 11:05
  • Enums are immutable, you can not add new types during runtime. I don't know if I got your question right, but this might be a problem. If there are no new services added during runtime, you could use Enums – Mirco Dec 31 '13 at 11:07
  • see http://stackoverflow.com/questions/1414755/java-extend-enum – Luigi R. Viggiano Dec 31 '13 at 11:08
  • Thank you for a suggestion, but I doubt that introducing new type would not require additional wrapping to use those types – acm0x Dec 31 '13 at 11:28

1 Answers1

2

One solution is to build the ids dynamically. Class initilization is thread safe so you can do this.

class BaseServiceType {
    protected static int id = 0;
    public static final int TYPE_A = id++;
    public static final int TYPE_B = id++;
}

And its extension

class ExtendedServiceType extends BaseServiceType {
   public static final int TYPE_E = id++;
   public static final int TYPE_F = id++;
}


class AlsoExtendedServiceType extends BaseServiceType {
   public static final int TYPE_X = id++;
   public static final int TYPE_Y = id++;
}

The only problem is the order classes are initialized change the ids. If this matters, you need to access the classes in the order you need.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130