== Why is this an issue?

Nested control flow statements ``++IF...ELSE++``, ``++WHILE++`` and ``++TRY...CATCH++`` are often key ingredients in creating
what's known as "Spaghetti code". This code smell can make your program difficult to understand and maintain.

When numerous control structures are placed inside one another, the code becomes a tangled, complex web.
This significantly reduces the code's readability and maintainability, and it also complicates the testing process.

== How to fix it

=== Code examples

The following example demonstrates the behavior of the rule with the default threshold of 4 levels of nesting:

==== Noncompliant code example

[source,sql]
----
IF @flag1 = 1 -- Compliant - depth = 1
  BEGIN
    IF @flag2 = 2 -- Compliant - depth = 2
      BEGIN
        WHILE @var1 > 0  -- Compliant - depth = 3
          BEGIN
            IF @flag3 = 3 -- Compliant - depth = 4, not exceeding the limit
              BEGIN
                IF @flag4 = 4 -- Noncompliant - depth = 5
                  BEGIN
                    IF @flag5 = 5 -- Depth = 6, exceeding the limit, but issues are only reported on depth = 5
                      BREAK
                  END
              END
            SET @var1 = @var1 - 1
          END
      END
  END
----

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

include::../message.adoc[]

=== Parameters

.max
****
_Integer_

----
4
----

Maximum allowed control flow statement nesting depth.
****


include::../highlighting.adoc[]

'''
== Comments And Links
(visible only on this page)

=== on 7 Mar 2018, 18:58:40 Ann Campbell wrote:
\[~freddy.mallet] we haven't (yet) deprecated this rule in favor of Cognitive Complexity, but do we want to continue adding new implementations?

=== on 8 Mar 2018, 08:36:40 Freddy Mallet wrote:
I would say yes [~ann.campbell.2] because for me the best way to get a massive adoption of the Cognitive Complexity metric is by not forcing anyone to use it. This rule is a good example of a basic feature that any developer not knowing the cognitive complexity metric would expect from a rule engine. And I think that would be a mistake to generate a kind of friction at the adoption of the rule engine by forcing people to "buy" the Cognitive Complexity metric. But promoting the Cognitive Complexity rule/metric in the description of this rule can be a good idea.

include::../comments-and-links.adoc[]

endif::env-github,rspecator-view[]
