Pattern catalog

Patterns are common ways of doing things, like recipes. Part of learning a skill is learning the patterns that help you be more productive.

Here are patterns on this website. When you start a new project, you can use the patterns to remind yourself of useful chunks of code.

Name Tags Summary Where referenced
IPO Program design

One of the simplest patterns:

  • Code to put valid input data into variables.
  • Code to work out anything output needs that isn't in the input.
  • Code to output variable values.
Patterns and mad libs, Check the service level, Mars or bust!
Loop over a list of dictionaries Loops

You have a data set. Each record is a dictionary. All the records are in a list. Use a for loop to run through each record in the list.

Data sets, Record subsets
Normalize a string Validation

Simplify string validity checks by converting user input to a standard form.

Check the service level, Keep asking: strings
Numeric validation loop Validation, Loops

Loop while a data-OK flag is false:

    Set a data-OK flag to true.

    Check whether the data is numeric. If not, set the data-OK flag to false.

    If the data-OK flag is still true, do a range test. If the data is out of range, set the data-OK flag to false.

    Repeat for as many tests as you need.

Keep asking: numbers
One-time numeric input validation Validation
  • Get user input into a string variable.
  • Try to convert the data to numeric. If it fails, show an error message, and stop the program.
  • If it works, check whether the number is in the valid range (not too small, and not too large). If it fails, show an error message, and stop the program.
  • If both checks pass, you have a number you can use for calculations.
Check the meal cost
One-time string input validation Validation, Strings
  • Get user input into a string variable.
  • Normalize it to simplify value checking.
  • Check whether the value is one of the valid values.
  • If not, show an error message and stop the program.
Check the service level
Separate input from processing Program design

Put input and validation in one program. Put processing code in another. Use the session to send data from one to the other.

String validation loop Validation, Strings, Loops

Use a while loop to keep asking the user for input, until they type a valid value.

Keep asking: strings