Verifying Parameters in Constructor or Service

by BasementJoe   Last Updated September 18, 2018 16:05 PM

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 name.

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.

Questions:

  1. 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?

  2. 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 Person object?



Related Questions