I was reading on this SO page about when to check parameters when constructing on object. The accepted answer suggests throwing the exception from the constructor, so that an invalid object cannot be constructed.
I agree with that approach, and I can't see how a
Person can be constructed without a
However one of the comments suggested:
I also agree that second option is better because it is more reusable than the first one. First option is violating Object Oriented Principles. Even factory method is better design than that.
Exactly what OOP principles are being violated when you throw an exception in the constructor? Is it guideline that a constructor shouldn't do work?
The other approach suggested by the OP was a
PersonService, however, this is just speculation, but with this approach are you hoping that the client code will call
public void addPerson(Person personToAdd) to verify that the person object doesn't contain a null? What happens if they find a away to circumvent that check? Or before
public void addPerson(Person personToAdd) they use that object in another class not written by them that expects a valid