I've been trying to figure out the Liskov Substitution Principle and Interface Segregation Principle and I'm a little confused with the following example.
Assume that we have a base class called Vehicle
with a couple of properties and a interface IVehicle
which is implemented in the IVehicle
class.
We have two child classes, Car
& Motorcycle
. Car
inherits from Vehicle and implements the IVehicle
interface. Motorcycle
inherits from Vehicle and implements the IVehicle
as well, but Motorcycle
has an extra property, which is also added in a new Interface IMotorcycle
that is implemented in the Motorcycle
class.
Let me clarify it by writing it down in code:
public interface IVehicle
{
string Brand { get; set; }
string Model { get; set; }
int HorsePower { get; set; }
}
public interface IMotorcycle
{
DateTime DateCreated { get; set; }
}
public abstract class Vehicle : IVehicle
{
public string Brand { get; set; }
public string Model { get; set; }
public int HorsePower { get; set; }
}
public class Car : Vehicle, IVehicle
{ }
public class Motorcycle : Vehicle, IVehicle, IMotorcycle
{
public DateTime DateCreated { get; set; }
}
public class Start
{
public IVehicle DoSomeStuff()
{
//Does some stuff
//Based on logic we either return
//a new Car or Motorcycle
//but if I return a motorcycle how would I be able to
//access the DateCreated attribute since I'm returning IVehicle
//I guess I have to cast it but is it a good practice to do that
//or am I setting up everything incorrect?
return new Motorcycle();
}
}
My questions: If we have a class say Start
which has a method that returns IVehicle
(public IVehicle DoSomeStuff()
). Based on the logic we will either return a new Car
or Motorcycle
. If we return a new Car
we will be able to access all properties since it only implements the IVehicle
interface, but let's assume that we return a new Motorcycle
how will be able to access the .DateCreated
property without casting it,
Is there a way to implement this better to instead have a common interace or did I miss anything?