Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New Rule: no equal conditions in IF and CASE statements #31

Closed
silviomarghitola opened this issue Jun 3, 2019 · 2 comments · Fixed by #86
Closed

New Rule: no equal conditions in IF and CASE statements #31

silviomarghitola opened this issue Jun 3, 2019 · 2 comments · Fixed by #86
Assignees
Labels
enhancement New feature or request
Milestone

Comments

@silviomarghitola
Copy link

Language Usage / Controll Structures / CASE ...
Avoid using equal conditions in different branches of the same IF or CASE statement

@PhilippSalvisberg
Copy link
Collaborator

from SonarSource:

Related "IF/ELSIF" statements and "WHEN" clauses in a "CASE" should not have the same condition
Bug

A CASE and a chain of IF/ELSIF statements is evaluated from top to bottom. At most, only one branch will be executed: the first one with a condition that evaluates to true.

Therefore, duplicating a condition automatically leads to dead code. Usually, this is due to a copy/paste error. At best, it's simply dead code and at worst, it's a bug that is likely to induce further bugs as the code is maintained, and obviously it could lead to unexpected behavior.

Noncompliant Code Example

IF param == 1 THEN
  x := 'A';
ELSIF param == 2 THEN
  x := 'B';
ELSIF param == 1 THEN -- Noncompliant, for sure this is a bug
  x := 'C';
END IF;

result := CASE param
   WHEN 1 THEN 'A'
   WHEN 2 THEN 'B'
   WHEN 1 THEN 'C'  -- Noncompliant
   ELSE 'D'
END;

Compliant Solution

IF param == 1 THEN
  result := 'A';
ELSIF param == 2 THEN
  result := 'B';
ELSIF param == 3 THEN
  result := 'C';
END IF;

result := CASE param
   WHEN 1 THEN 'A'
   WHEN 2 THEN 'B'
   WHEN 3 THEN 'C'
   ELSE 'D'
END;

@PhilippSalvisberg PhilippSalvisberg added the enhancement New feature or request label Jun 4, 2019
@PhilippSalvisberg PhilippSalvisberg added this to the v4.0 milestone Jun 4, 2019
@PhilippSalvisberg
Copy link
Collaborator

makes sense.

@kibeha kibeha self-assigned this Sep 16, 2020
kibeha added a commit to kibeha/plsql-and-sql-coding-guidelines that referenced this issue Sep 16, 2020
…ns in different branches of the same IF or CASE statement.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants