Search code examples
language-agnosticoopparametersinterfaceinformation-hiding

Is it better to pass an *interface* or an *object* as a parameter to a function?


I'm trying to convince a colleague that a function should take an interface as a parameter, and not the object itself. I think small objects can be fine to pass across, but for large ones I would give them an interface and just pass the i/f over, not the whole thing.

Note that there will only ever be one of these large classes - the i/f will never be used for a different object. This is merely for hiding the implementation of an object.

Would you agree that separating a large class into an interface(s) is good practice?
Are there any disadvantages to doing this?

Example:

public interface class IVeryLargeClass
{
    void DoSomething();
    ...
};

public ref class VeryLargeClass : public IVeryLargeClass
{
public:
    virtual void DoSomething() { ... }
    ...
};

public ref class AnotherClass
{
public:
    AnotherClass(VeryLargeClass^ vlc)  { vlc->DoSomething(); }
 // OR
    AnotherClass(IVeryLargeClass^ vlc) { vlc->DoSomething(); }
};

Solution

  • One of the first principles you learn in OO development:

    Program to an interface, not an implementation.

    You indicate that "there will only ever be one of these large classes - the i/f will never be used for a different object". This might be true in your case, but I wish I had a nickel for every time such a statement turned out to be wrong.

    In addition to considering whether there might be multiple implementations of your interface, you should also consider whether your concrete object exports (or might export) additional methods that do not share a logical affinity with the operations declared in the interface. In such a case, you could simply declare the additional operations in one or more additional interfaces. A client, then, need only couple with the interface that exports the operations in which it is interested.

    Put simply, interfaces provide a means of managing the coupling between clients and providers.