0

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?

Thomas Flinkow
  • 4,845
  • 5
  • 29
  • 65
  • 2
    Is it *exceptional* that its `null` (or white space)? if it is, throw. if its not exceptional, then deal with it in another way. The only rule here is don't use exceptions for *flow control*. – TheGeneral Jul 09 '20 at 06:55
  • 1
    I'd argue like this: If the parameter here is `null` it seems to be a programming error that should be made aware of early on (during development / testing). So, I'd do one of two things: a) add a `Debug.Assert` or b) throw an `ArgumentNullException`. If the premise does not hold (coding error if `null`) then this argument is invalid, of course. – Fildor Jul 09 '20 at 07:00

1 Answers1

3

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.

Henk van Boeijen
  • 7,357
  • 6
  • 32
  • 42