Rules / deep-nesting
Deeply nested IF in PLC code: how to simplify it
More than four levels of nested IF are hard to read and easy to get wrong. Early exits, combined conditions and moving inner levels into a separate block help.
Severity: Minor
Rule id: deep-nesting
Deep IF nesting
What the rule checks
Deeply nested IFs are hard to read and easy to get wrong. A sign the block should be simplified (early exits, guards) or part of it extracted into a separate FB/method.
What it does to the plant
A mistake in a permissive condition slips through review because the branches do not fit on one screen.
Example
PROGRAM PermitVAR xA, xB, xC, xD, xE, xRun : BOOL;END_VARIF xA THEN IF xB THEN IF xC THEN IF xD THEN IF xE THEN xRun := TRUE; END_IF END_IF END_IF END_IFEND_IF
PROGRAM PermitVAR xA, xB, xC, xD, xE, xRun : BOOL;END_VARxRun := xA AND xB AND xC AND xD AND xE;
Both listings are run through the linter by an automated test: the rule fires on the first and stays silent on the second.
How to fix
- Invert the conditions and use early exits (
RETURN/CONTINUE) instead of nesting. - Extract the inner levels into a separate FUNCTION_BLOCK or method.
Upload a PLCopen XML or CODESYS .export file: the report is free and the code is not stored.
The same linter without uploading a file: command line and GitHub Action.
Related rules
2026-11-26