Search code examples
javapolymorphismstatecode-duplicationinformation-hiding

How to avoid code duplication maintaining information hiding trough polymorphism


I wrote the following two classes (implementing a state pattern):

Price:

public abstract class Price {


    public abstract double getAmount(int rentalDays);

    public abstract  int getPriceCode();

}

RegularPrice:

public class RegularPrice extends Price {

    private static final int _priceCode = 0;


    @Override
    public double getAmount(int rentalDays) {
        double res = 2;
        if (rentalDays > 2)
            res += (rentalDays - 2) * 1.5;
        return res;
    }

    @Override
    public int getPriceCode() {
        return _priceCode;
    }
}

The problem is that adding other subclasses of Price with differents _priceCode translates into code duplication for the getPriceCode() method. I thought about pulling up the method to the superclass but then I couldn't declare _priceCode private.

What's the standard solution?


Solution

  • I can't see any reasons why getPriceCode() has to stay in the derived class since it is a common behaviour to all subclasses, so put it the base class. So _priceCode is in Price and not assigned and it should be declared as protected or package (depends if you want to let free access to it only from subclasses in the same package or even if from subclasses that belong to another package).

    Price

    public abstract class Price {
        protected static final int _priceCode;    // do you really need static?
    
        Price(int p){ this._priceCode=p;}
        public abstract double getAmount(int rentalDays);
        public int getPriceCode(){ return _priceCode; }
    
    }
    

    RegularPrice

    public class RegularPrice extends Price {
    
         RegularPrice(int p){ 
             //many ways to do this, but use costructors to set members
             super(p); 
          } 
    
        public double getAmount(int rentalDays) {
            double res = 2;
            if (rentalDays > 2)
                res += (rentalDays - 2) * 1.5;
            return res;
        }
    
    }
    

    In this way, _priceCode is directly visible only from subclasses of Price, from other parts of code it can be accessed only using the getter method and getPriceCode() is not duplicated.