Sonarqube - 扩展嵌套的三元运算符

Sonarqube - extend the nested ternary operators

我闻到这个表达式的代码味道:

return url == null ? View("Demo") : View(!string.IsNullOrEmpty(url) ? (object)url: null);

我如何扩展此三元运算符以避免非投诉编码标准(Sonar cube 将其检测为主要代码 smell/non-compliant)?

对于每条规则,SonarQube 都提供了合规和不合规解决方案的说明和示例。对于此特定规则,它 says:

Just because you can do something, doesn’t mean you should, and that’s the case with nested ternary operations. Nesting ternary operators results in the kind of code that may seem clear as day when you write it, but six months later will leave maintainers (or worse - future you) scratching their heads and cursing.

Instead, err on the side of clarity, and use another line to express the nested operation as a separate statement.

Noncompliant Code Example

public string GetReadableStatus(Job j)
{
 return j.IsRunning ? "Running" : j.HasErrors ? "Failed" : "Succeeded";  // Noncompliant
}

Compliant Solution

public string GetReadableStatus(Job j)
{
 if (j.IsRunning)
 {
   return "Running";
 }
 return j.HasErrors ? "Failed" : "Succeeded";
}

在您的特定示例中,将被制作为:

if (url == null) {
 return View("Demo");
}
return View(!string.IsNullOrEmpty(url) ? (object)url: null);

不过,我会考虑在 switch 声明中改写所有这些内容;这可能更容易阅读和维护,例如:

switch(url) {
 case null:
  return View("Demo");
 case "":
  return View(null);
 default:
  return View(url);
}