Break Statements helps reduce Production Risk
This code insight counts one violation each time a loop with a else clause do not contains any break or return statement. baddef contains_magic_number(list, magic_number):
for i in list:
if i == magic_number:
print "This list contains the magic number."
else:
print "This list does NOT contain the magic number."
good
def contains_magic_number(list, magic_number):
for i in list:
if i == magic_number:
print "This list contains the magic number."
break # added break statement here
else:
print "This list does NOT contain the magic number."
Why you should care
Theelse clause of a loop is executed when the loop sequence is empty. When a loop specifies no break statement, the elseclause will always execute, because the loop sequence will eventually always become empty. Sometimes this is the intended behavior, in which case you can ignore this error. But most times this is not the intended behavior, and you should therefore review the code in question.
Business Impacts
[nz_btn text="Production Risk" target="_self" animate="false" animation_type="ghost" color="pink" size="small" shape="rounded" type="normal" hover_normal="opacity" hover_ghost="fill" link="http://casthighlight.wpengine.com/category/product/indicators-methodology/innovation/" icon="icon-office"]CAST recommendations
References
https://www.quantifiedcode.com/knowledge-base/correctness/%60else%60%20clause%20on%20a%20loop%20without%20a%20%60break%60%20statement/4aqWoDeYAbout CAST and Highlight’s Code Insights
Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.
For reference only. For the complete details please refer the original article
https://doc.casthighlight.com/alt_suspiciousloop-avoid-else-clause-on-loop-without-a-break-statement/
https://doc.casthighlight.com/alt_suspiciousloop-avoid-else-clause-on-loop-without-a-break-statement/
Comments