When the same code is duplicated in two or more separate branches of a conditional, it can make the code harder to understand, maintain, and can
potentially introduce bugs if one instance of the code is changed but others are not.
Having two branches in an IF
/ELSE IF
chain with the same implementation is at best duplicate code, and at worst a coding
error.
IF @SortOrder = 1
BEGIN
SET @SortOrder = 0
SELECT LastName FROM Employees ORDER BY LastName
END
ELSE IF @SortOrder = 2
BEGIN
SET @SortOrder = 0
SELECT LastName FROM Employees ORDER BY LastName -- Noncompliant
END
ELSE
BEGIN
SET @SortOrder = -1
SELECT LastName FROM Employees
END
GO
If the same logic is needed for both instances the conditions should be combined.
IF (@SortOrder = 1 OR @SortOrder = 2)
BEGIN
SET @SortOrder = 0
SELECT LastName FROM Employees ORDER BY LastName
END
ELSE
BEGIN
SET @SortOrder = -1
SELECT LastName FROM Employees
END
GO
Exceptions
Branches in an IF
/ELSE IF
chain with an implementation that contains a single line of code are ignored.
IF @SortOrder = 1
BEGIN
SELECT LastName FROM Employees ORDER BY LastName
END
ELSE IF @SortOrder = 2
BEGIN
SELECT LastName FROM Employees
END
ELSE
BEGIN
SELECT LastName FROM Employees ORDER BY LastName -- No issue, usually this is done on purpose to increase the readability
END
GO
But this exception does not apply to IF
chains without ELSE
-s when all branches have the same single line of code. In the
case of IF
chains with ELSE
-s rule S3923 raises a bug.
IF @SortOrder = 1 -- Noncompliant, this might have been done on purpose but probably not
BEGIN
SELECT LastName FROM Employees ORDER BY LastName
END
ELSE IF @SortOrder = 2
BEGIN
SELECT LastName FROM Employees ORDER BY LastName
END
GO