I am reading the documentation of Microsfot acording with DDD. And in the validations sections it use this example to exaplain that the final state of an address it would be invalid:
public void SetAddress(string line1, string line2,
string city, string state, int zip)
{
_shippingAddress.line1 = line1 ?? throw new ...
_shippingAddress.line2 = line2;
_shippingAddress.city = city ?? throw new ...
_shippingAddress.state = (IsValid(state) ? state : throw new …);
}
And it tells: If the value of the state is invalid, the first address line and the city have already been changed. That might make the address invalid.
But I don't understand 2 points:
1.- If the state is invalid, wouldn't it throw an exception and then the address is not created?
2.- The first line of the address, if I don't misunderstand, the unique constrainst is that it has to be not null, but accept any value. If it is null, it throws an exception and the address is not created. if it is not null, it is correct, why if the state is not valid, the first line of the address is not valid?
Thanks.
CodePudding user response:
The problem is that there is some API here - SetAddress() - that allows to change parts of the already existing shipping address object while other's are not set properly yet.
For instance, I could easily just set address line1 one and pass in null for city when calling SetAddress(). Nothing keeps the caller from of SetAddress to then just catch the exception and move on leaving address line 1 set but city unset. And voila, you have an incomplete address, assuming it is incomplete without a city.
This is why such domain concepts like address should always be replaced as a whole to not allow inconsistent half-set objects. If SetAddress() would only accept an address class instance as a hole and address itself would only allow creation with all required mandatory values that can be easily avoided.
These situations also relate to the concepts of value objects and immutability. In addition, by working with value objects countermeasures the so called primitive obsession code smell.