Skip to content

Instantly share code, notes, and snippets.

@hakaneroztekin
Last active August 21, 2019 03:00
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 hakaneroztekin/136f354e41f0b3ef7170da5e73ec5562 to your computer and use it in GitHub Desktop.
Save hakaneroztekin/136f354e41f0b3ef7170da5e73ec5562 to your computer and use it in GitHub Desktop.
// In the example above, the userLister is not initialized
class DependencyProblem {
private UserLister userLister;
// gets users from DB and renders to the view (just a trivial example)
public void render() {
List<User> users = userLister.getUsers();
view.render(users);
}
}
// If we initialize it like below, we increase coupling between classes (tight coupling)
// UserLister userLister = new UserListerDB();
// Also, if we want to change it, we need to use UserListerCommaSeparatedFile();
// This change is no problem for a small project but a nightmare for a huge project
// Inversion of Control Solution
class SpringIOC {
// Just adding the annotation is enough. Spring manages the dependency (DI).
@Inject // this and @Autowired are almost identical
private UserLister userLister;
public void render() {
List<User> users = userLister.getUsers();
view.render(users);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment