Search code examples
androidresourcesunique-key

Should android resource id's be used for non-layout code?


The android resource ID is often used as a way to get/modify an XML-defined layout component. Is it acceptable to use them purely as unique identifiers for any Java code in your Android application? For example:

Using Android Resource IDs

ids.xml

<item name="sensor_pressure" type="id"/>
<item name="sensor_humidity" type="id"/>
<item name="sensor_precision_gas" type="id"/>

Sensor.java

public Sensor(int sensorId) {
    initializeSensor(sensorId);
}

private void determineSensorType(int sensorId) {
    switch(sensorId) {
    case R.id.sensor_pressure:
        intializePressureSensor();
        break;
    case R.id.sensor_humidity:
        initializeHumiditySensor();
        break;
    // etc...
    }
}

Or would it be preferable to do things in pure Java? For example:

Using Only Java

Sensor.java

public Sensor(int sensorId) {
    initializeSensor(sensorId);
}

enum SensorType {
    PRESSURE, HUMIDITY, PRECISION_GAS
}

private void determineSensorType(SensorType sensorType) {
    switch(sensorType) {
    case SensorType.PRESSURE:
        intializePressureSensor();
        break;
    // etc...
    }
}

Best Solution For My Example:

From MaciejGórski below. Using an interface, one can solve the problem posed by ridding of the need of unique IDs completely.

public interface Sensor {

}

public class HumiditySensor implements Sensor {

    public HumiditySensor() {
        init();
    }
}

Solution

  • How about an object oriented way?

    public interface Sensor {
    
    }
    
    public class HumiditySensor implements Sensor {
    
        public HumiditySensor() {
            init();
        }
    }
    

    You can avoid having ugly switch statements in many places in your code.