# Design rule of thumb: 1 loop per method

Here’s a great little guideline for writing testable code: limit the number of loops in any function or method to 1 at each level of nesting.

Consider the following function with two “top level” loops:

def function():
for ():
....
....
....
for ():
....
....
....


## Refactor 1

The body of a loop is often a great candidate for a refactoring. Do this instead:


def helper1():
for():
...
...
...

def helper2():
for():
...
...
...

def function():
helper1()
helper2()


Instead of sweating one nasty integration test for the function with two loops, you now have two unit tests (test_helper1, test_helper2) and two integration tests (test_function1, test_function2).

## Refactor 2

def function1():
for ():
...
...
...

def function2():
for ():
...
...
...

function1()
function2()


Depending on what function1 and function2 accomplish, they might be amenable to unit testing as well.