So let’s say I have a generic object, Person. A person has a name and a gender – name must be a string, and gender must be male or female. I also have a collection object, PersonList, that has an array of Person objects and allows operations on the set (eg., return a list of people of a certain gender.)
On one hand, it’d be nice to create the PersonList with the data in the constructor…
list = new PersonList([new Person('Alice', 'Female'), ...]);
…but then we don’t know if the data is valid. We can allow invalid Person objects in, and check their validity when we access them, or we can give Person a vaild() method and say…
list = new PersonList();
alice = new Person('Alice', 'Female');
if (alice->valid()) list->add(alice);
…or maybe we check valid() within add(). But it seems weird to me to have a valid() method at all.
Generally speaking, how would you instantiate these objects? Is this a subjective thing, or is there a universal “right way”?
If you trust yourself never to create invalid objects, you don’t really need a method to check validity. However, if you’re going to be creating potentially invalid objects based on user data, then you should have a validity checking method, and calling that method should be the last thing the constructor does. If transformations to that object can occur that can render it invalid, said method should also be called immediately after said transformations occur. Invalid objects should be caught instantly, and the end user of the class should never have to worry about it, beyond being thrown the occasional exception.