Currently I have class Context which I inject in some places in my code, like:

protected override object GenerateSomething (object input, Context ctx)

Depending on Context, Generate method gives different results.

But, would it be better to create interface IGeneratorContext like this:

public interface IGeneratorContext
    ISomething1 GetX ();
    ISomething2 GetY ();

And change method signature to this:

protected override object GenerateSomething (object input, IGeneratorContext ctx)

And I will still pass Context object to this method. Ofcourse I wil add interface IGeneratorContext to Context class. So now I will pass same object, but as interface with less methods exposed.

Is it a good idea?


Yes, it would be a better option to use an interface.

As you have already pointed out yourself, by using an interface you have better control over which methods are exposed. But another important aspect of using an interface is loose coupling.

This is because the injected class no longer has to be a child of a perticular class. This means that the injected class can inherit another class, and it means your code will be easier to extend in the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.