Search code examples
javaconstructornullnew-operator

Java constructor empty object


my first time asking here so sorry if not asking properly

public class Person
{
    private String name;
    private Date born;
    private Date died; //null indicates still alive.
    
    public Person(String initialName, Date birthDate, Date deathDate)
    {
        if (consistent(birthDate, deathDate))
        {
            name = initialName;
            born = new Date(birthDate);

            if (deathDate == null)
            {
                 died = null; 
            }
            else
            {
                 died = new Date(deathDate);
            }
        }
        else
        {
            System.out.println("Inconsistent dates.Aborting.");
            System.exit(0);
        }
    }
}

I have this code in my book. It is only part of the code, it is not a full code. I copied only the part that I was asking about. And my question is. Can't we just remove if (deathDate == null). If it is null, then died will be null anyway?


Solution

  • Keep reading. There is an else statement. What you propose is to replace this:

    if (deathDate == null) died = null;
    else died = new Date(deathDate);
    

    with:

    died = new Date(deathDate);
    

    which won't work; that would boil down to new Date(null) which will throw NullPointerException.

    NB: This is crazy code. When a precondition fails (inconsistent dates), you throw an exception. You don't print something to standard err and exit the entire VM. Replace those last two lines with throw new IllegalArgumentException("Death date cannot be before birth date. Death: " + death + " birth: " +birth);.