Best way to manage a device information class

Posted on

Problem

This is probably a really simple question.

An embedded device I’m working with will store the device information in an xml file.

In my code, I want to read this xml file and freely reference to it wherever I need to, so I made a simple helper class:

public class DeviceInformation {
    public static final String XML_DIRECTORY_ON_DEVICE = "/xml/";
    public static final String ROOT_DEVICE_XML_FILE = "rootdevice.xml";

    public static String DEVICE_ID;
    public static String DEVICE_TYPE;
    public static String HOME_ID;

    public DeviceInformation() {
        File xmlFile = new File(XML_DIRECTORY_ON_DEVICE + ROOT_DEVICE_XML_FILE);
        if (!xmlFile.exists())
            return;
        RootDeviceXMLReader rootDeviceXMLReader = new RootDeviceXMLReader(xmlFile);
        DeviceInfoStruct deviceInfoStruct = rootDeviceXMLReader.getDeviceInfoStruct();
        DEVICE_ID = deviceInfoStruct.getDeviceID();
        DEVICE_TYPE = deviceInfoStruct.getDeviceType();
        HOME_ID = deviceInfoStruct.getHomeID();
    }
}

And then I’d just get my device id by DeviceInformation.DEVICE_ID. Same goes for type and home_id.

But this approach just doesn’t seem elegant. Turn the initializer into a static one? Still, I feel like there’s something wrong with this whole approach and I just cannot articulate it. How can I improve this class?

Solution

I think you should have :

  1. A constructor taking device_id, device_type and home as an argument.

  2. a static method doing the file handling and calling the constructor previously defined.

This would make your code more modular, easier to test and would put different independent things (device creation and file handling) in different places.

I’d also like to point out that at the moment, your constructor does create a non-properly-initialised device when the file does not exist. It would probably be much better not to create it at all (and return null ?) if we don’t have the required information to do so.

Also, and this is not relevant to your question but there’s not real need for 2 variables XML_DIRECTORY_ON_DEVICE and ROOT_DEVICE_XML_FILE if you are always going to call them together. It might be just as easy to have “XML_PATH”.

I’m not 100% sure what you mean but if you want to refer to it everywhere then maybe make the class a singleton? You could just call it everywhere this way.

DeviceInformation.getInstance().someMethod(); 

This means that there is only one DeviceInformation in the project instead of many.

Leave a Reply

Your email address will not be published. Required fields are marked *