Zero checks in the constructor and in the maintenance method?

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());//throws illegal arg exception
     //add code
  }
}

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!

+5
7

, , . : , , , , , ? , , , , . , , .

, , .

, -. , , , , , , , , . ValidatedPerson, Person, , addPerson , - , ValidationPerson - validate, .

+9

Ctor. :

  • Person.
  • , Person , Person.
  • , Person (, , , ).
  • - .

IntelliJ, JetBrain @NotNull @Nullable, IDE , Ctor . . http://www.jetbrains.com/idea/documentation/howto.html.

+5

.

  • .

, factory:

class Person {
    private final String name;
    private Person(String name) { // private constructor
        this.name = name;
    }
    public static Person newPerson(String name) { // factory method
        VerifyNotNull(name); // IAE not from c'tor, guaranteed check
        return new Person(name);
    }
 }

, , Builder, :

class Person {
    private final String name;
    private Person(String name) { // private constructor
        this.name = name;
    }

    /**
     * Usage: Person p = new Person.Builder(name).build();
     */
    public static class Builder {
        private final String name;
        public Builder(String name) {
            this.name = name;
        }
        public Person build() {
            VerifyNotNull(name); // IAE not from c'tor, guaranteed check
            return new Person(name);
        }
    }
}
+3

. , varibles , . , . , , , ( null ) .

+1

.

- fail fast - .. , , , ( ). , .

, , . , "" , - , ? , . - - , , . .

+1

, , - Person. , . Factory (Evans):

public class Person
{ 
    public Person()
    {
       //Nothing much here.
    }

    public static Person Create(String name)
    {
        VerifyNotNull(name);//throws illegal arg exception if name is null
        Person person = new Person();
        person.name = name;
        return person;
    }

    ...
}
0

, .

, , , -, ; - , - (: , . : " " ). Person, /, , .

0

All Articles