Polymorphism – Handling Unused Function Parameters

interfacesparameterspolymorphism

I had a discussion with a co-worker about interface members having parameters that some implementations don't use.

Say I have an interface

interface IDoctor
{
    string GetMedicalOpinion(Age age, Weight weight, SleepSchedule sleepSchedule, Symptom symptom)
}

Implementations of IDoctor won't necessarily use every method parameter:

class BadDoctor : IDoctor
{
    string GetMedicalOpinion(Age age, Weight weight, SleepSchedule sleepSchedule, Symptom symptom)
    {
        if (Symptom == Symptoms.Fatigue)
            return "You're sick!";
        return "You're okay."
    }
}

My co-worker thinks that the interface is poorly defined because there are implementations that don't use every method parameter.

I think this is fine. Having one method with all of the parameters gives us polymorphism — we can swap in IDoctors of varying competence without modifying the surrounding code. Also, the parameters are immutable data, so consumers shouldn't have any expectation that the function does anything other than return a string. Finally, the parameters are all things that consumers should have naturally, so providing the info isn't a burden on consumers.

Does this violate contemporary design principles? Is there really a problem with interface members having parameters that are used by some implementations, but ignored by others?

Best Answer

I think the main problem is actually caused due to a reason that has been widely discussed recently on this exact board, Should we avoid custom objects as parameters?

In order to call the method you defined, you inherently need to deconstruct the object the attributes belong to.

By changing the method signature to the one in the following example, you eliminate the need to pass unused parameters.

interface IDoctor
{
    string DetermineMedicalState(IPatient patient);
}

It really seems like all the properties you are passing belong to one patient anyway, so keep them together in an object. That's what objects are also used for, to reduce the number of parameters.

With this approach you know the method accepts an IPatient variable and couldn't care less which type of doctor extracts which information from it.


To answer the questions you asked, I don't really think the initial design violates any rules, as long as it respects the contract given by the interface. But it's not an elegant design either and perhaps not even the right one.

By passing an IPatient object you still have polymorphism at hand, thus haven't lost anything.

Related Topic