我们的SonarQube经常在我们的代码上引发以下问题(Code Smell):"ArgumentException中使用的参数名称应该与现有的名称相匹配".以下是触发此问题的规则.
触发此问题的示例如下:
private void Validate(SaveCommand command)
{
if(string.IsNullOrEmpty(command.UserCode))
throw new ArgumentNullException(nameof(command.UserCode));
....
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:我如何正确地重构代码以遵守SonarQube(和MSDN)指南?
或者我应该保持这样.如果是这样,为什么?
我认为SonarQube就在这里:没有参数命名UserCode,因此你不应该将它指定为ArgumentNullException构造函数的参数.我会避免使用ArgumentNullException在所有在这里,作为参数不为空-否则会被扔NullReferenceException在command.UserCode.
相反,只需使用ArgumentException描述性消息,例如
throw new ArgumentException(
$"{nameof(command.UserCode)} property cannot be null or empty",
nameof(command));
Run Code Online (Sandbox Code Playgroud)
现在我们可以判断哪个参数不正确(command)以及如何(其UserCodeproeprty为null或为空).SonarQube应该没问题,它更准确地符合IMO的异常类型的含义.