diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a0f9bc..06bb69a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - [#123](https://github.com/green-code-initiative/ecoCode/issues/123) Improve unit tests for EC7 rule - Update ecocode-rules-specifications to 1.4.6 - README.md upgrade : docker test environment +- [#10](https://github.com/green-code-initiative/ecoCode-python/issues/10) Correction of NullPointException in EC2 rule ### Deleted diff --git a/src/main/java/fr/greencodeinitiative/python/checks/AvoidMultipleIfElseStatementCheck.java b/src/main/java/fr/greencodeinitiative/python/checks/AvoidMultipleIfElseStatementCheck.java index b625257..33f799a 100644 --- a/src/main/java/fr/greencodeinitiative/python/checks/AvoidMultipleIfElseStatementCheck.java +++ b/src/main/java/fr/greencodeinitiative/python/checks/AvoidMultipleIfElseStatementCheck.java @@ -246,7 +246,13 @@ private void visitElseNode(SubscriptionContext context, ElseClause pElseTree, in */ private void computeElseVariables(SubscriptionContext context, ElseClause pElseTree, int pLevel) { - for (Map.Entry entry : variablesStruct.getVariablesForCurrentIfStruct(pLevel).entrySet()) { + Map mapVariables = variablesStruct.getVariablesForCurrentIfStruct(pLevel); + + // specific use case : if there is no variables used in any conditions of IF / ELSEIF structures, + // we could have a NullPointerException if we don't check this case + if (mapVariables == null || mapVariables.isEmpty()) { return; } + + for (Map.Entry entry : mapVariables.entrySet()) { String variableName = entry.getKey(); // increment usage of all variables in the same level of ELSE staetement diff --git a/src/test/resources/checks/avoidMultipleIfElseStatementCompliant.py b/src/test/resources/checks/avoidMultipleIfElseStatementCompliant.py index 9a2c613..b5fdcb4 100644 --- a/src/test/resources/checks/avoidMultipleIfElseStatementCompliant.py +++ b/src/test/resources/checks/avoidMultipleIfElseStatementCompliant.py @@ -136,3 +136,19 @@ def compliant_variables_used_max_twice_in_if_orelif_statements_scenario_2(): else: nb2 = 3 return nb2 + +# COMPLIANT +# USE CASE (secondary) : check no NullPointerException if no variables really used in conditions +# USE CASE : compliant use case to check if following is OK : +# - more than twice uses of the same variable +# - BUT not directly used, only inside a function +def compliant_the_same_variable_is_used_more_than_twice_but_inside_functions(): + nb1 = 3 + nb2 = 10 + if len(nb1) == 1: + nb2 = 1 + elif len(nb1) == 3: + nb2 = 2 + else: + nb2 = 4 + return nb2 \ No newline at end of file