Question

I know you can't create a program that adheres 100% to the Dependency Inversion Principle. All of us violate it by instantiation strings in our programs without thinking about it. Since String is a class and not a datatype, we always become dependent on a concrete class.

I was wondering if there are any solutions for this (purely theoretical speaking). Since String is pretty much a blackbox with very few 'leaks', and has a complex background algorithm, I don't expect an actual implementation ofcourse :)

Was it helpful?

Solution

The intent of the principle is not to avoid creating instances within a class, or to avoid using the "new" keyword. Therefore instantiating objects (or strings) does not violate the principle.

The principle is also not about always creating a higher-level abstraction (e.g. an interface or base class) in order to inject it and promote looser coupling. If an abstraction is already reasonable, there is no reason to try to improve on it. What benefit would you ever gain by swapping out the implementation of string?

I actually posted this question a few years ago (semi-relevant): IOC/DI: Is Registering a Concrete Type a Code Smell?

So what is the principle about? It's about writing components that are highly focused on their own responsibilities, and injecting components that are highly focused on their own responsibilities. These components are usually services when using a dependency injection framework and constructor injection, but can also be datatypes when doing other types of injection (e.g. method injection).

Note that there is no requirement for these services or datatypes to be interfaces or base classes--they can absolutely be concrete types without violating the principle.

OTHER TIPS

Dependeny inversion is not about creation of object, its about high-level/low-level module dependency and who define the Domain (object and interface).

You are talking about dependency injection, a sub-part of the Inversion of Control principle.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top