Many, Small Functions (Python Basics 9)

Common Coding Problem

  • student writes fairly long program (several hundred lines)
  • student comes to me and says, “Help, my code doesn’t work.”
    • how am I supposed to debug hundreds of lines of vaguely broken code?

A Better Way

Some of my best coding advice:

  • break your code into many, small, helper functions
  • make sure each function does its job correctly
  • the main part of your code becomes much more readable as you call these helper functions

Small Functions

  • ideally, each small function should do one thing
  • a function that does more than one thing should be broken into several functions
  • functions that do only one thing are more likely to be reusable later
  • putting your small funtions in python modules that you can import makes reusing your code easy

Looking for a Sign

  • if you find yourself copying and pasting chunks of code, that is a clear sign that the code should be put in a small function

Example