This gives the same effect, but you're right with extra lines of code
No no. Consider:
public void TransferMoney(Account from, Account to, decimal amount) { from.Debit(amount); to.Credit(amount); }
against
public void TransferMoney(Account from, Account to, decimal amount) { // Ideally do them separately if (from == null || to == null) { throw new ArgumentNullException(); } from.Debit(amount); to.Credit(amount); }
Both will fail with exceptions, but the first one will not work if a side effect is triggered first. This is bad and should be avoided whenever possible.
(Obviously, in a real scenario, this would supposedly be transactional, and there would be no real harm, but you accept my point.)
Also, if one parameter is used as an argument for another method or, even worse, saved for later use, you can end up eliminating the exception from a completely different place so that it can completely exclude - Obviously, there was an original problem .
Usually I check only null parameters only for non-private methods, but leave private methods to throw a NullReferenceException.
This seems like a pretty reasonable policy. If a private / internal method is called from some hairy code, and I am concerned that I may have mixed up the situation, I sometimes check it even then.
Jon skeet
source share