1

I have a set information that I am able to read in as raw data which corresponds to different physical quantities depending on which device provided that information. Every device contains the same amount of data and the same types, just different fields are interpreted differently. Here's how I have implemented it so far:

public abstract class SuperData {
    int voltage1;
    int voltage2;

    SuperData(int v1, int v2) {
        voltage1 = v1;
        voltage2 = v2;
    }

    public int getVoltage1 { return voltage1; }
    public int getVoltage2 { return voltage2; }
}

public class CarAData extends SuperData {
    CarAData(int v1, int v2) { super(v1, v2); }

    public int getKeyVoltage { return getVoltage1(); }
    public int getLightVoltage { return getVoltage2(); }
}

public class CarBData extends SuperData {
    CarAData(int v1, int v2) { super(v1, v2); }

    public int getStarterVoltage { return getVoltage1(); }
    public int getCigarretteVoltage { return getVoltage2(); }
}

This is just a trivial example; in reality it is about 60 fields that are just a byte array coming over Bluetooth. I am using a factory to create the correct object based on another data stream but the problem is it requires the use of instanceof down the road to know which method to call.

So what pattern is the best way to represent data which has different meanings?

1

You're describing a Variant Record or Discriminated Union. They're not directly supported in Java, but as you've already discovered you can simulate them with class hierarchies.

instanceof shouldn't be a problem. It's a bit of reflection voodoo, but you only have to do it once per record if you cast your object to the correct Type once you identify it. If the reflection bothers you, include a 'Tag' method in the base class that returns a descriptor of some sort.

It's too bad you're not working in C#; C-like Union structures are supported directly in that language.

  • Thank you for naming the pattern I was describing. It is also too bad that java's protected gives package access as opposed to C++'s behavior of subclasses only. Then I could hide the non-descriptive getVoltage1() method. – JayCle Oct 21 '15 at 2:19
  • Ah, I see what you did there. Respectfully, I don't think the subclassing is worth the effort just to get a rename of fields that are already there. Your variant records should describe variations in the actual mapping of the data. – Robert Harvey Oct 21 '15 at 2:20
  • Would you consider subclassing when v1 is a brake one one vehicle but v2 is a brake on another? Or should I just require the class user to figure it out? – JayCle Oct 23 '15 at 12:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.