title: How to Consolidate Many Classes and Avoid instanceof?
body: <p>The program I'm helping to develop is supposed to output several dynamically generated questions for the user to answer. The questions are of different types and have a corresponding class <code>Constraint</code> that they fill with the user-given information. My question is how to create uniform behavior for the different constraints.</p>
  
  <pre><code>                    ----&gt;Constraint&lt;--------------------
                      |                  |               |
                    FConstraint        PConstraint    TConstraint
                    |         |
              UConstraint AConstraint
  </code></pre>
  
  <p>The base class <code>Constraint</code> is empty, as is TConstraint. </p>
  
  <p><code>UConstraint</code>, <code>PConstraint</code> and <code>AConstraint</code> share three variables. However, <code>UConstraint</code>and <code>AConstraint</code> have one additional variable that <code>PConstraint</code> doesn't have.</p>
  
  <p>I feel like I'm trying to hammer through a brick wall with some pincers. My one thought is to provide an abstract method to Constraint with the signature:</p>
  
  <pre><code>// All answers are of type string.
  abstract void setValue(string variable, string answer);
  </code></pre>
  
  <p>Which are implemented by every <code>Constraint</code> subclass. However, passing a string to determine which variable to set seems error-prone and a similarly bad code smell.</p>
  
  <p>The second option was to move the three similar variables up into Constraint, but that still leaves <code>UConstraint, AConstraint</code> with that extra bit of information I might need to set. It doesn't help that <code>TConstraint</code> doesn't need any of those.</p>
  
  <p>My current brute-force "Screw this design." solution is an <code>instanceof</code> soup in which I check and fill in the missing Constraint-specific information.</p>
  
  <pre><code>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.
  </code></pre>
  
  <p>Is there a better solution to this design than the abstract function? </p>