Last active
December 19, 2015 06:29
-
-
Save metasansana/5912291 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*The Great Dependency Injection.*/ | |
//This is psuedo code. Screw the syntax rules! | |
//No dependency injection. | |
class User { | |
private Database db; | |
private String email; | |
private String password; | |
public User (String email, Sting password) { | |
this.db = Database.getNewConnection(); //This might throw an exception if we can't connect! | |
this.email = email; | |
this.password = password; | |
} | |
public Boolean login () { | |
return this.db.attemptLogin(this.email, this.password); | |
} | |
} | |
//This is messy. If we wanted to change how we connect to the database or how we handle potential errors encountered upon doing | |
//so, we would have to modify the User class' constructor. | |
// We could change the constructor body to this: | |
public User (String email, Sting password) { | |
try { | |
this.db = Database.getNewConnection(); | |
}catch (Exception e){ | |
(new Logger).goTellOnThisMethod(e); | |
} | |
this.email = email; | |
this.password = password; | |
} | |
//But what's the purpose of the User class? To connect to the database? No! It's to log in the user (hence the login method). So why | |
//should we force our User class to care about connecting to the database? | |
//Enter Dependecy injection. | |
//Clearly, the User class has a dependecy on the Database class, as it uses it in its login() method. That's about it though so really that's | |
//the only place we should have any code relating to the Database class. | |
//So let's try that again: | |
//Constructor | |
public User (String email, Sting password) { | |
this.email = email; | |
this.password = password; | |
//No more code for here! | |
} | |
public Boolean login(Database db) { //Note we take a database object as an argument now. This is the injection of the dependency. | |
return db.attemptLogin(this.email, this.password); | |
} //Done | |
//This way all our User class does is login and any time we have to make changes to it, they are going to be directly related to logging in. | |
//That's it! We have now made the User class more maintainable because it is simpler. | |
//Now as for all that fancy database connection code, you can put that somewhere else where it makes sense. Best to use a factory method in | |
//my opinion. | |
user = new User ('apple@sauce.com', 'secretmonkey' ); | |
result = user.login((new DatabaseFactory).connect()); | |
if(result) { | |
//you are logged | |
} else { | |
//Call the NSA! | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment