Last active
April 15, 2019 03:46
-
-
Save DhavalDalal/844a98e8813f6bbd2b1ebace56266aab to your computer and use it in GitHub Desktop.
DRYing to Exception Monad
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
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); | |
} | |
} |
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
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"); | |
} | |
} |
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
class Dispatcher { | |
static void redirect(URL target) { | |
System.out.println("Going to => " + target); | |
} | |
} |
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
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