liveBook · Manning

Refactoring

As explained in The Well-Grounded Python Developer: How the pros use Python and Flask

Refactoring is restructuring existing code to improve its design or maintainability while preserving its intended behavior.

Refactoring improves maintainability by restructuring code around clearer responsibilities and more flexible reuse. A function that calculates, formats, and prints results is difficult to reuse; separating those jobs keeps the core calculation independent from its eventual output destination. section 1.3.2

Separate calculation from presentation

Instead of one function that performs a complex calculation, formats the result, and prints it, create a calculation function that returns raw results and a formatting function that prepares them for display. The same results can then support a screen, web page, printer, or API response without changing the calculation. section 1.3.2

Use these signals to decide when a refactoring is worthwhile:

  • Split a function when its explanation contains “and,” because that often signals multiple responsibilities. section 1.3.2
  • Break up functions that are too long to comprehend easily; around 25 lines is a guideline, not a strict limit. section 3.2.5
  • If several extracted functions operate on the same data, consider grouping them as methods of a class. section 3.2.5
  • Choose names that reveal each function’s single task, making the resulting code easier to read and reason about. section 3.2.5

Refactoring is not about following a rigid function-length rule. It is a practical response to code that has become difficult to understand, reuse, or adapt. Small, focused functions make the larger application easier to maintain. section 3.2.5

How The Well-Grounded Python Developer: How the pros use Python and Flask covers it

How deep it goes
Explains separation and function extraction through practical examples, without detailing a broader refactoring catalog.
Examples
Uses a calculation-formatting-output split and the extraction of long functions into focused functions or class methods.
What you can do after
Apply refactoring by splitting mixed responsibilities, extracting focused functions, and grouping related operations into classes when appropriate.
How it connects
Connects refactoring to maintainability, the single responsibility principle, functions, classes, naming, and IDE support.

Also explained in

Compare how 22 books explain refactoring →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Python Developer: How the pros use Python and Flask. The section links point to the parts of the book it draws on.