Sohan's Blog

Things I'm Learning

DRY - Total 161 Duplicate ArgumentNullException Calls in ASP.Net MVC Source Code

There are 161 occurrences of the following code pattern inside the ASP.Net MVC source code: See details of which class and which line at
method(type argument)
  if(argument == null){
    throw new ArgumentNullException(“argument”)

So, in total this pattern introduces 312 lines of duplicate code without whitespaces and 644 lines of duplicate code including whitespaces. And the pattern is simple, just check a condition and throw exception if its true. Not to mention, there are numerous other duplications where string.IsNullOrEmpty is used to check for string arguments.
This observation is interesting to me. Since, I think it adds a lot of noise to the code. In fact, if you randomly look at any of the methods - you have a good chance of seeing the first few lines doing this exactly similar thing. And this adds noise to me. Not to mention that, the developer needs to write the code, write tests for this code and if one needs to use this method, somehow should know this in advance that passing a null will result in an exception. But of course, this is not explicit from the method signature unless the developer also takes the pain to put a documentation styled comment and mention about this ArgumentNullException.
To remove this clutter, I think C# can introduce a few language keywords such as the follows:
public void Authenticate(required User user)
public void AddNewUser(nonblank string userName)
A compiler can very easily compile the code and put the exception throwing logic based on these keywords. Call it a syntactic sugar or a language keyword, this is the kind of translation that seems to be perfect for the compilers. And I can foresee it being used in almost all methods we write, since if the methods require an argument they do it for a purpose and most of the time null is not expected anyway!
I don’t know if this will reach the people responsible for developing C#, but if it does, I think the community will really love this new language feature.
I know about workarounds using AOP or other hyped-but-seldom-used tricks to solve this problem. But these tricks often make life harder by introducing a learning curve and then punishing the learning by slowing down the application. So, its best to put in as a core language feature. What do you think?