I was reading on this SO page about when to check parameters when constructing an 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. The first option is violating Object Oriented Principles. Even the factory method is better designed than that.
Exactly what OOP principles are being violated when you throw an exception in the constructor? Is it the 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 way 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
Again, this is all part of the speculation, but it seems you're putting a lot of responsibility on the client to ensure the
Person object is valid when that should have been done when it was created.