在 ArgumentException 中使用参数的 属性
Using a parameter's property in an ArgumentException
我们的 SonarQube 经常在我们的代码中引发以下问题(代码异味):"Parameter names used into ArgumentException should match an existing one"。 Here 是触发此问题的规则。
触发此问题的示例如下:
private void Validate(SaveCommand command)
{
if(string.IsNullOrEmpty(command.UserCode))
throw new ArgumentNullException(nameof(command.UserCode));
....
}
我的问题是:如何正确重构代码以遵守 SonarQube(和 MSDN)准则?
或者我应该保持这样。如果是,为什么?
我认为 SonarQube 恰到好处:没有名为 UserCode
的参数,因此您不应将其指定为 ArgumentNullException
构造函数的参数。我会在这里完全避免使用 ArgumentNullException
,因为 参数 不为空 - 否则它会在 command.UserCode
处抛出 NullReferenceException
。
相反,只需使用 ArgumentException
和描述性消息,例如
throw new ArgumentException(
$"{nameof(command.UserCode)} property cannot be null or empty",
nameof(command));
现在我们可以判断哪个参数不正确 (command
) 以及如何(其 UserCode
属性为 null 或空)。 SonarQube 应该没问题,它更准确地符合异常类型的含义 IMO。
我们的 SonarQube 经常在我们的代码中引发以下问题(代码异味):"Parameter names used into ArgumentException should match an existing one"。 Here 是触发此问题的规则。
触发此问题的示例如下:
private void Validate(SaveCommand command)
{
if(string.IsNullOrEmpty(command.UserCode))
throw new ArgumentNullException(nameof(command.UserCode));
....
}
我的问题是:如何正确重构代码以遵守 SonarQube(和 MSDN)准则?
或者我应该保持这样。如果是,为什么?
我认为 SonarQube 恰到好处:没有名为 UserCode
的参数,因此您不应将其指定为 ArgumentNullException
构造函数的参数。我会在这里完全避免使用 ArgumentNullException
,因为 参数 不为空 - 否则它会在 command.UserCode
处抛出 NullReferenceException
。
相反,只需使用 ArgumentException
和描述性消息,例如
throw new ArgumentException(
$"{nameof(command.UserCode)} property cannot be null or empty",
nameof(command));
现在我们可以判断哪个参数不正确 (command
) 以及如何(其 UserCode
属性为 null 或空)。 SonarQube 应该没问题,它更准确地符合异常类型的含义 IMO。