【问题标题】:Using a parameter's property in an ArgumentException在 ArgumentException 中使用参数的属性
【发布时间】:2019-05-11 15:40:12
【问题描述】:

我们的 SonarQube 经常在我们的代码中引发以下问题(代码异味):“用于 ArgumentException 的参数名称应与现有名称匹配”。 Here 是触发此问题的规则。

触发此问题的示例如下:

private void Validate(SaveCommand command)
{
    if(string.IsNullOrEmpty(command.UserCode))
        throw new ArgumentNullException(nameof(command.UserCode));
    ....
}

我的问题是:我如何正确重构代码以遵守 SonarQube(和 MSDN)准则?

或者我应该保持这样的状态。如果有,为什么?

【问题讨论】:

    标签: c# sonarqube


    【解决方案1】:

    我认为 SonarQube 就在这里:没有名为 UserCode 的参数,因此您不应该将其指定为 ArgumentNullException 构造函数的参数。我会避免在这里使用 ArgumentNullException,因为 argument 不为空 - 否则它会在 command.UserCode 处抛出 NullReferenceException

    相反,只需使用带有描述性消息的ArgumentException,例如

    throw new ArgumentException(
        $"{nameof(command.UserCode)} property cannot be null or empty",
        nameof(command));
    

    现在我们可以知道哪个参数不正确(command)以及如何(它的UserCode proeprty 为空或空)。 SonarQube 应该没问题,更符合 IMO 异常类型的含义。

    【讨论】:

    • 伟大的收获! (Y)
    • 谢谢!这很有意义:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多