I have a factory class, which makes Order objects, which in turn create Item objects. These 3 classes are bundled in a single package with no other classes. Each item has an "ItemMode" attribute. I created excessive null checks to achieve a defensive programming style. While I am confident with this coding style, even though it can be a bit verbose, I'm now doubting this approach because of the following reasons:
- If the amount of created objects and the amount of arguments that need to be validated increases, that's a whole lot of code that must be run. Could this could performance issues? If so, are we talking about nano-, milli- or plain seconds?
- Considering only the factory is able to instantiate Order and Item objects, we could theoretically skip the redundant if==null checks in the other classes. I know no factory can be created with a mode that is null, so no Orders or Items could be created with a mode that is null. However, I know this because I wrote the code. This is not a priori clear for other developers on the project.
Would you keep the redundant checks or not?
I first made the Item class:
class Item
{
//Constructor
protected Item(ItemMode mode)
{
if(mode == null)
{
throw new IllegalArgumentException("mode should not be null.");
}
}
...
}
Then the Order class:
class Order
{
//Constructor
protected Order(ItemMode mode, ...)
{
if(mode == null)
{
throw new IllegalArgumentException("mode should not be null.");
}
}
...
public void methodThatMakesSomeItems()
{
...
}
}
And lastly the factory class:
class Factory
{
//Constructor
public Factory(ItemMode mode, ...)
{
if(mode == null)
{
throw new IllegalArgumentException("mode should not be null.");
}
}
...
public void methodThatMakesSomeOrders()
{
...
}
}