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 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
.
Seems like this is Java, but in C++ it should definitively throw ( a std::invalid_argument
even ).
See C++ FAQ Lite 17.2.
I guess that for Java it's exactly the same.
In the rare cases where throwing exceptions presents a too big of a overhead, you should return, and set a flag in the object that it didn't construct properly. Afterwards check a isValid()
member function.
Throw a null argument exception.
If field is critical it should cast an exception to indicate that object shouldnt be used. If its not critical you can assign default values.
If an object can have invalid default values, then it should initialize to the default values and wait for initialization. E.g., foo.set_values(...)
. In this case, there should be a query of is_ready()
or is_valid()
to allow checking before use.
If an object can absolutely not be in an invalid data-state, then it should throw an exception.
Both of these cases are things I've encounted.
精彩评论