Skip to main content

Maximum Nesting Level (MNL)

v1.0.0
short name: MNL
effort: 10m
default threshold: 5

Maximum nesting level is a quantitative metric that measures the maximum number of nested blocks that are present in a function/method. Code with high nesting level is often hard to read and maintain.

The blocks of if, else, if else, do, while, for, try, catch, finally, case, etc. affect the metric value.

The base nesting level of a function/method/constructor is 0.

Why Be Cautious

High nesting levels can lead to:

  • Reduced Readability: Deeply nested code is harder to understand and follow.
  • Increased Complexity: More layers of logic increase the chance of errors.

How to Address High Nesting Level?

First, review the code for potential simplifications. For example, checking if a collection is not empty and then iterating over the elements of that collection is unnecessary since the for-loop won't execute if there are no elements:

// Unnecessary, since the for-loop will only be executed if there is at least one element
if (list.isNotEmpty) {
for (final item in list) {
...
}
}

If you have nested if statements or collection elements, consider merging them into one statement/collection element:

if (someCondition) {
// Can be merged into one if statement
if (anotherCondition) {
...
}
}

Next, using early returns can help in some cases:

// Can be replaced with an early return
if (someCondition) {
...

if (anotherCondition) {
...
}
}

And last but not least, consider breaking down large functions/methods into smaller ones.

Config Example

analysis_options.yaml
dcm:
metrics:
maximum-nesting-level:
threshold: 5

To set multiple threshold or other common config options, refer to the Configuring Metrics page.

Example

info

To view what contributes to the metric value, generate an HTML report.

❌ Bad: High Nesting Level

// MNL: 5
void processOrder(Order order) {
if (order.isPaid) {
if (order.hasStock) {
if (order.items.isNotEmpty) {
for (final item in order.items) {
if (item.isAvailable) {
item.ship();
} else {
print('Item not available');
}
}
}
} else {
print('Order is out of stock');
}
} else {
print('Payment is pending');
}
}

✅ Good: Low Nesting Level

// MNL: 2
void processOrder(Order order) {
// Uses early return
if (!order.isPaid) {
print('Payment is pending');
return;
}

if (!order.hasStock) {
print('Order is out of stock');
return;
}

// No longer has a check for isNotEmpty
for (var item in order.items) {
if (item.isAvailable) {
item.ship();
} else {
print('Item not available');
}
}
}