Minor
Boolean checks should not be inverted
Description
The rule "Boolean checks should not be inverted" means that when writing code for SQL Server, boolean checks should not be written in a way that inverts the logic of the check. For example, a check for a value less than 10 should not be written as "value greater than or equal to 10". This is because inverting the logic of the check can cause confusion and make the code harder to read and understand. Additionally, it can lead to errors in the code and can be difficult to debug. Therefore, it is best practice to write boolean checks in the most straightforward way.
Key Benefits
- Avoiding logic errors: By not inverting boolean checks, logic errors can be avoided that can lead to unexpected behavior.
- Easier to read: Non-inverted boolean checks are easier to read and understand, reducing the need for debugging.
- More efficient code: By not inverting boolean checks, code can be more efficient, resulting in faster performance.
Non-compliant Code Example
DECLARE @Number int= 50; IF NOT(@Number >= 100) --Non compliant code (Boolean check is inverted) BEGIN Select * From Employee Where id < @Number; PRINT 'The number is less then 100.'; END; ELSE BEGIN IF NOT (@Number <= 100) --Non compliant code (Boolean check is inverted) BEGIN Select * From Employee Where id < @Number; PRINT 'The number is greater then 100.'; END; ELSE PRINT 'The number is equal to 100.'; END ; GO
Compliant Code Example
DECLARE @Number int= 50; IF @Number < 100 --Compliant code BEGIN Select * From Employee Where id < @Number; PRINT 'The number is less then 100.'; END; ELSE BEGIN IF @Number > 100 --Compliant code BEGIN Select * From Employee Where id < @Number; PRINT 'The number is greater then 100.'; END; ELSE PRINT 'The number is equal to 100.'; END ; GO