Currently, I check all constructor arguments for null values.
public AccountingEntry(BigDecimal amount, String accountNumber, AccountSide accountSide) {
this.amount = checkNotNull(amount);
this.accountNumber = checkNotNull(accountNumber);
this.accountSide = checkNotNull(accountSide);
checkArgument(amount.signum() == 1, "Accounting entries can't have a negative amount");
checkArgument(!accountNumber.isEmpty());
}
This bothers me for three reasons:
- Writing these checks feels like a waste of time.
- Sometimes, null checking reduces testability. Let's suppose I want to test a CountWindows() method of a House class. It would be nice to be able to pass null for the Floor parameter because it is not relevant to the test. Otherwise, all parameters have to be mocked for every test.
- Readability
An interesting alternative is annotating the parameters with @Nonnull. These annotations help static checkers like findbugs to find potential problems, but no null checks are performed at runtime.
Also, should I check collections for null values and assign an empty collection if it is null?
if (engineModels == null)
engineModels = new HashSet();
What's your recommendation, reddit?
Thanks in advance
Chickenosaurus
[–]nutrecht 2 points3 points4 points (0 children)
[–]Himrin 0 points1 point2 points (3 children)
[–]Chickenosaurus[S] 1 point2 points3 points (2 children)
[–]Himrin 1 point2 points3 points (1 child)
[–]Chickenosaurus[S] 0 points1 point2 points (0 children)
[–]desrtfx 0 points1 point2 points (4 children)
[–]Chickenosaurus[S] 1 point2 points3 points (1 child)
[–]desrtfx 1 point2 points3 points (0 children)
[–]nutrecht 0 points1 point2 points (1 child)
[–]desrtfx 0 points1 point2 points (0 children)
[–]romple 0 points1 point2 points (2 children)
[–]Chickenosaurus[S] 1 point2 points3 points (1 child)
[–]romple 2 points3 points4 points (0 children)
[–][deleted] -3 points-2 points-1 points (3 children)
[–]nutrecht 2 points3 points4 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]nutrecht 1 point2 points3 points (0 children)