Java Constructor Style (Check parameters aren't null)

Posted by Peter on Stack Overflow See other posts from Stack Overflow or by Peter
Published on 2010-06-08T13:39:55Z Indexed on 2010/06/08 13:42 UTC
Read the original article Hit count: 250

Filed under:
|
|
|

What are the best practices if you have a class which accepts some parameters but none of them are allowed to be null?

The following is obvious but the exception is a little unspecific:

public class SomeClass
{
     public SomeClass(Object one, Object two)
     {
        if (one == null || two == null)
        {
            throw new IllegalArgumentException("Parameters can't be null");
        }
        //...
     }
}

Here the exceptions let you know which parameter is null, but the constructor is now pretty ugly:

public class SomeClass
{
     public SomeClass(Object one, Object two)
     {
        if (one == null)
        {
            throw new IllegalArgumentException("one can't be null");
        }           
        if (two == null)
        {
            throw new IllegalArgumentException("two can't be null");
        }
        //...
  }

Here the constructor is neater, but now the constructor code isn't really in the constructor:

public class SomeClass
{
     public SomeClass(Object one, Object two)
     {
        setOne(one);
        setTwo(two);
     }


     public void setOne(Object one)
     {
        if (one == null)
        {
            throw new IllegalArgumentException("one can't be null");
        }           
        //...
     }

     public void setTwo(Object two)
     {
        if (two == null)
        {
            throw new IllegalArgumentException("two can't be null");
        }
        //...
     }
  }

Which of these styles is best? Or is there an alternative which is more widely accepted?

Cheers,

Pete

© Stack Overflow or respective owner

Related posts about java

Related posts about constructor