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

[ISSUE 142] new python rule : AvoidMultipleIfElseStatement #215

Merged
merged 2 commits into from
Aug 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ if ($nb == 0) {
} else {
$nb = -1;
}
return $nb;
```

## Compliant Code Example
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
If we are using too many conditional IF, ELSEIF or ELSE statements it will impact performance.
We can think of using a switch statement instead of multiple if-else if possible, or refactor code
to reduce number of IF, ELSEIF and ELSE statements. Sometimes called "complexity cyclomatic".
MATCH-CASE statement has a performance advantage over if – else.

## Functional rules
- one variable must be used maximum twice in IF / ELSEIF / ELSE statements at the same level - WARNINGs :
- IF and ELSEIF statements use explicitly variable names !
- ELSE statements use implicity variable names !
- one variable must be used maximum twice in IF / ELSEIF / ELSE statements at differents hierarchical levels
- we can assume that if one variable is used three times or more, we should :
- use a MATCH-CASE statement instead
- or refactor the code if possible

## Non-compliant Code Example

Non-compliant, because `nb` is used 4 times :
- 2 explicit times in IF statements
- 2 implicit times in ELSE statements

```python
index = 1
nb = 2
...
if nb == 0:
nb = index
elif nb == 1:
nb = index * 2
elif nb == 2:
nb = index * 3
else:
nb = -1
return nb
```

## Compliant Code Example

MATCH-CASE statement solution + refactor solution

```python
index = 1
nb = 2
...
match nb:
case 0:
nb = index * (nb + 1)
case 1:
nb = index * (nb + 1)
case 2:
nb = index * (nb + 1)
case _:
nb = -1
return nb
```