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?
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.
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With