Skip to content

Commit 71ff8ab

Browse files
authored
Merge pull request #12 from green-code-initiative/ISSUE_10
[ISSUE 10] correction NullPointerException + add test use case
2 parents f32cc3f + bbf3479 commit 71ff8ab

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1919
- [#123](https://github.com/green-code-initiative/ecoCode/issues/123) Improve unit tests for EC7 rule
2020
- Update ecocode-rules-specifications to 1.4.6
2121
- README.md upgrade : docker test environment
22+
- [#10](https://github.com/green-code-initiative/ecoCode-python/issues/10) Correction of NullPointException in EC2 rule
2223

2324
### Deleted
2425

src/main/java/fr/greencodeinitiative/python/checks/AvoidMultipleIfElseStatementCheck.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,13 @@ private void visitElseNode(SubscriptionContext context, ElseClause pElseTree, in
246246
*/
247247
private void computeElseVariables(SubscriptionContext context, ElseClause pElseTree, int pLevel) {
248248

249-
for (Map.Entry<String, Integer> entry : variablesStruct.getVariablesForCurrentIfStruct(pLevel).entrySet()) {
249+
Map<String, Integer> mapVariables = variablesStruct.getVariablesForCurrentIfStruct(pLevel);
250+
251+
// specific use case : if there is no variables used in any conditions of IF / ELSEIF structures,
252+
// we could have a NullPointerException if we don't check this case
253+
if (mapVariables == null || mapVariables.isEmpty()) { return; }
254+
255+
for (Map.Entry<String, Integer> entry : mapVariables.entrySet()) {
250256
String variableName = entry.getKey();
251257

252258
// increment usage of all variables in the same level of ELSE staetement

src/test/resources/checks/avoidMultipleIfElseStatementCompliant.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,3 +136,19 @@ def compliant_variables_used_max_twice_in_if_orelif_statements_scenario_2():
136136
else:
137137
nb2 = 3
138138
return nb2
139+
140+
# COMPLIANT
141+
# USE CASE (secondary) : check no NullPointerException if no variables really used in conditions
142+
# USE CASE : compliant use case to check if following is OK :
143+
# - more than twice uses of the same variable
144+
# - BUT not directly used, only inside a function
145+
def compliant_the_same_variable_is_used_more_than_twice_but_inside_functions():
146+
nb1 = 3
147+
nb2 = 10
148+
if len(nb1) == 1:
149+
nb2 = 1
150+
elif len(nb1) == 3:
151+
nb2 = 2
152+
else:
153+
nb2 = 4
154+
return nb2

0 commit comments

Comments
 (0)