Please see the code below:
public interface ISport { int FitnessLevel { get; } int Players { get; } int Duration { get; } } public class Football : ISport { public int FitnessLevel { get; } = 5; public int Players { get; } = 11; public int Duration { get; } = 90; } public class Person { private readonly ISport _sport; private Guid _id; private readonly int _fitnessLevel; public Person(ISport sport, Guid id, int fitnessLevel) { _id = id; _sport = sport; _fitnessLevel = fitnessLevel; if (sport == null) { throw new ArgumentException("Sport cannot be null.", "Sport"); } if (_sport.FitnessLevel > fitnessLevel) { throw new ArgumentException("Fitness Level is not high enough.", "FitnessLevel"); } if (id == Guid.Empty) { throw new ArgumentException("ID cannot be empty.", "ID"); } } }
and the test code below:
ISport sport = new Football(); Person person = new Person(sport, Guid.NewGuid(), 3);
The Person constructor throws an exception in this case because the persons fitness level is not enough to play the sport in question.
Please focus on the code below:
if (_sport.FitnessLevel > fitnessLevel) { throw new ArgumentException("Fitness Level is not high enough.", "FitnessLevel"); }
Notice that the Football class is used to validate the Person. Is this a normal to approach validation like this:
1) A Value Objects member is used to validate an entity
2) A Value Objects member is used to validate another value object
I am asking this because I have never seen validation approached like this before and I am trying to follow the principle of least astonishment these days.