Skip to content

Instantly share code, notes, and snippets.

@sandromancuso
Created February 8, 2015 23:27
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 sandromancuso/3ab5b84ede96a2e1520e to your computer and use it in GitHub Desktop.
Save sandromancuso/3ab5b84ede96a2e1520e to your computer and use it in GitHub Desktop.
@Test public void
print_transactions_in_reverse_chronological_order() {
given(clock.timeAsString()).willReturn("01/04/2014", "02/04/2014", "10/04/2014");
account.deposit(1000);
account.withdraw(100);
account.deposit(500);
account.printStatement();
InOrder inOrder = Mockito.inOrder(console);
inOrder.verify(console).printLine("DATE | AMOUNT | BALANCE");
inOrder.verify(console).printLine("10/04/2014 | 500.00 | 1400.00");
inOrder.verify(console).printLine("02/04/2014 | -100.00 | 900.00");
inOrder.verify(console).printLine("01/04/2014 | 1000.00 | 1000.00");
}
public class StatementPrinter {
public static final String STATEMENT_HEADER = "DATE | AMOUNT | BALANCE";
private Console console;
public StatementPrinter(Console console) {
this.console = console;
}
public void print(List<Transaction> transactions) {
printStatementHeader();
printStatementLines(transactions);
}
private void printStatementHeader() {
console.printLine(STATEMENT_HEADER);
}
private void printStatementLines(List<Transaction> transactions) {
List<String> statementLines = statementLinesFor(transactions);
reverse(statementLines).forEach(console::printLine);
}
private List<String> statementLinesFor(List<Transaction> transactions) {
final AtomicInteger runningBalance = new AtomicInteger(0);
return transactions.stream()
.map(t -> statementLine(runningBalance, t))
.collect(toList());
}
private String statementLine(AtomicInteger runningBalance, Transaction t) {
return
t.date() +
" | " +
formatWithTwoDecimalDigits(t.amount()) +
" | " +
formatWithTwoDecimalDigits(runningBalance.addAndGet(t.amount()));
}
private String formatWithTwoDecimalDigits(int amount) {
DecimalFormat decimalFormat = new DecimalFormat("#.00");
return decimalFormat.format(amount);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment