Is this design for dependency injection understandable?

I am working on a project with a large existing code base, and I was tasked with some reorganization of a small part. The existing code base does not have a large number of unit tests, but I would like at least the part that I am working on to have a complete set of unit tests with good code coverage.

Since the existing code base was not designed for unit testing, I need to make some structural changes to support dependency isolation. I try to influence the existing code as little as possible, but I have few opportunities to make changes to other modules. I would like to receive feedback on whether there are changes that I made, or if there is a better way to approach the problem. I made the following changes:

  • I extracted the interfaces for all the nontrivial classes that my coordinator class depends on. Other developers reluctantly admitted this, with a slight grunt.

  • I changed the coordinator class to refer only to the interfaces for its operation.

  • I could not use the DI structure, but I had to introduce a large number of dependencies (including adding additional dependencies as part of the class operation), so I changed the coordinator class to look like this (domain- specific names are simplified):

.

public sealed class Coordinator
{
    private IFactory _factory;

    public Coordinator(int param)
        : this(param, new StandardFactory())
    {            
    }

    public Coordinator(int param, IFactory factory)
    {
        _factory = factory;
        //Factory used here and elsewhere...
    }

    public interface IFactory
    {
        IClassA BuildClassA();

        IClassB BuildClassB(string param);

        IClassC BuildClassC();
    }

    private sealed class StandardFactory : IFactory
    {
        public IClassA BuildClassA()
        {
            return new ClassA();   
        }

        public IClassB BuildClassB(string param)
        {
            return new ClassB(param);
        }

        public IClassC BuildClassC()
        {
            return new ClassC();
        }
    }
}

factory, . , , factory, , . , , , . , , , , .


. - , . , .

+3
2

Injeciton, Bastard Injection. Bastard Injection -, , , .

Coordinator. , testability , IFactory , . , / , , , .

, , , IFactory .

.

+3

, , , IFactory internal, "" Coodinator. InternalsVisibleTo, .

+2

Source: https://habr.com/ru/post/1757840/


All Articles