I would like to track a Motor with a Grails application. At several occasions, the location of the motor changes, but the location type also changes. How do I efficiently store the current location?
A first attempt would be:
class Motor {
String motornumber
Locationtype lt
}
class Locationtype {
String type
}
class Machine {
String machinenumber
}
class Repaircompany {
String companyname
}
Depending on Locationtype lt
which is ONE of {"Machine","Repair"}
, a Motor object shall store the machine id or the repaircompany id at which the motor is located at. "Machine" means: The Motor is deployed on a machine, "Repair" means: the Motor is currently being repaired.
So I would like to have a field location
as a field inside Motor
, but of which type? I know, each time I access location
, I would have to evaluate lt
.
I was thinking about a field inside a trait. Would I be off-track with that or is that the way to go?
There are many possible solutions here, and none is necessarily better than another based on the limited information provided. Two possible solutions:
Simplest: Add a nullable Machine
field and a nullable Repaircompany
field to the Motor
object. Then either could be populated (or technically both) and you can work as needed from those values.
Likely better: Create a Location
base class (can be abstract) and extend Machine
and Repaircompany
from it. In Motor
, create a field of type Location
which could then be populated with either subclass.
For either solution, you probably don't need a Locationtype
any more. You can determine that via which field is populated (for solution 1) or via subclass (for solution 2).