I have a base class, let’s call it DispenseResult that stores the result of a machine operation. I am designing for a family of machines. DispenseResult will contain member variables that are applicable to all machines, such as current drawn during an operation.
I was thinking of having a derived class to model certain specialized machines, e.g. MotorizedDispenseResult which would have member variables pertaining to motor function etc.
A part of the client code is to get these various member variables from DispenseResult (or a derived class) and log them. If I do it the way described above then I’ll end up with code like:
void log(DispenseResult result) {
// store results common to all machines
log("current = " + result.getCurrent());
// store results for specialized cases
if (result instance of MotorizedDispenseResult) {
log("error = " + ((MotorizedDispenseResult)result).getMotorError());
... etc.
}
}
This is going to get messy as new derived types are created with all the instanceof checking. Is there a cleaner way to do it?
TY,
Fred
Option 1
That way all the subclass specific deviations live in the subclasses instead of somewhere else.
Option 2
If the functionality needs to live outside the class hierarchy, What I would do is
Map<SpecificClass, Handler>This why you don’t have to write extensive if statements, you can let the map do it for you. This is also easier to test, you can test your Handler impls in isolation.