views:

520

answers:

9
+21  Q: 

OOP design problem

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"?

A: 

use the is operator to check against the accepted classes, and you can throw an exception in the constructor

Pentium10
A: 

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
    }
}
Oli
+7  A: 

Object-oriented programming alone cannot handle this problem well. What you need is generic programming (C++ solution shown here):

template <class FuelType>
class Car
{
public:
  void FillTank(FuelType fuel);
};

Your diesel car is then just a specific car, Car<Diesel>.

Peter Alexander
+23  A: 

Use a generic base class (if your language supports it (the below is C#)):

public abstract class Car<TFuel>  where TFuel : Fuel
{
    public abstract void FillTank(TFuel fuel);
}

Basically this enforces any class that inherits from car to specify which type of fuel it uses. Furthermore, the car class imposes a restriction that TFuel must be some subtype of the abstract Fuel class.

Lets say we have some class Diesel which is simple:

public class Diesel : Fuel
{
    ...
}

And a car which only runs on diesel:

public DieselCar : Car<Diesel>
{
     public override void FillTank(Diesel fuel)
     {
          //perform diesel fuel logic here.
     }
}
klausbyskov
Why inheritance instead of composition?
Paco
+1 What I'd done as well :)-- for the "why inheritance": Because Diesel "is-a" Fuel, and DieselCar "is-a" car. Inheritance ain't evil, I don't know why people tend to think this. Look at java and .Net; both uses inheritance all over the place. I guess you could avoid making a DieselCar a car, and instead implement IFuelable<T>, but that really depends on the properties of a Car in this example.
cwap
@cwap - inheritance isn't evil, it just carries certain risks. But this probably isn't the kind of question that can be settled in a comment. :) There are numerous SO questions about this if you want to know why people recommend composition over inheritance, like http://stackoverflow.com/questions/361371/should-inheritance-of-non-interface-types-be-removed-from-programming-languages, and a lot of good articles on the .net. For example, http://blogs.msdn.com/steverowe/archive/2008/04/28/prefer-composition-over-inheritance.aspx, http://www.artima.com/lejava/articles/designprinciples4.html.
Jeff Sternal
@Jeff Sternal I agree that this discussion probably does not belong in the comments, but I feel that I must point out that abstract classes have a clear benefit over interfaces in that the abstract base class can be extended with new functionality (overrideable methods) without breaking existing child classses. This is not the case for interfaces.
klausbyskov
@klausbyskov - absolutely, and I didn't intend to discourage you from answering Paco! (After all, his comment pertains to your proposal - which I think is the best answer if generics are an option.)
Jeff Sternal
This is a good solution to many problems, but it's important to note that this also means that there is no longer a `Car` base class that can be used polymorphically.
munificent
+1  A: 

a double dispatch can be used for this: accept some fuel before before filling. Mind you that in language that don't support it directly, you introduce dependencies

stefaanv
+1  A: 

It sounds like you just want to restrict the type of fuel that goes into your diesel car. Something like:

public class Fuel
{
    public Fuel()
    {
    }
}

public class Diesel: Fuel
{
}

public class Car<T> where T: Fuel
{
    public Car()
    {
    }

    public void FillTank(T fuel)
    {
    }
}

public class DieselCar: Car<Diesel>
{
}

Would do the trick e.g.

var car = new DieselCar();
car.FillTank(/* would expect Diesel fuel only */);

Essentially what you are doing here is allowing a Car to have specific fuel types. It also allows you to create a car that would support any type of Fuel (the chance would be a fine thing!). However, in your case, the DieselCar, you would just derive a class from car and restrict it to using Diesel fuel only.

James
+11  A: 

If there is a hard boundary between types of cars and types of fuel, then FillTank() has no business being in the base Car class, since knowing that you have a car doesn't tell you what kind of fuel. So, for this to ensure correctness at compile time, FillTank() should be defined in the subclasses, and should only take the Fuel subclass that works.

But what if you have common code that you don't want to repeat between the subclasses? Then you write a protected FillingTank() method for the base class that the subclass's function calls. Same thing goes for Fuel.

But what if you have some magic car that runs on multiple fuels, say diesel or gas? Then that car becomes a subclass of both DieselCar and GasCar and you need to make sure that Car is declared as a virtual superclass so you don't have two Car instances in a DualFuelCar object. Filling the tank should Just Work with little or no modification: by default, you'll get both DualFuelCar.FillTank(GasFuel) and DualFuelCar.FillTank(DieselFuel), giving you an overloaded-by-type function.

But what if you don't want the subclass to have a FillTank() function? Then you need to switch to run time checking and do what you thought you had to: make the subclass check Fuel.type and either throw an exception or return an error code (prefer the latter) if there is a mismatch. In C++, RTTI and dynamic_cast<> are what I would recommend. In Python, isinstance().

Mike D.
A: 

In a CLOS-like system, you could do something like this:

(defclass vehicle () ())
(defclass fuel () ())
(defgeneric fill-tank (vehicle fuel))
(defmethod fill-tank ((v vehicle) (f fuel)) (format nil "Dude, you can't put that kind of fuel in this car"))

(defclass diesel-truck (vehicle) ())
(defclass normal-truck (vehicle) ())
(defclass diesel (fuel) ())
(defmethod fill-tank ((v diesel-truck) (f diesel)) (format nil "Glug glug"))

giving you this behaviour:

CL> (fill-tank (make-instance 'normal-truck) (make-instance 'diesel))
"Dude, you can't put that kind of fuel in this car"
CL> (fill-tank (make-instance 'diesel-truck) (make-instance 'diesel))
"Glug glug"

Which, really, is Common Lisp's version of double dispatch, as mentioned by stefaanv.

Frank Shearar
A: 

you can extend your original Car interface

interface Car {
    drive();
}

interface DieselCar extends Car {
    fillTank(Diesel fuel);
}

interface SolarCar extends Car {
    chargeBattery(Sun fuel);
}

}

Mauricio
The problem then is that if I have a list of Car I cant fill the tank on all of the cars without knowing which car it is. And I think the problem I have boils down to exactly that question. In this case you should not expose a fill tank method on the base class because it would not make sense.
Marcus