Reputation: 13
In the book "Implementing Domain Driven Design" of Vaughn Vernon, in the Testing of Value Objects section, the author talks about how we can use just shallow copy instead of deep copy to test the mutability of an object.
This is the constructor of BusinessPriority
public final class BusinessPriority implements Serializable {
private static final long serialVersionUID = 1L;
private BusinessPriorityRatings ratings;
public BusinessPriority(BusinessPriorityRatings aRatings) {
super();
this.setRatings(aRatings);
}
public BusinessPriority(BusinessPriority aBusinessPriority) {
this(aBusinessPriority.ratings());
}
This is the testcase
public void testCostPercentageCalculation() throws Exception {
BusinessPriority businessPriority = new BusinessPriority(
new BusinessPriorityRatings(2, 4, 1, 1));
BusinessPriority businessPriorityCopy =
new BusinessPriority(businessPriority);
assertEquals(businessPriority, businessPriorityCopy);
BusinessPriorityTotals totals = new BusinessPriorityTotals(53, 49, 53 + 49, 37, 33);
float cost = businessPriority.costPercentage(totals);
assertEquals(this.oneDecimal().format(cost), "2.7");
assertEquals(businessPriority, businessPriorityCopy);
}
This is the equals method
@Override
public boolean equals(Object anObject) {
boolean equalObjects = false;
if (anObject != null && this.getClass() == anObject.getClass()) {
BusinessPriority typedObject = (BusinessPriority) anObject;
equalObjects =
this.ratings().equals(typedObject.ratings());
}
return equalObjects;
}
As I can see, shallow copying is not enough in this case, because shallow copying will make businessPriority.rating() and businessPriorityCopy.rating() refer to the same object, thus always equal regardless of whether some attribute of this object is changed or not
So am I correct and if so, why the book talks about shallow copying in this case ?
/////////////////////
Upvotes: 0
Views: 53
Reputation: 1017
Because he is not testing the equality on ratings but instead of the value object holding the rating.
because they are equal by value (and not reference), think a value object as a java 17 records, the test demonstrates that two immutable objects remains equals by shallow copy.
Upvotes: 0