-
Notifications
You must be signed in to change notification settings - Fork 79
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[ISSUE 142] new python rule : AvoidMultipleIfElseStatement
- Loading branch information
Showing
2 changed files
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -31,6 +31,7 @@ if ($nb == 0) { | |
} else { | ||
$nb = -1; | ||
} | ||
return $nb; | ||
``` | ||
|
||
## Compliant Code Example | ||
|
54 changes: 54 additions & 0 deletions
54
ecocode-rules-specifications/src/main/rules/EC2/python/EC2.asciidoc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 MATCHS-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 | ||
``` |