Skip to content

Instantly share code, notes, and snippets.

@fgarcia
Last active January 22, 2019 22:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fgarcia/bf044c178a7d90cfcaa81a3f6e95119d to your computer and use it in GitHub Desktop.
Save fgarcia/bf044c178a7d90cfcaa81a3f6e95119d to your computer and use it in GitHub Desktop.
Composition Root and Service Locator

If a program needs to make an API call, it is very likely that there is an ApiClient class to make http requests.

let api = new ApiClient('https://api.bank.com')
let bank = new BankFacade(api)

Since I consider an http request as something very basic in any app, I like having this in my runtime

$runtime.services.httpRequest()

The ApiClient has a static dependecy on that global dependency.

Originally I thought it was a great idea becase that way I knew if any part of my code had to make an http request, sooner or later it would go through that point.

Having that point makes easy mocking http requests. However I realized later one should not be mocking http calls. Instead I should mock the objects from those calls.

Despite the code smell I keep using this strategy for two reasons

  1. I like being able to mock http calls when I prototype code
  2. I have a way to throw an error if a test makes an unexpected API call to the outside request.

Nowdays I enforce some light 'test' awareness in my code.

  • Outside world actions (http request, shell, filesystem access...) will fail if the code runs in a testing environment
  • Each service can encode some fake/mock factory with common testing needs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment