yashashwi
yashashwi

Reputation: 50

How to simply introduce a new method on a large subset of classes implementing an interface?

I have an interface, say IVehicle, which is implemented in 100s of classes, some of them are variety of 4 wheeler and some are two wheeler dervied types.

I need to introduce a new method for all the 4 wheeler classes, lets say there are 50 of them. My challenge is to reduce the effort as much as I can.

I suggested, to introduce a new interface / abstract class with a method definition. But this require to change every 4 wheeler class declaration and extend with an extra parent.

Is there any possible way?

Upvotes: 0

Views: 61

Answers (1)

Justinas Marozas
Justinas Marozas

Reputation: 2682

If you really want to avoid changing all those classes and want a solution that can be considered to be OO, one thing you can do is decorate those classes where they are used and need this extra behaviour.

I'll use C# for example code as you mentioned you're looking for C#/Java solution.

interface IVehicle
{
    void DoThisNormalThing();
    // ...
}

interface IBetterVehicle : IVehicle
{
    void DoThisNeatThing();
}

class FourWheelVehicle : IVehicle
{
    public void DoThisNormalThing()
    {
        // ...
    }
    // ...
}

class BetterFourWheelVehicle : IBetterVehicle
{
    private readonly _vehicle;

    public BetterFourWheelVehicle(IVehicle vehicle)
    {
        _vehicle = vehicle;
    }

    public void DoThisNormalThing()
    {
        _vehicle.DoThisNormalThing();
    }

    public void DoThisNeatThing()
    {
        // ...
    }
    // ...
}

Then usage:

var vehicle = new FourWheelVehicle();
var betterVehicle = new BetterFourWheelVehicle(vehicle);
betterVehicle.DoThisNeatThing();

This can be done using extension methods as well (and would result in a little less code and fewer allocated objects), but as this question is tagged with [oop] I wouldn't say extension methods are an OO construct. They're much more aligned with procedural style as they turn your objects into bags of procedures.

Upvotes: 1

Related Questions