Skip to content

Instantly share code, notes, and snippets.

@DhavalDalal
Last active April 15, 2019 03:46
Show Gist options
  • Save DhavalDalal/844a98e8813f6bbd2b1ebace56266aab to your computer and use it in GitHub Desktop.
Save DhavalDalal/844a98e8813f6bbd2b1ebace56266aab to your computer and use it in GitHub Desktop.
DRYing to Exception Monad

DRYing to Exception Monad (Java)

class Authenticate {
public static void main(String[] args) throws Exception {
final URL dashboard = new URL("http://dashboard");
final URL loginPage = new URL("http://login");
final String userid = "softwareartisan";
final String pwd = "1234";
User user;
Authenticator authenticator = new Authenticator();
try {
user = authenticator.login(userid, pwd);
} catch (Exception es) {
try {
user = authenticator.gmailLogin(userid, pwd);
} catch(Exception eg) {
Dispatcher.redirect(loginPage);
return;
}
}
URL target;
try {
long twoFactorPwd = 167840;
authenticator.twoFactor(user, twoFactorPwd);
target = dashboard;
} catch (Exception tfe) {
target = loginPage;
}
Dispatcher.redirect(target);
}
}
class Authenticator {
public User login(String id, String pwd) throws Exception {
// throw new Exception("password mismatch");
return new User(id, "Dhaval");
}
public User gmailLogin(String id, String pwd) throws Exception {
// throw new IOException("some problem");
return new User(id, "Dhaval");
}
public void twoFactor(User user, long pwd) {
// throw new RuntimeException("twoFactor Incorrect key");
}
}
class Dispatcher {
static void redirect(URL target) {
System.out.println("Going to => " + target);
}
}
class User {
private final String id;
private final String name;
User(final String id, final String name) {
this.id = id;
this.name = name;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment