There’s a piece of code I’m currently looking like which serialises/deserialises data.
The class structure looks something like this:
public class Field
{
public abstract void writeField(DataOutputStream out);
public abstract int getFieldID();
...
protected static final int INT_FIELD = 1;
protected static final int BOOL_FIELD = 2;
...
public void write(DataOutputStream out)
{
out.writeInt(getFieldID());
writeField(out);
}
...
}
public class IntField extends Field
{
public int v;
public void writeField(DataOutputStream out)
{
out.writeInt(v);
}
public int getFieldID()
{
return Field.INT_FIELD;
}
}
I feel like the way getFieldID is implemented is not the best.
Writing an abstract method to return a unique identifier for that class feels like a bad smell.
Is there better ways to go about implementing this?
Listing subclass-specific constants in a base class is not that great an idea, because ideally a superclass should not know about its subclasses. Just listing the constants in the base is not as bad as using them to differentiate among subclasses in the code of the base class.
Ideally, you should move the constants into their respective subclasses. If you cannot do it without breaking a compile, you’ve indeed stumbled upon a prime candidate for refactoring.