When trying to write good code, function size is important, but there’s one thing that’s more important: function complexity. Here’s a simple function and a complex function, both five lines:
def simple_function():
do_something()
do_something_else()
also_do_another_thing()
and_another()
and_so_on()
def complex_function():
if i > j:
for k in some_list:
do_something_with_k()
else:
do_something_with_j()
This is actually measurable. We say that simple_function
has a cyclomatic complexity of 1, meaning that that there is only one path the code execution can follow. complex_function
has a cyclomatic complexity of 3.
Many people think that a function’s complexity shouldn’t exceed 10. I think this is actually too much and 3 to 5 is better. However, 10 is already a vast improvement over much existing code. You don’t need to count paths or install a complexity measurement tool—just keep your functions from becoming complex. I know it sounds easier than it is, but for the time being I’m just presenting the theory.