Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

For example lets take this method: public List<string[]> ReadAll(int listCapacit

ID: 639816 • Letter: F

Question

For example lets take this method:

public List<string[]> ReadAll(int listCapacity)
{
    List<string[]> list = new List<string[]>(listCapacity);

    while (Read())
    {
        list.Add(GetCurrentRow());
    }

    return list;
}
If listCapacity is less than zero, an ArgumentException will be thrown by the constructor of List<T>. Does it make sense to double check this? Passing the argument to List<T> immediately seems careless, but checking it seems silly because List<T> will definitely check it.

Important note: the code snippet is not just a copy-paste method, its part of a full utility.

Explanation / Answer

Aside memory allocation reason (which, by the way, looks like premature optimization to me), there are other elements in favor of catching invalid arguments as soon as possible:

Stack trace

When an exception occurs, you expect the few last lines to show you the location of a mistake. Having to search from bottom to top of the stack to find the culprit will waste your time later, during debug, when you specifically won't have time.

Being sloppy about input validation and letting called methods handle that again and again will mean that the stack trace will be larger than it should be. If you know that ReadAll cannot accept a negative capacity, why adding a line to stack trace, instead of throwing an exception right now in order to make the debugging easy?

Readability

Your code is expected to be self-documenting. I can only know your method doesn't accept negative values if I inspect the method closely. This is OK if I'm about to modify the method; this is not OK if I simply want to use the method, and don't really care how is it implemented.

And no, I can't rely on documentation, since it's always incomplete and obsolete.

Validating the inputs right at the top of the method would help readability: it would be clear that I can't use negative values, and I would avoid wasting additional time:

Inspecting the body of the method,
Inspecting every method in the code base this method calls,
Reading MSDN for every .NET Framework method this method calls.
Code contracts

Since you tagged your question .net and your code looks like C#, I can't avoid talking about code contracts. If you have used code contracts, you would be forced to add a Contract.Requires anyway, otherwise the static checker will complain that nothing guarantees that the list constructor will be called with valid arguments.

That's also the benefit of code contracts: they force you to handle invalid inputs at the top of the stack, so when the input is invalid, you stop right now, instead of calling dozens of other methods before encountering an exception.