liveBook · Manning

Dependency

As explained in Grokking Software Architecture

A relationship in which one software component relies on another.

A dependency is an object another object needs to work. In layered systems, dependency arrows point downward: the UI commands the business layer, while returned data can travel upward without reversing source-code references. section 4.2.1 section 2.4.3

Hard-coding a database inside a report generator makes tests depend on that connection. Constructor injection supplies the dependency from outside, so a fake database can return controlled data. section 2.4.3

Listing 2.5 "After": Loosely Coupled (reportGenerator.js)
class ReportGeneratorAfter {  #A
  constructor(dbConnection) {  #A
    // The dependency is "injected" into the constructor.  #A
    this.dbConnection = dbConnection;  #A
  }   #A
 
  generate(reportName) {
    const data = this.dbConnection.getData(reportName);
    return `Report '${reportName}' generated with ${data.length} rows.`;
  }
}

See the report generator accept its database connection through the constructor instead of creating one itself. section 2.4.3

How Grokking Software Architecture covers it

How deep it goes
Defines dependencies and injection, then works through a database refactor and test using a fake object.
Examples
Contrasts a report generator with a hard-coded database connection against one tested with an injected fake database.
What you can do after
Apply constructor injection to replace a hard-coded database connection with a fake for isolated tests.
How it connects
Connects dependency direction with command flow and data flow, and dependency injection with loose coupling and unit testing.

Also explained in

Compare how 35 books explain dependency →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Software Architecture. The section links point to the parts of the book it draws on.