My students often ask me “How can I tell if my code is too complex?” There are a lot of different answers to that question, but I thought I would share my favorite complexity detection tool with you – a tiny purple stuffed monkey:
The basic concept behind it all is to explain your code to your duck/monkey/other inanimate object, step by step. If it takes you longer than 1-2 minutes to explain a method, it’s probably too complex and should be refactored to something simpler.
Well that sounds great and all, but how exactly do I reduce a method’s complexity?
Good catch – “Just simplify it” is unacceptably hand-wavey and doesn’t really provide much guidance. One good approach for reducing complexity is called the Single Level of Abstraction Principle (SLAP). As might be apparent from the name, SLAP recommends that all statements within a given method exist at the same “Level of Abstraction”.