Reputation: 341
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();
}
}
Upvotes: 3
Views: 93
Reputation: 22232
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.
Upvotes: 2
Reputation: 10242
It's certainly doable, but I can't think of a single benefit of putting some kind of contants/ids in a resource file. Using enums allow you to group related constants and it helps you avoid accidentally mixing unrelated constants.
Upvotes: 0
Reputation: 1006604
Is it acceptable to use them purely as unique identifiers for any Java code in your Android application?
It certainly works, but...
Or would it be preferable to do things in pure Java?
I'd go with this approach. If nothing else, the enum
prevents you from getting your identifiers mixed up with other integers.
Upvotes: 1