I have a program that deals with measurements. The measurement might be Temperature, Speed, Weight, Pressure
So I have a class which represents a Temperature
measurement, another class which represents a Speed
measurement, another class for Weight
, and another class for Pressure
Then I have all this nearly identical code, except one version deals with Temperature
readings, another version deals with Speed
readings, another version deals with Weight
readings, another version deals with Pressure
So I think maybe I can eliminate a lot of this duplicate code by using Generics.
But I eventually come across a problem: somewhere along the line I'll need to make an instance of a measurement class reading, an instance of type T:
T newReading = new T(value);
and that can't be done with Generics.
(Actually it can be done if I didn't need to pass in a parameter, such as the value of the reading, but creating an immutable measurement reading only works if I can set the value in the constructor (as far as I know).
So I'm wondering if there's any way around this problem. (Turn the problem upside down on it's head? View it from a different angle?) Or, can it be proved there's no workaround?
Currently I went the route of a code generator. I create a single version of all the code using the word "measurement", then the code generator replaces all instances of "measurement" with "temperature", and repeats replacing "measurement" with "speed", "weight", "pressure", etc. until I have all the needed nearly identical code versions. With more effort I might be able to expand this to be a Domain Specific Language (DSL), or perhaps it already qualifies as one.
I still wonder if there's an easier way.