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?
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:
Writing tests for component implementing Opaque IoC is much harder
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With