Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should a constructor act when given invalid parameters?

Tags:

constructor

If a class has a constructor which takes some value object as parameter and relies on this to do its initialization. How should it react if this object is null?

class SomeClass
{
    private SomeData _data; 
    public SomeClass(SomeValueObject obj)
    {
        _data = obj.Data;
    }
}

This is one example, but in general: How should a constructor act if it is given invalid parameters and therefore cannot do the construction properly? Should it just return without doing any initialization? Set the parameters to some default values? Throw an exception? Something else?

I'm sure the answer to this is "It depends", but are there any best practices etc?

like image 489
stiank81 Avatar asked Jan 29 '10 22:01

stiank81


People also ask

What is a constructor with no parameters?

A constructor that takes no parameters is called a parameterless constructor. Parameterless constructors are invoked whenever an object is instantiated by using the new operator and no arguments are provided to new . For more information, see Instance Constructors.

What is a constructor with no parameters in Java?

1. No-argument constructor: A constructor that has no parameter is known as the default constructor. If we don't define a constructor in a class, then the compiler creates a default constructor(with no arguments) for the class.

Can a constructor accept parameters?

You can use any data type for a parameter of a method or a constructor. This includes primitive data types, such as doubles, floats, and integers, as you saw in the computePayment method, and reference data types, such as objects and arrays.

Should constructor throw?

One-stage constructors should throw if they fail to fully initialize the object. If the object cannot be initialized, it must not be allowed to exist, so the constructor must throw.


2 Answers

A programmer should be able to assume an object was successfully created, unless an exception is raised. The type of exception depends on the argument, but should nonetheless be unchecked. The last thing you want is the constructor fail to build a valid object and not tell the caller about it.

I think using default values in a constructor is a dangerous habit.

like image 140
Elliot Avatar answered Oct 22 '22 20:10

Elliot


A lot depends on your business logic. If your business logic requires SomeValueObject to be not null, meaning SomeClass could not be instantiated without SomeValueObject then the constructor should definitely throw an Exception, probably IllegalArgumentException.

like image 20
Mihir Mathuria Avatar answered Oct 22 '22 20:10

Mihir Mathuria