The problem with writing defensive fail early code, it doesn’t take long before methods are 70% argument checking, 30% logic:
public void Method(object arg1, object arg2) { if (arg1 == null) { throw new ArgumentNullException("arg1"); } if (arg2 == null) { throw new ArgumentNullException("arg2");</div> } ... ... ... }
Code contracts can be a great way to move code out of the method body, but how can you clean up the code just through traditional refactoring? For the last few projects I’ve worked on, I’ve been using a small helper class that abstracts all the conditional code out, leaving just a single line call for each check you need.
public void Method(object arg1, object arg2) { Throw.IfNull(arg1, "arg1"); Throw.IfNull(arg2, "arg2"); ... ... ... }
String parameter checking can wrap up even more conditional logic. The following code throws an ArgumentNullException if the string is null, or just an ArgumentException if it is empty or whitespace.
Throw.IfNullEmptyOrWhitespace(stringValue, "stringValue");
Get the code from GitHub.
As part of his fantastic ‘What is .NET standard‘ presentation at DDD12, Adam Ralph provided an amazing amount of detail in such a short amount of time. One of the most valuable points, which is completely obvious when you think about it, is how you should work with .NET standard when creating libraries. NET standard now comes in a multitude of flavours: currently 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6 and 2.0. When starting out . . .
If you’re trying to access a class library (.NET Standard) from a traditional console application (in VS2017 those can be found under ‘Windows Classic Desktop’) you will run into problems; which can feel a little strange for something that was pretty simple in VS2015 and earlier. You can add a reference to the class library project (Resharper will even volunteer to add the dependency / namespace reference if you don’t already have it). But the . . .