Skip to main content

The Dreaded Service Locator Pattern

Torbjørn Marø recently blogged about Dependency Injection, due to Mark Seeman visiting the Norwegian .Net User Group in Bergen. This triggered my thinking about the dreaded Service Locator.

I have worked with several teams that favored a home-made ServiceLocator class, a static component referencing a set of services, typically chunks of functionality that are singletons that interact with something external like database, filesystem, or web-service.

My beef with the Service Locator is that you can put it in, and use it from anywhere: It can be used to grab services in a controller/action component, inside a service, in a domain object, inside a for-loop, anywhere. This sounds pretty powerful, but ends up bringing in a lot of maintenance problems.

Now, in spite of my troublesome experiences with it, I keep finding myself being pretty lousy at explaining the disadvantages of a ServiceLocator to my peers.

I therefore hunted through Seeman's blog for some better explanations, and here's what I found:

He totally nails it in the first post:
Service Locator is a well-known pattern, and since it was described by Martin Fowler, it must be good, right?
No, it’s actually an anti-pattern and should be avoided.
Let’s examine why this is so. In short, the problem with Service Locator is that it hides a class’ dependencies, causing run-time errors instead of compile-time errors, as well as making the code more difficult to maintain because it becomes unclear when you would be introducing a breaking change.
Also have a look at the comments for some more discussion and affirmation.

Seeman has also written a book on the subject of DI, and Service Locator is discussed within. I haven't read it, but it sounds pretty good, especially if you work with .Net.

In case you got a little lost in his C# examples, here's my own take on it:

Let's say you want to test a CustomerRepository (an already initialized field in this test class):

@Test customerRepositoryHasCustomers {
  assertTrue(customerRepository.hasCustomers());
}

Bang! This explodes in a null-pointer because you haven't injected the proper services that are used inside the hasCustomers method (via ServiceLocator). So you try again:

@Test customerRepositoryHasCustomers {
  ServiceLocator.setRemoteCustomerService(new MockCustomerService());
  assertTrue(customerRepository.hasCustomers());
}
Bang again! This is because there is another service which is used inside the hasCustomers method a little later. 

As you can see, once you know what you need, the ServiceLocator is pretty straight forward to use.  And you don't notice this need during runtime, because the ServiceLocator is fully populated during startup.  

(This explains why the Service Locator being a perfectly fine pattern for those who don't enjoy writing tests.)

Then there's the maintenance issue: If you change the hasCustomers method to make use of even more services, you won't discover that the tests are broken until you run them again. Also the other way around: If you remove use of services in the method, you aren't reminded to remove this superflous setup from your tests.

In total, Service Locator removes a whole lot of compile-time verification that would be nice to have. Again, this doesn't matter much for those who don't write tests.

But, it does matter for the over all drive towards good code and architecture. Quoting Mark Seeman again (from the end of the third post):
Refactoring from Service Locator to Abstract Factories make it more painful to violate the SRP.
Using Service Locators breaks the window that usually stops you from giving a class too much responsibility. Usually, when you see the number of constructor, or method arguments are towering past a handful, you start thinking "refactor?". But with the Service Locator in use, you don't get this reaction.

Comments

Popular posts from this blog

Open source CMS evaluations

I have now seen three more or less serious open source CMS reviews. First guy to hit the field was Matt Raible ( 1 2 3 4 ), ending up with Drupal , Joomla , Magnolia , OpenCms and MeshCMS being runner-ups. Then there is OpenAdvantage that tries out a handful ( Drupal , Exponent CMS , Lenya , Mambo , and Silva ), including Plone which they use for their own site (funny/annoying that the entire site has no RSS-feeds, nor is it possible to comment on the articles), following Matt's approach by exluding many CMS that seem not to fit the criteria. It is somewhat strange that OpenAdvantage cuts away Magnolia because it "Requires J2EE server; difficult to install and configure; more of a framework than CMS", and proceed to include Apache Lenya in the full evaluation. Magnolia does not require a J2EE server. It runs on Tomcat just like Lenya does (maybe it's an idea to bundle Magnolia with Jetty to make it seem more lightweight). I'm still sure that OpenAdvant

Encrypting and Decrypting with Spring

I was recently working with protecting some sensitive data in a typical Java application with a database underneath. We convert the data on its way out of the application using Spring Security Crypto Utilities . It "was decided" that we'd be doing AES with a key-length of 256 , and this just happens to be the kind of encryption Spring crypto does out of the box. Sweet! The big aber is that whatever JRE is running the application has to be patched with Oracle's JCE  in order to do 256 bits. It's a fascinating story , the short version being that U.S. companies are restricted from exporting various encryption algorithms to certain countries, and some countries are restricted from importing them. Once I had patched my JRE with the JCE, I found it fascinating how straight forward it was to encrypt and decrypt using the Spring Encryptors. So just for fun at the weekend, I threw together a little desktop app that will encrypt and decrypt stuff for the given password

What I've Learned After a Month of Podcasting

So, it's been about a month since I launched   GitMinutes , and wow, it's been a fun ride. I have gotten a lot of feedback, and a lot more downloads/listeners than I had expected! Judging the numbers is hard, but a generous estimate is that somewhere around 2000-3000 have listened to the podcast, and about 500-1000 regularly download. Considering that only a percentage of my target audience actively listen to podcasts, these are some pretty good numbers. I've heard that 10% of the general population in the western world regularly listen to podcasts (probably a bit higher percentage among Git users), so I like to think I've reached a big chunk of the Git pros out there. GitMinutes has gathered 110 followers on Twitter, and 63, erm.. circlers on Google+, and it has received 117 +'es! And it's been flattr'ed twice :) Here are some of the things I learned during this last month: Conceptually.. Starting my own sandbox podcast for trying out everythin

The academical approach

Oops, seems I to published this post prematurely by hitting some Blogger keyboard shortcut. I've been sitting for some minutes trying to figure out how to approach the JavaZone talk mentioned in my previous blog-post. Note that I have already submitted an abstract to the comittee, and that I won't publish the abstract here in the blog. Now of course the abstract is pretty detailed on what the talk is going to be about, but I've still got some elbow room on how to "implement" the talk. I will use this blog as a tool to get my aim right on how to present the talk, what examples to include, what the slides should look like, and how to make it most straightforward and understandable for the audience. Now in lack of having done any presentations at a larger conference before, I'm gonna dig into what I learned at the University, which wasn't very much, but they did teach me how to write a research paper, a skill which I will adapt into creating my talk: The one

Managing dot-files with vcsh and myrepos

Say I want to get my dot-files out on a new computer. Here's what I do: # install vcsh & myrepos via apt/brew/etc vcsh clone https://github.com/tfnico/config-mr.git mr mr update Done! All dot-files are ready to use and in place. No deploy command, no linking up symlinks to the files . No checking/out in my entire home directory as a Git repository. Yet, all my dot-files are neatly kept in fine-grained repositories, and any changes I make are immediately ready to be committed: config-atom.git     -> ~/.atom/* config-mr.git     -> ~/.mrconfig     -> ~/.config/mr/* config-tmuxinator.git       -> ~/.tmuxinator/* config-vim.git     -> ~/.vimrc     -> ~/.vim/* config-bin.git        -> ~/bin/* config-git.git               -> ~/.gitconfig config-tmux.git       -> ~/.tmux.conf     config-zsh.git     -> ~/.zshrc How can this be? The key here is to use vcsh to keep track of your dot-files, and its partner myrepos/mr for o