I have a Java problem here. I have many constants, which are consecutive constant integers, currently defined like:
interface Flags {
static final short A = 0;
static final short B = A + 1;
static final short FIRST_USER_FLAG = B + 1;
}
Many of you would now recommend me to use Enum. The problem is, I need more than one place with those flags. So it would be like:
interface CustomFlags {
static final short USER_A = Flags.FIRST_USER_FLAG + 1;
static final short USER_B = USER_A + 1;
}
The code you see here, also has to be the same on two sides of network, included in server code and client code. Every message between those has defined it’s flag and by this flag, the networking creates message object, registered with this flag. This doesn’t seem to be the best approach, but I couldn’t think of anything better. And the problem is, that the networking code has its own flags and messages, which does some basic authentication and handshaking. And then there has to be messages (and their flags) defined by the code that uses the networking.
My question is, how to make this more maintainable and readable? Also, if there’s anyone, who knows about better approach to send and recreate messages (I’m using both TCP and UDP, depends on the message), I would be really thankful to hear it.
If there’s something I didn’t explain, please let me know and I’ll add it.
PS: Sorry for my bad english, as I’m not native speaker.
I would leave it the way it is. That’s quite a usual technique for defining constants of a protocol. If the peer isn’t Java I would probably ‘de-engineer’ a bit further, and just define the names and their values directly without worrying about the arithmetic. You don’t want this to be easy to change, you actually want it to be impossible to change, so that inadvertent protocol incompatibilities don’t creep in. Enums are for cases where you are more interested in the names and in type safety and not too concerned about the actual values, ordinals, etc.