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:
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:
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...
}
}
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();
}
}
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.