Our SonarQube often raises the following issue (Code Smell) on our code: "Parameter names used into ArgumentException should match an existing one". Here is the rule that triggers this issue.
An example of this issue being triggered can be the following:
private void Validate(SaveCommand command)
{
if(string.IsNullOrEmpty(command.UserCode))
throw new ArgumentNullException(nameof(command.UserCode));
....
}
My question is: How do i properly refactor the code to abide by SonarQube (and MSDN) guidelines?
Or should i just keep it like this. If so, why?
I think SonarQube is spot on here: there's no parameter named UserCode
, so you shouldn't be specifying it as an argument to the ArgumentNullException
constructor. I would avoid using ArgumentNullException
at all here, as the argument isn't null - otherwise it would be throwing a NullReferenceException
at command.UserCode
.
Instead, just use ArgumentException
with a descriptive message, e.g.
throw new ArgumentException(
$"{nameof(command.UserCode)} property cannot be null or empty",
nameof(command));
Now we can tell which parameter is incorrect (command
) and how (its UserCode
proeprty is null or empty). SonarQube should be fine with this, and it meets the meaning of the exception type more accurately IMO.
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