Reading a function that has a lot of nesting is hard. This is also known as the Bumpy Road code smell. It is often caused by many conditions or loops that are deeply nested. There are many ways to simplify such complicated code. A common one that is sometimes applicable is to Replace Nested Conditional with Guard Clauses.
Have people discuss in pairs how much levels of nesting they think is ok.
A small code to practice the Replace Nested Conditional with Guard Clauses refactoring is the PayRoll-Refactoring-Kata.
A good way to start is by asking the participants whether they see any issue with this code.
Next you want to explain what the Bumpy Road code smell is using the given code.
Then, demo the refactoring slowly and explain your thought process.
First select the
result variable to show how big its scope is and how often it is used.
Explain that it is a good idea to reduce the scope of such a variable because it reduces cognitive load and allows further refactoring.
Go on showing the refactoring by introducing early returns.
Ask the people whether they think it’s easier to read and why.
Have the participants practice the same exercise. If the group is familiar with Ensemble Programming, you might want them to do it in an ensemble first. When there is time left have them do it again in pairs.
Have the participants scan their own code for occurrences where this refactoring would apply, and have them write down the filename and line number.
Ask the participants how they did spot those places. What are the characteristics of a potential guard clause?