Is there a better way to require that an argument is not null in a method? I keep checking if any of the arguments that my method requires are null, as show below. But I'm wondering if there is a better way.
public void MyMethod(string a, int b)
{
if(a==null){throw new ArgumentNullException("a");}
if(b==null){throw new ArgumentNullException("b");}
//more stuff here
}
The @NotNull annotation is, actually, an explicit contract declaring that: A method should not return null. Variables (fields, local variables, and parameters) cannot hold a null value.
The nonNull method is a static method of the Objects class in Java that checks whether the input object reference supplied to it is non-null or not. If the passed object is non-null, then the method returns true. If the passed object is null , then the method returns false.
Annotation Type NonNullA common Spring annotation to declare that annotated elements cannot be null . Leverages JSR-305 meta-annotations to indicate nullability in Java to common tools with JSR-305 support and used by Kotlin to infer nullability of Spring API.
NullPointerException will be thrown with 'field name is marked non-null but is null' as the exception message.
Rick Brewster (author of Paint.NET) blogged about a Fluent API alternative:
http://blog.getpaint.net/2008/12/06/a-fluent-approach-to-c-parameter-validation/
You can write some utility methods. This is the common pattern in java.
user code:
public void MyMethod(string a, int b)
{
//validate each
Objects.RequireNotNull(a);
Objects.RequireNotNull(b);
//or validate in single line as array
Objects.RequireNotNullArray(a, b);
}
implementation code:
public static class Objects
{
public static T RequireNotNull<T>(T arg)
{
if(arg == null)
{
throw new ArgumentNullException();
}
return arg;
}
public static object[] RequireNotNullArray(params object[] args)
{
return RequireNotNullArray<object>(args);
}
public static T[] RequireNotNullArray<T>(params T[] args)
{
Objects.RequireNotNull(args);
for(int i=0; i<args.Length; i++)
{
T arg = args[i];
if(arg == null)
{
throw new ArgumentNullException($"null entry at position:{i}");
}
}
return args;
}
}
You cannot get the variable name in the exception. but with the stack trace and your source code, it should be possible to easily track down.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With