views:

63

answers:

3

Which of these 3 approches would choose and why?

// This is the one I would choose

class Car {

}

class FeeCalculator {

    public double calculateFee(Car car) {
        return 0;
    } 
}

// in that case the problem might be when we use ORM framework and we try to invoke save with parameter Car

class Car {

    private FeeCalculator calculator;

    public double calculateFee() {
        return calculator.calculateFee(this); 
    }
}

class FeeCalculator {

    public double calculateFee(Car car) {
        return 0;
    }
}

// in that case the problem mentioned above is solved, but I don't like this design

class Car {

    public double calculateFee(FeeCalculator calculator) {
        return calculator.calculateFee(this); 
    }
}

class FeeCalculator {

    public double calculateFee(Car car) {
        return 0;
    }
}
A: 

I would use a variation on the second theme. I would inject a FeeCalculator into the car (either old-skool or via a DI framework - Spring/Guice/etc.) and then have the car be able to calculate its fees by delegating. However, I would make the FeeCalculator API not aware of Car (otherwise you have a circular dependency and you have to expose things from Car that you might not otherwise want to). Instead, I would have the API to FeeCalculator take the basic inputs of the calculation - number of days on hire, day rate, customer discount schedule, etc.

dty
+3  A: 

I vote for the first one. Such a calculator is not part of a car and a car usually has not the capability to calculate fees.

The Second design models something like car-has-a-calculator, the third option is close to car-is-a-calculator (even though it delegates the calculation to another class).


And in addition, the ORM framework should not influence the architecture of the model. The model should reflect the 'real world', there's enough experts around to implement the model in any ORM framework.

Andreas_D
A: 

What does a Car have to do with calculating a fee? Nothing, most likely. In that regard, I like option 1.

Shakedown