DEV Community

loading...
Cover image for Dependency Injection: Write  code that's easier to debug

Dependency Injection: Write code that's easier to debug

_toul_ profile image Toul Updated on ・1 min read

Dependency injection is the idea of removing dependencies from within a function and aids in building a more resilient codebase by doing so.

Removing dependencies from a function also makes it easier to debug because tests are more straightforward to conduct.

To better understand dependency injection, an example will be shown using test-driven development.

Example

Suppose we have a file called user.json containing a single user's information, and we want to get their age via a function.

Data Structure

// user.json
{
  "age": 34
}
Enter fullscreen mode Exit fullscreen mode

Function

type User struct {
 Age int `json:"age"`
}
// GetUserData opens a file and returns a piece of data
func GetUserData(fPath String) (String, error) {
 userFile, err := os.Open(fPath)
 if err != nil {
 fmt.Println(err)
 }
 byteValue, _ := ioutil.ReadAll(userFile)
 var u User
 json.Unmarshal(byteValue, &u)
 return u
}
Enter fullscreen mode Exit fullscreen mode

Test Function

func TestGetUserData(t *testing.T) {
 t.Parallel()
 got, _ := GetUserData("../test/resources/user.json")
 s := fmt.Sprint(got)
 if s == "" {
 t.Errorf("Wanted %s got %s", got, s)
 }
}
Enter fullscreen mode Exit fullscreen mode

Dependencies

The above function works, and the test also works. However, the following dependencies have been introduced:

continue reading...

Discussion (0)

pic
Editor guide