Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface Dependencies [closed]

Tags:

c#

oop

When you create an interface and you know you will have a dependency on another, do you make the constructor part of the interface?

In my case, I want to create

An IClientReceiveRecorder that I can give to a client and have all the network traffic collected for a short test session. It is probably just going to contain a collection of strings.

An IEvaluator that can get all the messages received and implement various things we want to test for. For example, I might have a concrete Evaluator that tests whether or not all the strings contain the letter 'c'.

I know that any IEvaluator is going to need a IClientReceiveRecorder to get the messages it is to evaluate.

So, I see a few options. Do I do something like

interface IEvaluator
{
    IEvaluator(IClientReceiveRecorder);

    void Evaluate();
} 

It doesn't compile, so I am guessing not.

Perhaps I do something like

interface IEvaluator
{
    void Evaluate(IClientReceiveRecorder);
}

Or, do I just leave it up to the concrete class to take a IClientReceiveRecorder in its constuctor?

like image 945
Christopher Pisz Avatar asked Dec 23 '22 11:12

Christopher Pisz


2 Answers

The straight forward answer is to leave implementation detail up to the concrete class.

Knowing that the implementation of IEvaluator is going to have a dependency of IClientReceiveRecorder is an implementation detail and would not be included in the IEvaluator interface.

If you know that the interface is going to be composed of another interface you could do something like the following:

interface IEvaluator
{
    IClientReceiveRecorder { get; set; }

    void Evaluate();
}

How that property is populated is an implementation detail and should not be part of the interface.

like image 100
Matt Rowland Avatar answered Jan 13 '23 02:01

Matt Rowland


You really shouldn't need to.

An interface isn't necessarily a contract of dependencies, it's a contract of functionality. Any implementation can expose its dependencies via constructor(s). But in the event that a different implementation has different (or no) dependencies, it still implements the interface and exposes the functionality.

One thing you could do is expose a property getter in the interface which shows the dependency. This would at least imply to implementing types that they need to expose a getter with the intended type, which happens to be a dependency.

Another alternative entirely might be to use an abstract class instead of an interface. (Understanding the differences between them, of course.) That abstract class can also use a constructor to expose the dependency, and implementing types would have to use that constructor. This alternative could necessitate other changes throughout your code, so it's up to you.

like image 28
David Avatar answered Jan 13 '23 02:01

David