Say you have these two methods:
Number 1:
void AddPerson(Person person) { // Validate person if(person.Name != null && IsValidDate(person.BirthDate) DB.AddPersonToDatabase(person); }
Number 2:
void AddPerson(string name, DateTime birthDate) { Person p = new Person(name, birthDate); DB.AddPersonToDatabase(person); }
Which of the two methods is the best one? I know the first one is more correct OO-wise, but I feel the second is more readable, and you don’t have to make sure the object is valid as the parameters make sure of this. I just don’t like to having to validate the objects anywhere I pass them as parameters. Are there other approaches?
EDIT: Thx for all the answers. To clarify, validating in the constructor and a IsValid method is of course a good approach, but in my code the valid state of the person is often dependant of the context and could vary from method to method. This could of course be a sign of bad design.
The code is just a example to describe the problem.
The first shouldn’t have to validate person.Name and person.BirthDate – they should be validated automatically by the
Personconstructor. In other words, if you’re passed a Person, you should know that it’s valid.On the other hand, you’d have to check that
personisn’t a null reference.It’s sometimes worth having convenience methods like the second version to avoid having to explicitly call the constructor quite as often though. It should usually just call the
Personconstructor and then delegate the work to the first form.