liveBook · Manning

Reuse

As explained in Get Programming: Learn to code with Python

Code reuse is the practice of incorporating existing software components into new programs instead of reimplementing their functionality.

Code reuse means incorporating existing code into a new program instead of writing the same functionality again. Reusable code can be treated as a black box: provide inputs, let it perform its behavior, and use its output. section 20.2

Replacing copy-and-paste code

Instead of repeating four operations for every pair of numbers, wrap the operations and reuse the wrapper: a = 1 b = 2 < wrapper for operations_with_a_and_b > a = 3 b = 4 < wrapper for operations_with_a_and_b > The values change, but the operation code stays in one reusable place. In Python, these wrappers are functions. section 20.2

Reuse helps programs by allowing you to:

  • Avoid copying and pasting the same operations for different inputs. section 20.2
  • Call one function with different kinds of suitable data, such as temperatures, ages, or weights. section 23.4
  • Reuse a function that reads one data format for another file organized in the same format. section 23.4
  • Build more complex programs from existing functions, objects, and libraries rather than creating everything from scratch. section 35.0
Figure 20.4. Black-box view of code that adds, subtracts, multiplies, and divides any two numbers

A black-box diagram shows the shared operation bundle receiving two numbers and producing the results of addition, subtraction, multiplication, and division. section 20.2

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains repetition, black-box thinking, and practical function reuse, while deferring the detailed mechanics of writing wrappers.
Examples
Uses arithmetic on number pairs, repeated file reading, and area-code-to-state data.
What it assumes
Assumes basic Python variables and data while introducing black boxes and reusable functions as organizing ideas.
What you can do after
Build programs from reusable functions that accept different inputs and process similarly organized data.
How it connects
Connects code reuse with functions, abstraction, objects, input/output, and libraries.

Also explained in

Compare how 6 books explain reuse →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.