0

Often when writing code I wonder what the best way is to discriminate between types (by which I don't necessarily mean types used in typesystems). That brings up 3 questions:

  • What is better?
  • When is it better?
  • What are the (dis)advantages?

Using properties to discriminate

class BinaryExpression {

    String operator; // e.g. "+"
    Number lhs, rhs;
}

Subclassing to discrimination

class BinaryExpression {
    Number lhs, rhs;
}

class Addition extends BinaryExpression {}

// Etc.

Note: I'm not sure if I have the terms right. Please correct me if I'm wrong.

1
  • Sharing your research helps everyone. Tell us what you've tried and why it didn’t meet your needs. This demonstrates that you’ve taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer. Also see How to Ask
    – gnat
    Oct 3, 2015 at 18:19

1 Answer 1

3

If there's a functional or operational difference between the types, then creating explicit types allows cleaner object-oriented implementations of the different functional behaviors.

If the difference is just an appearance thing, then full object-orientation might be overkill (though there will be many purists who object to this pragmatic approach).

For your example of operators. If you were actually using the operator class to perform calculations, then subclassing is probably the way to go (because of the differing implementations of a "compute" method for example).

If you are simply holding the content for output serialization, then a property containing the operator character might be all you need for your purposes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.