Tuesday, February 17, 2015

On parameter validation

Many good developers think that the more you validate your inputs the better.

My favorite example of this is validation of constructor parameters.
Too often I can see a pattern like this:

public Client(string instanceUrl, string accessToken, string apiVersion, HttpClient httpClient)
{
    if (string.IsNullOrEmpty(instanceUrl)) 
    {
        throw new ArgumentNullException("instanceUrl");
    }
    
    if (string.IsNullOrEmpty(accessToken)) 
    {
        throw new ArgumentNullException("accessToken");
    }
    
    if (string.IsNullOrEmpty(apiVersion)) 
    {
        throw new ArgumentNullException("instanceUrl");
    }

    if (httpClient == null) 
    {
        throw new ArgumentNullException("httpClient");
    }

    _serviceHttpClient = new ServiceHttpClient(instanceUrl, apiVersion, accessToken, httpClient);
}

So we have one line of  useful code burried in 16 lines of noise. 

Not all parameter validation is like this, but constructor parameters are often a great example. Suppose you use dependency injection and a DI container like Unity. What is a chance it will ever send you null in your parameter?

Zero. 

So why are you validating it?

To look good. To look like a good, careful developer. There is no other purpose of this piece of code. Get rid of it. It is worth more dead than alive.

Or if you insist you really want to have it, are you willing to unit test it too? Are you really willing to add another 30+ lines of code to test these 16?

The main issue with this code is not that it is useless.  Neither it is how it violates single responsibility principle. Yes, being useless is enough to kick it out. Yes, violating single responsibility is a serious sin.

But it is actively risk-prone and thus harmful. Do you disagree? Fine. And did you actually spot the error in the code? There is classic copy-paste error there. Exactly the one you will have in your code sooner or later.

Don't get me wrong. Parameter validation is important. But understand what, how and why do you validate.

To be continued.

No comments:

Post a Comment