Skip to content

QuizNot attempted

Dependency inversion

Which is dependency inversion?
// A
function saveUser(user) { return fetch('/api/users', { method: 'POST', body: JSON.stringify(user) }); }
// B
function makeSaveUser(api) { return (user) => api.post('/users', user); }
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • B: high-level code depends on an abstraction (api) that is passed in, so it can be swapped or mocked
  • In B the high-level logic receives its dependency (api) as a parameter, so it depends on an abstraction that can be swapped (fetch, axios, GraphQL) or faked in tests.
  • Not A: it hard-codes fetch and the URL, so the dependency is concrete and fixed.
  • Not equivalent: only B can be tested without mocking globals.
  • Not needs a framework: passing an argument is dependency injection
  • Context and props do it in React.