Rule Definition
When an if statement is followed by one or more else if statements then the final else if, shall be followed by an else statement. In the case of a simple if statement the else statement need not be included. The final else statement, which should either take appropriate action or contain a suitable comment as to why no action is taken, is defensive programming.
Remediation
Ensure logical completeness by using else block at the end of "if...else if" contruct
Violation Code Sample
using System;
public class Klass {
public void func1() {}
public void func2() {}
public void Run() {
int val = -1;
if (val < 0)
{
func1();
}
else if (val > 0) // violation: no else statement
{
func2();
}
}
}
Fixed Code Sample
using System;
public class Klass {
public void func1() {}
public void func2() {}
public void Run() {
int val = -1;
if (val < 0)
{
func1();
}
else if (val > 0)
{
func2();
}
else
{
Console.Write("Nothing done");
}
}
}
Related Technologies
Technical Criterion
CWE-478 - Missing Default Case in Switch Statement
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.