开发者

The battle between TDD/Injection and information hiding - A possible compromise?

I just proposed the following pattern for someone else. I have used it a few times, when I wanted the ability to inject dependencies for test, but but still wanted this backdoor 开发者_Go百科(somewhat) invisible to outsiders. Hence, the empty public ctor and internal ctor with the argument:

public class ClassThatUseInjection
{
    private readonly SomeClass _injectedClass;

    public ClassThatUseInjection(): this(new SomeClass()) {}

    internal ClassThatUseInjection(SomeClass injectedClass)
    {
        _injectedClass = injectedClass;
    }
}


public class SomeClass
{
    public object SomeProperty { get; set; }
}

My idea was that since the empty ctor does nothing but forward with a new instance, my crime is not too bad. What do you think? Is is too smelly?

Regards, Morten


I think it is ok. In fact, what you are doing with injecting the class is Dependency Injection and a practical use of the Open/Closed Principle.
I don't even see no harm in making that internal ctor into a public one.
My problem with this is always, that I don't want to force others to create an instance of the injected class, therefore, the default ctor. But if they want to create an instance, they can go ahead and do so.

On a related note: IMHO, you should use an interface instead of a class, otherwise, I don't see too much advantage in passing that class in the first place...


It's called "poor man's dependency injection", if you can't get a proper IOC container into your app its a reasonable alternative although you would be better off with the power a container gives you.

Jimmy Bogard has a good write up here


wanted this backdoor (somewhat) invisible to outsiders

Making it internal successfully does that, IMO.

The down-side is that it puts your tests in the same assembly.

See also Hide public method used to help test a .NET assembly about how to hide public methods if your tests are in an external assembly.


Edit: what you've done is especially appropriate, if SomeClass is logically internal ... if it's an implementation detail which shouldn't/needn't be exposed in the assembly's public interface.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜