Modifying the scala:S126 rule or adding an "if without an else" variation

This rule exists and it seems to be a java variation of it.

This rule only flags when “if” is followed by “else if” and then has no “else”. Although, in scala, having no “else” is a BIG code smell regardless of an existence of an “else if”. Also, for many user groups the usage of “else if” is a “no go”, meaning that many codebases will end up with the original rule “never flagging” and being useless at detecting “if without and else” that they really need.

Can this rule be made editable or can you work on adding this rule to sonarcloud or letting users add it? I have the regex to detect it but am unable to add it.

Hey there.

Thanks for the report. Can you include some brief code samples demonstrating the missing cases?

Absolutely. I wrote 2 methods, both are terrible code patterns. Without going into much detail on compiler, etc.: both these 2 cases are equally wrong as the “type” can’t even be inferred by the IDE and the compiler and it ends up being AnyVal (scala version of “anything”).

Problem here, Sonar only catches and flags on the “methodB” version of the “no else” rule
(ignore the rest of the “reds” as it’s being flagged for no test coverage since I did not make tests for these methods)

Text-based code snippet please (something our devs can copy paste). :pray: Sorry for not specifying.

  def methodA(n: Int): Int = {
    val a = if (n < 3) {
      1
    }
    a match {
      case x: Int => n + x
      case _      => n
    }
  }

  def methodB(n: Int): Int = {
    val b = if (n < 3) {
      1
    } else if (n > 10) {
      n
    }
    b match {
      case x: Int => n + x
      case _      => n
    }
  }

IMO. Both of the above should flag on the rule mentioned in title. Or else, there should be a rule to flag A (B flags on scala:S126)

Hello @Valter_Fernandes,

Thank you for the report. If expressions without else are indeed a problem when the result value is not discarded. I created a ticket to fix the behavior.

Best,
Valentin

1 Like