Hi I am making a Value Object.
public class Age
{
public Age(int age)
{
Value = age
}
public int Value { get; private set; }
}
I want to check that the value being passed inside the constructor is valid. It seems very reasonable and practical to me that we should put the validation inside the constructor and if the parameter is not valid then we should throw an exception.
Then I saw some stackoverflow post which advised against it and they made a very good point. They said that suppose: You have business requirement that age must be greater than 18. So you add a check in your constructor and if the passed age is less than 18 you throw an exception. But after some time requirement changes and now valid age is 21. So you change the validation logic to throw an exception if the age is less than 21.
Now the problem arises, how would you construct the object which were saved with the age 18 - 20?
So now I'm confused as to where I should my validation logic because for a ValueObject I think it should be inside the value object somewhere.