Identify Paragraphs in Long Methods

Long function is a common code smell. Learning to identify paragraphs that can be extracted as methods is often a good strategy in this situation. This learning hour is about understanding concepts and people will probably not be able to use this technique fluently without a follow-up session. It is adapted from a longer session that is detailed in this repo.

Learning Goals

Session Outline

Connect - Why does code have long methods?

Ask this question and write down what they say on sticky notes on the shared whiteboard. Most developers have experience of and opinions about long methods. There are no wrong answers!

Concept - Code Paragraphs

Long methods tend to get longer, (hopefully in the Connect someone will have said this, and you can reiterate what they said). At some point the method may become so long and complex that nobody understands what it does anymore - they can’t hold in their head all that complexity at once. In this situation we need techniques that still work even when we don’t understand the code.

A Sparrow Deck is a way to train the brain to recognize patterns. If you havn’t done one before with the team, start with the original sparrow deck first. Then show the Sparrow Deck on Paragraphs.

Alternatively, if you don’t want to use these prepared materials, you could collect some of your own code samples and put boxes around parts which may or may not be paragraphs. Give them to participants and ask them to classify them as “paragraph” or “not a paragraph” just by looking.

A paragraph is a section of code within a long method that hangs together and might make sense to extract as a method. You can spot them without reading the code in any detail. They have one or more of these visual characteristics:

Once you think you’ve spotted a paragraph, it may take a little more investigation to see whether it really would be possible and/or desirable to extract as a method. If you have a refactoring tool, it can do this analysis for you. Ask it to do “extract method” on the paragraph. It should be able to show you if it’s possible and what the method signature would be.

Concrete Practice - BigDiceGame

Bring up a development environment with a piece of code that has some easy to spot paragraphs that will easily turn into extracted methods. For example BigDiceGame.

Work in an ensemble, guiding the group to convert each paragraph into a method. Use nonsense names at first (AppleSauce) until you are able to come up with honest names. (This is Naming as a Process).

Conclusions - main idea

In pairs, ask people to explain the main idea of code paragraphs.