I have an object that keeps weather measurements for a single factory.
public class FactoryWeather {
// each measurement consists of min, max and average observations.
private Measurement temperature;
private Measurement humidity;
private Measurement ...
public constructor,setters/getters...
}
Measurement types are defined as enum like below :
public enum WeatherMeasurementEnum {
// min and max range of single measurement
TEMPERATURE(-50,50),
HUMIDITY(0,100),
...
// validity check for measurements
public boolean isValid(int average) {
return average >= minimum && average <= maximum;
}
}
Finally, I update each measurement using following method :
public void updateWeatherMeasurement(String type, Measurement measurement, FactoryWeather factory) {
WeatherMeasurementEnum m = WeatherMeasurementEnum(type.toUpperCase());
if(!m.isValid(measurement.getAverage())
throw new AppException("Invalid measurement!");
switch(m) {
case TEMPERATURE: factory.setTemperature(measurement);break;
case HUMIDITY: factory.setHumidity(measurement);break;
...
}
}
Although the switch statement might look fine, type of measurements can grow in future. Taking this into consideration and the sake of best practice, is it possible to eliminate this kind of long switch or if/else statements ?
Aucun commentaire:
Enregistrer un commentaire