Alex Rivera | Logout

OOP design problem

Asked 2010-02-18T13:56:08.123
24

What is good design in this simple case:

Let's say I have a base class Car with a method FillTank(Fuel fuel) where fuel is also a base class which have several leaf classes, diesel, ethanol etc.

On my leaf car class DieselCar.FillTank(Fuel fuel) only a certain type of fuel is allowed (no surprises there:)). Now here is my concern, according to my interface every car can be tanked with any fuel, but that seems wrong to me, in every FillTank() implementation check the input fuel for the correct type and if not throw error or something.

How can I redesign such case to a more accurate one, is it even possible? How to design a base method which takes a base-class for input without getting these "strange results"?

Edit
Report

1 Answer

0

I think the accepted method would be to have a ValidFuel(Fuel f) method in your base class that throws some sort of NotImplementedException (different languages have different terms) if the "leaf" cars don't override it.

FillTank could be then be entirely in the base class and call ValidFuel to see if it's valid.

public class BaseCar {
    public bool ValidFuel(Fuel f) {
        throw new Exception("IMPLEMENT THIS FUNCTION!!!");
    }

    public void FillTank(Fuel fuel) {
        if (!this.ValidFuel(fuel))
             throw new Exception("Fuel type is not valid for this car.");
        // do what you'd do to fill the car
    }
}

public class DieselCar:BaseCar {
    public bool ValidFuel(Fuel f) {
        return f is DeiselFuel
    }
}
answered 2010-02-18T14:01:45.947

Your Answer