Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save zsoldosp/896231 to your computer and use it in GitHub Desktop.
Save zsoldosp/896231 to your computer and use it in GitHub Desktop.
comment for http://jamesshore.com/Blog/Lets-Play/Episode-98.html - making calculations look nicer (sad, no lambdas in java)
package com.jamesshore.finances.domain;
// import ....
public class ValidDollars extends Dollars {
public static final double MAX_VALUE = 1000000000d; // one beeeellion dollars!
public static final double MIN_VALUE = -1000000000d;
private double amount;
// ... <snip> ...
private double amount(Dollars dollars) {
return ((ValidDollars)dollars).amount;
}
private boolean outOfRange(double value) {
return (value > MAX_VALUE) || (value < MIN_VALUE);
}
private interface DollarsCalculation {
double perform(double thisAmount, double otherAmount);
}
private Dollars performCalculation(Dollars dollars, DollarsCalculation calculation)
{
// TODO: should InvalidDollars have an error message, taken from .ctor?
if (!dollars.isValid()) return new InvalidDollars(); // msg: dollars.reason
double result = calculation.perform(this.amount, amount(dollars));
if (outOfRange(result)) return new InvalidDollars(); // msg: overflow/underflow, inline logic here?
return new ValidDollars(result);
}
public Dollars plus(Dollars dollars) {
return this.performCalculation(dollars, new DollarsCalculation() {
public double perform(double thisAmount, double otherAmount)
{
return thisAmount + otherAmount;
}
});
}
// ... <snip> ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment