Add value object examples (#66) · mperor/JavaLab@b525212 · GitHub
Skip to content

Commit b525212

Browse files
committed
Add value object examples (#66)
1 parent fd097bd commit b525212

4 files changed

Lines changed: 109 additions & 0 deletions

File tree

Lines changed: 19 additions & 0 deletions
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package pl.mperor.lab.java.clean.code.ddd.value.object;
2+
3+
import java.util.regex.Pattern;
4+
5+
record EmailAddress(String email) {
6+
7+
private static final Pattern PATTERN = Pattern.compile("^[A-Za-z0-9+_.-]+@(.+)$");
8+
9+
EmailAddress {
10+
if (email == null || PATTERN.asMatchPredicate().negate().test(email)) {
11+
throw new IllegalArgumentException("Invalid email address!");
12+
}
13+
}
14+
}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package pl.mperor.lab.java.clean.code.ddd.value.object;
2+
3+
import java.math.BigDecimal;
4+
import java.math.RoundingMode;
5+
6+
record Money(BigDecimal amount) {
7+
8+
Money(BigDecimal amount) {
9+
if (amount == null) {
10+
throw new IllegalArgumentException("Amount must not be null");
11+
}
12+
if (amount.compareTo(BigDecimal.ZERO) < 0) {
13+
throw new IllegalArgumentException("Amount cannot be negative!");
14+
}
15+
this.amount = setScale(amount);
16+
}
17+
18+
private BigDecimal setScale(BigDecimal input) {
19+
return input.setScale(2, RoundingMode.HALF_EVEN);
20+
}
21+
22+
public Money add(Money other) {
23+
return new Money(this.amount.add(other.amount));
24+
}
25+
26+
public Money subtract(Money other) {
27+
return new Money(this.amount.subtract(other.amount));
28+
}
29+
30+
public static Money of(BigDecimal amount) {
31+
return new Money(amount);
32+
}
33+
}
Lines changed: 43 additions & 0 deletions

0 commit comments

Comments
 (0)