Home > front end >  Sonarqube - extend the nested ternary operators
Sonarqube - extend the nested ternary operators

Time:10-20

I am getting a code smell for this expression:

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

How can I extend this ternary operators to avoid non-complaint coding standard (Sonar cube detected this as a Major code smell/non-compliant) ?

CodePudding user response:

For every rule SonarQube provides a description and an example of compliant and non-compliant solution. For this specific rule it 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";
}

In your particular example that would be made as:

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

I would consider however rephrasing all of that in a switch statement; this might be easier to read and maintain, e.g.:

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