Skip to content

Instantly share code, notes, and snippets.

@abbi-gaurav
Created October 23, 2014 06:15
Show Gist options
  • Save abbi-gaurav/6d1a9ffa19cd4bc6640d to your computer and use it in GitHub Desktop.
Save abbi-gaurav/6d1a9ffa19cd4bc6640d to your computer and use it in GitHub Desktop.
Using Java 8 lambdas to lift the exceptions and remove boiler plate try-catch
package lambdas;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.function.Function;
/**
* Created by gabbi on 19/10/14.
*/
public class BankAPIsClient {
public static void main(String... args) throws AccountMgrException, LoanManagerException {
RecordsFetcher delegator = new RecordsFetcher();
new AccountManager(delegator).getAccountsDetails();
new LoanManager(delegator).getLoanRecords();
}
}
class AccountManager {
private final RecordsFetcher delegator;
public AccountManager(RecordsFetcher delegator) {
this.delegator = delegator;
}
public java.util.List<String> getAccountsDetails() throws AccountMgrException {
return delegator.perform("/sm/path/to/Account/Records/", ex -> new AccountMgrException(ex, "Error during Fetch"));
}
public java.util.List<String> getAccountsDetailsNormalWay() throws AccountMgrException {
try {
//a low level API to get data from IO or over the wire
return delegator.perform("/sm/path/to/Account/Records/");
} catch (IOException e) {
//logging can be done here
throw new AccountMgrException(e, "Error during Fetch");
}
}
}
class AccountMgrException extends Exception {
public AccountMgrException(Exception ex, String message) {
super(message, ex);
}
}
class LoanManager {
private final RecordsFetcher recordFetcher;
public LoanManager(RecordsFetcher fetcher) {
this.recordFetcher = fetcher;
}
public java.util.List<String> getLoanRecords() throws LoanManagerException {
return recordFetcher.perform("/sm/path/to/Loan/Records/", ex -> new LoanManagerException("Error fetching loan records", ex));
}
}
class LoanManagerException extends Exception {
public LoanManagerException(String message, Exception ex) {
super(message, ex);
}
}
class RecordsFetcher {
public <E extends Exception> java.util.List<String> perform(String fileName, Function<IOException, E> exceptionLifter) throws E {
try {
return Files.readAllLines(Paths.get(fileName));
} catch (IOException e) {
//logging can be added here
throw exceptionLifter.apply(e);
}
}
public List<String> perform(String path) throws IOException {
return perform(path, ex -> ex);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment