C#: Argument validation: null/empty strings - c#

I don't know how many countless times I've had to write code to validate string arguments:
public RoomName(string name)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException("Cannot be empty", "name");
}
}
Is there anyway to avoid this? Is there some attribute or design-by-contract mechanism to avoid this? Is there no way to say:
public RoomName(NotNullOrEmptyString name)
{
without having to actually create that type?

You can do that via code injection with attributes.
Another option to save some coding time, but still give you a lot of control, would be to use something like CuttingEdge.Conditions. This provides a fluent interface for argument checking, so you can write:
name.Requires().IsNotNull();

Though the question has been answered a while ago, I have been thinking about the same problem lately. Formalized code contracts (with automatic verification or checks) seem to be a good idea, but generally, their verification-capability is quite limited, and for simple checks like null- or empty-string checking, they require just as much code (or more) than the old-fashioned checks.
Ironically, the best answer in my opinion for the string-case is indeed one or two classes that wrap a string that has been checked not to be null, empty or white-space, and pass this instance around:
public class NonEmptyString : IComparable<NonEmptyString>, ...
{
private readonly string _value;
public NonEmptyString(string value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (value.Length == 0)
{
throw NewStringIsEmptyException("value");
}
_value = value;
}
public string Value
{
get { return _value; }
}
...
}
public class NonWhiteSpaceString : NonEmptyString
{
....
}
Sure, passing around these instances does not prevent you from having to check if they are null themselves, but it's got some big advantages:
You don't have to check on empty or white-space strings over and over again, which can be error prone in situations where the string is passed around a lot.
As I have done in my implementation, checking for null is something different than checking for an empty value (or whitespace value), because you want to throw a specific ArgumentNullException in the former case, and some ArgumentException in the second.
It clearly signals the constraint on the value of the string, just like any wrapping class is supposed to do. In fact, if you have a string that has any constraints and it is passed around a lot, I always recommend to wrap it in a class that encapsulates the check and keeps the rest of the code out of trouble. A good example of this are strings that must satisfy a certain regular expression. However, I'm diverting from the question here...

See also C#: How to Implement and use a NotNull and CanBeNull attribute for more information on Code Contracts, how they can be implemented today in VS2008, and how they will be integrated into VS2010.

Related

Why method should be converted to a property?

I'm creating a method named Check_Finished() but the visual studio won't allow me to do so. Instead, it prompts me as potential fix to convert it into a property. I can't understand why can't we use a method instead of the property here, provided that both have the same purpose and both are gonna return the same thing.
enter image description here
This(below) is the code I want to use.
public bool Check_Finished()
{
if(started && !running)
{
return true;
}
}
This is the one visual studio prompts me to convert to:
public bool Check_Finished
{
get
{
if (started && !running)
{
return true;
}
}
}
which still isn't working. Here this happens:
enter image description here
I can do the following and it works but I wanted to try a different approach just to understand things more.
public bool Finished
{
get { return started && !running; }
}
Sure, you can use a method, but all code paths need to return a value. What if the condition (if-statement) doesn't pass? What should be returned? You don't specify it, leading to a case where no return value is given, which causes the compiler error.
But in general, for such a case, you should prefer using a property, as it represents data and no special calculations have to be done in order to return the value (this wording is not necessarily the rule, but it is easy to "remember" what to use with this mnemonic, though you will get a feeling for that with more experience). Take a look at the MSDN guideline for using properties or methods:
In general, methods represent actions and properties represent data. Properties are meant to be used like fields, meaning that properties should not be computationally complex or produce side effects. When it does not violate the following guidelines, consider using a property, rather than a method, because less experienced developers find properties easier to use.

Is there a way to get the name of the function argument (not the parameter)?

I am I am using C# 7+, and I am aware of the [CallerMemberName] attribute, but what I am looking for is an attribute that would get me the name of an argument.
Use case: Checking for null, even with the ?? and ? null operators, can be a bit tedious with the condition checks and throwing the proper exceptions with the proper values. For a few months now I've been using a solution inspired by some article I read and that could be described as an "argument validation builder". It would be used something like this:
public class MyClass
{
public void DoTheThing(IFoo foo, ICollection<IBar> bars, string specialText)
{
new ArgumentValidator()
.NotNull(foo, nameof(foo))
.NotNullOrEmpty(bars, nameof(bars))
.NotNullOrEmpty(specialText, nameof(specialText));
...rest of function
}
}
If, for example, foo was null, then ArgumentValidator.NotNull(...) would throw a new ArgumentNullException with the parameter name "foo". This approach makes argument checking a bit more concise, and that's pretty much the only reason I'm doing this.
It would be really nice if I didn't have to specify nameof(...) every single time. That is, I'd like to be able to do this:
new ArgumentValidator()
.NotNull(foo)
.NotNullOrEmpty(bars)
.NotNullOrEmpty(specialText);
In order to do that though, I would need to figure how to make the NotNull(...) and other functions figure out the name of the argument.
I've tried making a parameter-based attribute, I've tried looking at Environment.StackTrace (not thrilled about trying to parse that nor about the performance implications), I've looked at StackFrame, I've looked at getting type info about the class -> method info -> parameter info and the custom attributes, and I still haven't found a way forward.
I'd like to make an attribute similar to [CallerMemberName], but this attribute would extract the name of the argument that was used to call the function, assign it to the decorated parameter, and would performs quickly (in other words, I want to avoid stack trace stuff if possible, especially since I'm using these checks a lot).
This is where I'm at:
[AttributeUsage( AttributeTargets.Parameter )]
class ArgumentNameAttribute : Attribute
{
public string SomeProperty { get; set; }
}
class Program
{
static void NotNull<T>( T argument, [ArgumentNameAttribute] string argumentName )
{
//how to get at the argumentName?
}
static void DoTheThing( string thing )
{
NotNull( thing );
Console.WriteLine( "hello world" );
}
static void Main( string[] args )
{
DoTheThing( "12345" );
}
}
Alternately, I'll accept another solution that makes argument checking concise and expressive.
Ideas?
No one has created an answer yet, but comments have mentioned alternatives:
Aspect Oriented Programming (AOP)
Use C# 8's nullable reference type syntax
While not answering the specific question, these did answer the general intent of a cleaner way to handle null types. Considering my question answered.

In C#, should one check references passed to methods against null?

Well, a few months ago I asked a similar question about C and C++, but I've been paying more attention to C# lately due to the whole "Windows Phone" thing.
So, in C#, should one bother to check against NULL at method boundaries? I think this is different than in C and C++, because in C# one generally can determine whether a given reference is valid -- the compiler will prevent one from passing uninitialized references anywhere, and therefore the only remaining possible mistake is for it to be null. Furthermore, there's a specific exception defined inside the .NET Framework for these things, the ArgumentNullException, which seems to codify what programmers think they should be getting when an invalid null was passed.
My personal opinion is once again that a caller doing this is broken, and that said caller should have NREs thrown at them until the end of days. However, I'm much less sure about this than I am in native code land -- C# has quite a different programming style in places compared to either C or C++ in this regard.
So... should you check for null parameters in C# methods?
Yes, check for them. Preferably use Code Contracts to tell the caller that you require non-null parameters
void Foo(Bar bar) {
Contract.Requires(bar != null);
}
This is particularly advantageous since the client can see exactly what is required of parameters.
If you can't use Code Contracts, use a guard clause
void Foo(Bar bar) {
Guard.Against<ArgumentNullException>(bar == null);
}
Fail fast.
I think it's better to throw an ArgumentNullException (or use a contract as Jason suggests) if your method doesn't want a particular parameter to be null. It's a much better indicator by the contract to the client not to pass null in the first place when calling your method.
Null-checking is then the client's responsibility which makes for more maintainable code on both sides (often a win-win situation)... at least that's what I feel.
It is a good practice to validate all the parameters at least in public methods. This helps to locate bugs faster and also helps while reading the code, as it describes method's contract.
We implemented a static class AssertUtilities that has a bunch of method for parameters and state validation. I believe some people call such classes Guard.
For example:
public static void ArgumentNotNull(object argument, string argumentName)
{
if (argument == null)
throw new ArgumentNullException(argumentName);
}
public static void ArgumentInRange(decimal argument, decimal minValue, decimal maxValue, string argumentName)
{
if (argument < minValue || argument > maxValue)
{
throw new ArgumentOutOfRangeException(
argumentName,
FormatUtilities.Format("Argument out of range: {0}. Must be between {1} and {2}.", argument, minValue, maxValue));
}
}
public static void ArgumentState(bool expression, string argumentName, string formatText, params object[] args)
{
if (!expression)
throw new ArgumentException(FormatUtilities.Format(formatText, args), argumentName);
}
public static void ArgumentHasText(string argument, string argumentName)
{
ArgumentNotNull(argument, argumentName);
ArgumentState(argument.Length > 0, argumentName, "Argument cannot be an empty string.");
}
So... should you check for null parameters in C# methods?
Yes, unless of course when null is permitted.
A better perspective: You should always check for valid parameter values. Sometimes a reference is allowed to be null, sometimes an int must be >= 0 or a string may not be NullOrWhiteSpace.
So it is a good practice to start every method with a parameter validation block.
From there on there are a few choices. Validation on internal/private methods is usually considered less critical, and for performance reasons it can be made conditional (or even left out).
Validation at a boundary is usually left on in Release builds. There is very little reason to ever turn it off.
Most projects will use some helper classes for validation, to minimize repetitive coding inside the methods. A very good but not yet very popular toolkit is the built-in System.Diagnostics.Contracts class. The Code-Contracts tools have many settings concerning parameter validation.

C# - Methods for null checking

What's the preferred way of checking if the value is null?
Let's say we have some entity, which has properties, which can be null (some of them or all of them).
And I wish to check this in runtime, if some property is actually null or not.
Would you use simple Entity.Property != null check in this case or would you implement a specific method, let's say like
bool HasProperty() {
return Property != null;
}
What would you choose and why?
For property values which can be null, my preference is to do the following
Have the property containing the value which can possibly be null
Have another property prefixed with Has and the rest containing the original property name which determines if the other property is non-null
Add an assert into the original property if it's accessed when null
In this example it would be
SomeType Property {
get {
Contract.Requires(HasProperty);
return _property; }
}
bool HasProperty {
get { return _property != null; }
}
The reasoning behind this is that C# does not have a standard way of describing whether or not a value can be null. There are many different conventions and techniques avalaible but simply no standard. And not understanding the null semantics around a value leads to missed null checks and eventually NullReferenceExceptions.
I've found the best way to express this is to make the null feature of a property explicit in the type itself by adding the Has property if and only if the property can be null. It's not a perfect solution but I've found it works well in large projects.
Other solutions I've tried
Do Nothing: This just fails over and over again
Using an explicit Maybe<T> or Option<T> type in the flavor of F#. This works but I find I receive a lot of push-back from developers who've never done functional programming and it leads to a rejection of the idea entirely in favor of #1.
Just check if the property itself is null, there is no need to create a method for this. Properties are really just methods that are generated by the compiler.
There is no pattern that covers this. In fact, anything you do to try and make this "easier" could be considered an anti-pattern.
"Hey, don't check if the property is null, use the Is[Property Name]Null property"
Uh, no.
I check only against null, because every nullable type does internally exactly what you described (but the internal method is called HasValue instead of HasProperty):
http://msdn.microsoft.com/de-de/library/b3h38hb0.aspx
If Property is something that isn't public, then you would need a method like HasProperty(). Also, if you implement your "nullness" in another way, it would also be good to have a HasProperty() method.
Null is not necessarily bad. I think it all depends on why you need to check for null to determine how you should check for it.
I would choose to write a separate Has* property only if the property is auto-initializing (i.e. just getting it might cause, say, an empty collection to be allocated) and it makes a performance difference. If getting the property is cheap (as it should be; in some cases you just can't help having it make a difference, though), there's no need for a superfluous Has method.
So no Has for the general case:
public string Foo { get; set; }
But in some cases, it can be a good idea:
private List<string> someStrings = null;
public List<string> SomeStrings {
get {
if (someStrings == null)
someStrings = new List<string>();
return someStrings;
}
}
public bool HasSomeStrings {
get { return (someStrings != null && someStrings.Count > 0); }
}

When to check for nulls

This is kinda an open ended question but I'm trying to sharpen my skills with good practices in exception handling specifically when to check for nulls in general.
I know mostly when to check for nulls but I have to say half the time I don't and that's bothering to me. I know ints cannot be set to null unless you use a nullable int. I know strings can be set to null OR empty hence you can check for IsNullOrEmpty.
Obviously in constructors you want to add your explicit checks there also. That's a given. And that I think you should check for null anytime you're passing in an array, generic object, or other objects into a method that can be set to null basically right?
But there is more here to exception handling. For instance I don't know when to always check and throw a null ref exception explicitely in code. If I've got incoming params, usually it's pretty straight forward but there are always cases where I ask myself, is an explicit null throw needed?
I don't really have specific examples but wondering if there's a good reference out there that really talks about exception handling in reference to when to throw them (inside methods, classes, you name it).
You shouldn't throw NullReferenceException. If it is an argument that is null throw ArgumentNullException instead.
I prefer to check for null for all reference types parameters of public/protected methods. For private methods, you may omit the check if you're sure all calls will always have valid data.
Unless you're using Code Contracts, I'd say it's good practice to check arguments for any public/protected member - as well as explicitly documenting whether they can or can't be null. For private/internal methods it becomes a matter of verifying your own code rather than someone else's... it's a judgement call at that point.
I sometimes use a helper extension method for this, so I can write:
public void Foo(string x, string y, string z)
{
x.ThrowIfNull("x");
y.ThrowIfNull("y");
// Don't check z - it's allowed to be null
// Method body here
}
ThrowIfNull will throw an ArgumentNullException with the appropriate name.
By checking explicitly before you make any other calls, you know that if an exception is thrown, nothing else will have happened so you won't have corrupted state.
I admit I'll omit such checks where I know for certain that the first call will do the same checks - e.g. if it's one overload piggybacking onto another.
With Code Contracts, I'd write:
public void Foo(string x, string y, string z)
{
Contract.Requires(x != null);
Contract.Requires(y != null);
// Rest of method here
}
This will throw a ContractException instead of ArgumentNullException, but all the information is still present and no-one should be catching ArgumentNullException explicitly anyway (other than possibly to cope with third party badness).
Of course the decision of whether you should allow null values is an entirely different matter. That depends entirely on the situation. Preventing nulls from ever entering your world does make some things easier, but at the same time nulls can be useful in their own right.
My rules of thumb for when to check for nulls are:
Always check the arguments passed to a public/protected method of any class.
Always check the arguments to constructors and initialize methods.
Always check the arguments in an indexer or property setter.
Always check the arguments to methods that are interface implementations.
With multiple overloads, try to put all argument preconditions in a single method that other overloads delegate to.
Early notification of null arguments (closer to the point of error) are much better than random NullReferenceExceptions that occur far from the point of the error.
You can use utility methods to clean up the typical if( arg == null ) throw new ArgumentNullException(...); constructs. You may also want to look into code contracts in C# 4.0 as a way to improve your code. Code contracts perform both static and runtime checks which can help identify problems even at compile time.
In general, writing preconditions for methods is a time consuming (and therefore often omitted) practice. However, the benefit to this type of defensive coding is in the hours of potentially saved time debugging red herrings that occur because you didn't validate your inputs.
As a side note, ReSharper is a good tool for identifying potential access to arguments or local members that may be null at runtime.
The earlier the better. The sooner you catch the (invalid) null, the less likely you'll be throwing out in the middle of some critical process. One other thing to consider is using your properties (setters) to centralize your validation. Often I reference my properties in the constructor, so I get good reuse on that validation.
class A
{
private string _Name
public string Name
{
get { return _Name; }
set
{
if (value == null)
throw new ArgumentNullException("Name");
_Name = value;
}
}
public A(string name)
{
//Note the use of property with built in validation
Name = name;
}
}
Depends on your type of method/api/library/framework. I think its ok for private methods that they dont check for null values unless they are kind of assertion methods.
If you programm defensive and litter your code with "not null"-tests or "if"-statements your code will be unreadable.
Define the areas where a client can mess up your code by submitting wrong/empty/null arguments. If you know where, you can draw the line where to do your null checks. Do it at your api entry points just like the security works in real life.
Imagine you would be bothered every minute to show your ticket in a cinema every movie would suck.
I prefer using static template methods for checking input constraints. the general format for this would be something like:
static class Check {
public static T NotNull(T arg) {
if( arg == null ) throw new ArgumentNullException();
}
}
The benefit to using this is that your method or constructor can now wrap the first use of the argument with Check.NotNull() as exampled here:
this.instanceMember = Check.NotNull(myArgument);
When I get to .Net 4, I'll likely convert to code contracts, but until then this works. BTW, You can find a more complete definition of the Check class I use at the following url:
http://csharptest.net/browse/src/Shared/Check.cs

Categories