Avoid long ‘if/else if’ chains that could be replaced by a ‘switch’ statement

Why you should care

For code readability purpose, prefer using switch if there are three or more options in a if.

How we detect

CAST Highlight counts one occurrence each time a elseif chain is managing 3 or more conditions. That is, each time an elseif chain contains 2 “else if” or more.

Example

def iconstNode(value: Int) {
// FIRST OPTION
if (value >= -1 && value <= 5) {
InsnNode(Opcodes.ICONST_0 + value)
}
// SECOND OPTION
else if (value >= java.lang.Byte.MIN_VALUE && value <= java.lang.Byte.MAX_VALUE) {
IntInsnNode(Opcodes.BIPUSH, value)
}
// THIRD OPTION ==> +1 VIOLATION !!!!!
else if (value >= java.lang.Short.MIN_VALUE && value <= java.lang.Short.MAX_VALUE) {
IntInsnNode(Opcodes.SIPUSH, value)
}
else {
LdcInsnNode(Integer(value))
}
}

References

5362

About 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.