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 😉
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