In order to decouple code you can have service locater's but is this not the same as global variables/state?.
I know these often run off interfaces, so you pass in an interface and get a concrete class back but still my question stands.
For example:
class Something {
void DoSomething() {
IMyType myType = ServiceLocator.GetSerivceTypeOf(IMyType);
}
}
Here the class requires MyType which is created somewhere else, but rather than passing MyType down through the chains (via constructors etc...) it is acquired in this manner.
I asked this question early in my professional career as a developer - prior to then I'd not come across this pattern. Anthony has nailed my opinion (and therefore is the selected answer now) on service locator's - in fact I see them as anti-patterns like others. The links provided are a good starting point - but to somewhat answer my own question after all this time, they act as global state and should be avoided. Prefer standard dependency injection ;)
To implement the IoC, you have the choice of two main patterns: Service Locator and Dependency Injection. The Service Locator allows you to "resolve" a dependency within a class and the Dependency Injection allows you to "inject" a dependency from outside the class.
It can be difficult to give up on the idea of directly controlling Dependencies, and many developers take Static Factories to new levels. This leads to the Service Locator anti-pattern. A Service Locator supplies application components outside the Composition Root with access to an unbounded set of Dependencies.
With service locator the application class asks for it explicitly by a message to the locator. With injection there is no explicit request, the service appears in the application class – hence the inversion of control.
The reason global variables are bad is that they enable functions to have hidden (non-obvious, surprising, hard to detect, hard to diagnose) side effects, leading to an increase in complexity, potentially leading to Spaghetti code.
Yes they are global variables. Sophisticated ones, but they still have the same basic drawbacks. For that reason, dependency injection is preferable.
For more detailed discussion of the alternative of constructor injection, see also the question What’s the difference between the Dependency Injection and Service Locator patterns?
And other web pages Singletons are Pathological Liars and Dependency Injection pattern
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