Home

Collapsible if statements should be merged

Description

    The "Collapsible if statements should be merged" rule states that when multiple if statements can be combined into a single if statement, they should be merged. This helps to make code more concise and easier to read, as well as reducing the overall complexity of the code. It also helps to avoid potential errors that can occur when multiple if statements are used. For example, if two if statements are used to check for a condition, but the first statement fails, the second statement will still be executed, even though the condition was already checked. By merging the two statements into one, this potential error can be avoided.

Key Benefits

  • Reduces Complexity: By merging if statements, code complexity can be reduced.
  • Improves Readability: Merging if statements makes code easier to read and understand.
  • Simplifies Debugging: By reducing the number of if statements, debugging can be simplified.
  • Increases Performance: Merging if statements can improve performance by reducing the number of comparisons.

 

Non-compliant Code Example

function string TestFunctionCall (string cnt)

string cnt1;

if cnt = "1" then
    if cnt1 = "2" then //Non compliant code
        messagebox('Success')

    end if
end if

return cnt

end function
function string TestFunctionCall (string cnt)

IF x > 1 THEN 
     IF x > 2 THEN //Non compliant code
	    IF x > 3 THEN //Non compliant code
		    IF x > 4 THEN //Non compliant code
			    IF x > 5 THEN //Non compliant code
				    cnt = "x > 5"
			    END IF;
            END IF;
        END IF;
     END IF;
 END IF;

return cnt

end function

Compliant Code Example

function string TestFunctionCall (string cnt)

string cnt1;

if cnt = "1" AND cnt1 = "2" then //Compliant code (Merged collapsible IF condition into one)
        messagebox('Success')
end if

return cnt

end function
function string TestFunctionCall (string cnt)

IF x > 5 THEN //Compliant code (Merged collapsible IF condition into one)
	cnt = "x > 5"
END IF;

return cnt

end function
function string TestFunctionCall2 (string cnt)

IF x > 1 AND x > 2 THEN //Compliant code
		cnt = "x > 2"
	END IF;
	IF x > 3 THEN 
		cnt = "x > 3"
        END IF;
	IF x > 4 THEN 
		cnt = "x > 4"
	END IF;
	IF x > 5 THEN 
		cnt = "x > 5"
	END IF;
 END IF;

return cnt

end function
Visual Expert 2024
 VEPBRULE53