I am currently wondering about what is "best" to do if null
is passed to the following method. Should it silently return (as it does no) or should it throw an exception instead?
public void RaisePropertyChanged(string propertyName)
{
if(propertyName is null)
{
return;
}
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
Here it says
[I]f the function's assumptions about its inputs are violated, it should throw an exception instead of returning normally
and I believe the function assumes that a non-null
input is passed to it, however, it could still execute (successfully?) as it simply does nothing if null
is passed.
Is throwing an exception instead of returning the "best" thing to do here in terms of good / clean code?
When a missing property name is considered to be a development error, then the method should throw an ArgumentNullException
. Otherwise, it's fine to silently return.
Whatever you do, a bit safer would be to test for string.IsNullOrWhiteSpace(propertyName)
. When you do this, just throw an ArgumentException
when a proper name is not provided.