The program that I am helping to develop should output several dynamically generated questions for the user's response. Questions are of different types and have the corresponding Constraint
class, which is populated with user data. My question is how to create consistent behavior for different constraints.
---->Constraint<-------------------- | | | FConstraint PConstraint TConstraint | | UConstraint AConstraint
The base class of Constraint
empty, as is TConstraint.
UConstraint
, PConstraint
and AConstraint
share three variables. However, UConstraint
and AConstraint
have one additional variable that PConstraint
does not have.
It seems to me that I'm trying to hammer a brick wall with some ticks. My thought is to provide an abstract Constraint method with a signature:
which are implemented by each subclass of Constraint
. However, passing a string to determine which variable to set seems error-prone, and the same bad code smell.
The second option was to move three similar variables to Constraint, but that still leaves UConstraint, AConstraint
with this extra bit of information that I might need to set. This does not help TConstraint
not need any of them.
My current brute force is βTurn this project on.β the solution is instanceof
soup, in which I check and fill in the missing information related to restrictions.
Object constraint = item.getConstraint(); if (constraint instanceof AConstraint) { AConstraint constraint = (AConstraint) constraint; if (constraint.getValue() == null) { constraint.setValue(string); } else if (constraint.getKey() == null) { constraint.setKey(string); } // More of the same. } else if (constraint instanceof PConstraint) { // As the above if() group. } // etc.
Is there a better solution for this design than an abstract function?
source share