-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMoney.java
More file actions
73 lines (59 loc) · 1.46 KB
/
Money.java
File metadata and controls
73 lines (59 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package sharedkernel;
import java.math.BigDecimal;
import java.util.Objects;
public final class Money {
private final BigDecimal value;
private final Currency currency;
public Money(
final BigDecimal value,
final Currency currency) {
ensureDecimals(value);
this.value = value;
this.currency = currency;
}
private void ensureDecimals(
final BigDecimal value) {
if(value.scale() > 2) {
String msg = "Max 2 decimals allowed";
throw new IllegalArgumentException(msg);
}
}
public Money add(Money other) {
validateSameCurrency(other);
BigDecimal sum = this.value.add(other.value);
return new Money(sum, currency);
}
public Money subtract(Money other) {
validateSameCurrency(other);
BigDecimal sum = this.value.subtract(other.value);
return new Money(sum, currency);
}
private void validateSameCurrency(
final Money other) {
if(!this.currency.equals(other.currency)) {
String msg = "Currency mismatch";
throw new IllegalArgumentException(msg);
}
}
public BigDecimal getValue() {
return value;
}
public Currency getCurrency() {
return currency;
}
@Override
public int hashCode() {
return Objects.hash(currency, value);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Money other = (Money) obj;
return currency == other.currency && Objects.equals(value, other.value);
}
}