This is a topic in one of our code reviews, I would like to know more.
Let's say I'm writing a service that allows me to insert a simple Person object into a database.
public class Person
{
private String name;
....
}
We have a simple VerifyNotNull method throws an IllegalArgumentException.
Which route do you take and why.
Option 1:
Check the constructor of the Person object is not null, but
public Person(String name)
{
VerifyNotNull(name);//throws illegal arg exception if name is null
this.name = name;
}
Option 2:
Allow creation of Person with a null value, check invalid for addPerson call.
public class PersonService
{
public void addPerson(Person personToAdd)
{
VerifyNotNull(personToAdd.getName());
}
}
I don't like the idea of throwing exceptions in constructors. Option 2 seems right to me, I don’t know how to explain or justify it, though.
Are exceptions allowed in constructors?
Thank you for your help!