Nani Nani - 1 month ago 6
C# Question

interface method (definition) dependent on another method (definition) defined in same interface

public interface ICar
{
bool IsSpeeds200KMPH(CarData carData);
bool IsABSEnabled(CarData carData);
int doors {get;set;}
int wheels {get;set;}
bool IsABSAdvanced();
bool IsSpeedReaches225();
void drive(CarType car);
}

public class BMW : ICar
{
}

public class Honda : ICar
{
}

// factory class to create car object dynamically
public class CarFactory
{
public ICar CreateCar(CarType car)
{
if(car == TypesOfCars.Honda)
return new Honda;
else if(car == TypesOfCars.BMW)
return new BMW;
//....
}
}


//main() method snippet
CarFactory factory = new CarFactory();
ICar carType = facory.CreateCar(DynamicallyProvided_CarTypeValue);
carType.IsABSEnabled(DynamicallyProvided_carData);
carType.IsABSAdvanced();


In above example I have implemented Strategy Pattern. My problem is, I have different Car classes implementing ICar interface. the method IsABSAdvanced() can be called only if the method IsABSEnabled() returns true, otherwise exclusively it should return false. Thus how I can make one interface method(definition) dependent on another method(definition) defined in the same interface? Is there any way to limit the restriction to interface level, such that anyone who access IsABSAdvanced() shoudln't know that it actually checks IsABSEnabled() method internally. Is there such feasibility or else how I can achieve it?

Answer

What you're looking for are abstract classes.

Interfaces only hold informations about the API a class should hold - not the logic that comes with it.

If you want logic ontop of it, you have a few options - one, for example:

public interface ICar
{
    bool IsSpeeds200KMPH(CarData carData);
    bool IsABSEnabled(CarData carData);
    int doors {get;set;}
    int wheels {get;set;}
    bool ABSAdvanced{get;};
    bool IsSpeedReaches225();
    void drive(CarType car);
}

public abstract class AbstractCar : ICar {
    public bool ABSAdvanced {
        get {
            if(!isABSEnabled()) {
                return false;
            }
            /* some additional logic based on the interface */
            /* ... */
            return true;
        }
    }
}

and then all cars extends AbstractCar - since AbstractCar is an abstract class it won't be able to be instantiated into an object.

Also your question probably can be simplified by:

public abstract class AbstractCar : ICar {
    public bool ABSAdvanced { get {return isAbsEnabled();} }
}

Which then again makes ABSAdavanced redundant if isABSEnabled is part of the public API depending on the implementation details.

Comments