Search code examples
c#javaoopobject-model

When to subclass and when to use attributes in an object model


I'm looking for some guidance for an object model I'm working on for an evaluation tool. There are currently two types of evaluations

  • Peer
  • Team

The only difference between these two evaluations is the way that a form is presented to a user in the UI. The peer evaluation will show peers in your team that you should evaluate based on some criteria, and the team evaluation will show all the teams involved to be evaluated based on some criteria. Other than that these two evaluations are exactly the same.

When building an object model should I make an abstract Evaluation object and then subclass the Peer evaluation and the Team evaluation? Or should I create an Evaluation object and have two attributes to represent the two different types of evaluations?

In the future there could possibly be more types of evaluations added.


Solution

  • In general, if the type is just a piece of information, you make it a field. If it's used to change the behavior of the methods like

    public void foo() {
        if (type == PEER) {
            doSomething();
        }
        else {
            doSomethingElse();
        }
    }
    

    then it's an indication that you should subclass, and use polymorphism to get the appropriate behavior depending on the type. Another solution is to use delegation rather than inheritance, and to associate behavior to the type:

    public enum EvaluationType {
        PEER {
            @Override
            public void foo() {
                ...
            }
        },
        TEAM {
            @Override
            public void foo() {
                ...
            }
        };
    
        public abstract void foo();
    }
    
    public class Evaluation {
        private EvaluationType type;
    
        public void foo() {
            return this.type.foo();
        }
    }