Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OOP design problem

Tags:

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

like image 276
Marcus Avatar asked Feb 18 '10 13:02

Marcus


People also ask

What is object oriented design question?

The object-oriented design (OOD) question is centered around writing out a program to model a real-world system. For example, one OOD question I've been asked was to design a restaurant. The solution would involve specifying the important classes and methods for managing a restaurant.

How do you prepare object oriented design questions?

Preparation Before the InterviewsYou should have a good command of one object-oriented programming language such as Java/C++/Python etc. Have some experience in it and learn how the OOPs concepts work in these languages. 2. Understand the various object-oriented design principles such as SOLID/DRY principles etc.

What is object oriented design example?

OOD involves defining the specific objects and classes that will make up that program. The first OO language, Simula, was developed in the 1960s, followed by Smalltalk in 1972. Examples of well-known OO programming languages include Ruby, C++, Java, PHP, and Smalltalk.


1 Answers

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.      } } 
like image 150
Klaus Byskov Pedersen Avatar answered Dec 17 '22 07:12

Klaus Byskov Pedersen