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
}
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
}
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)
}
}
Dependencies
The above function works, and the test also works. However, the following dependencies have been introduced:
Top comments (0)