Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are hidden dependencies?

Could someone please give me an example of a hidden dependency. I've googled it, and found results like this:

"A visible dependency is a dependency that developers can see from a class's interface. If a dependency cannot be seen from the class's interface, it is a hidden dependency."

(Source - http://tutorials.jenkov.com/ood/understanding-dependencies.html#visiblehidden)

But I still don't quite get it.

Does it mean when a dependency is happening inside a function, and not a declared variable in the beginning of a class? Or is it when you simply create functions other than the signature methods declared in an interface?

like image 850
Jesper Avatar asked Oct 07 '17 02:10

Jesper


1 Answers

Transparent (Concrete) Dependency: A Transparent Dependency is a dependency which is set through a public constructor.

Opaque (Hidden) Dependency: An Opaque Dependency is a dependency that is NOT set through a public constructor, as a result it is not easy to see the dependency

Here is an example:

// Transparent Dependency
public class StudentService
{
    private IStudentRepository _studentRepository;
    public StudentService(IStudentRepository studentRepository)
    {
        _studentRepository = studentRepository;
    }

    public List<Student> GetStudents()
    {
        return _studentRepository.GetAllStudents();
    }
}

// Opaque Dependency
public class StudentService
{
    public List<Student> GetStudents()
    {
        var _studentRepository = new StudentRepository("my-db-name");
        return _studentRepository.GetAllStudents();
    }
}

Opaque Dependecies are considered to be an anti-pattern, this article highlights the problems with Opaque IoC:

  1. Writing tests for component implementing Opaque IoC is much harder

  2. Transparent IoC helps identity classes which are doing "too much"

Mark Seemann describes the second point elegantly:

One of the wonderful benefits of Constructor Injection is that it makes violations of the Single Responsibility Principle glaringly obvious.

Closely related to this is Nikola's 2nd law of IoC:

Any class having more than 3 dependencies should be questioned for SRP violation

like image 147
Hooman Bahreini Avatar answered Nov 11 '22 19:11

Hooman Bahreini