Code Reuse

Code reuse means building new software from parts that already exist and already work: a function you wrote last week, a class from another module, or a library that thousands of programmers depend on. You meet it as soon as a program needs the same calculation in two places, and every time you write an import line. This lesson compares the ways code can be reused and gives you simple counts for deciding when reuse pays off.

Forms of reuse

Code reuse is using existing, tested code in a new context instead of writing equivalent code again. The form you choose decides what happens when that code later changes.


Form

How it works

Effect of a later fix

Copy and paste

Duplicate the source text

Each copy must be fixed separately

Function or module call

Call one shared definition

One edit reaches every caller

Library or package

Import code maintained elsewhere

Upgrade to the fixed version

Inheritance

A subclass acquires a parent class's methods

A parent fix reaches every subclass

Composition

An object holds another object and delegates to it

Fix the delegate once


Copy and paste looks like reuse, because nothing is retyped, but it produces a clone. Every other form keeps one definition and lets many places depend on it. Libraries extend this across projects: you call a library through its API without reading its internals.


Python
def average(scores):
    if not scores:
        return 0.0
    return round(sum(scores) / len(scores), 1)

quiz_mark = average([78, 85, 91])
lab_mark = average([66, 74])


Both calls run the same tested definition, so the empty-list check protects every caller.



Counting the payoff

Suppose a routine of LL lines is needed in kk places. Copying it costs kLkL lines. Writing it once as a function of LfL_f lines and calling it with cc lines at each call site costs Lf+kcL_f + kc lines.


linescopied=kLlinesshared=Lf+kc\text{lines}_{\text{copied}} = kL \qquad \text{lines}_{\text{shared}} = L_f + kc


The bigger difference is maintenance. A defect in the routine needs kk edits when it is copied and 1 edit when it is shared, and a fix made in one copy does not reach the others. If you have to find each remaining copy by searching, every copy you miss keeps the bug alive.


Four modules each holding their own copy of a routine beside four modules that all call one shared average function.


Example: A 15-line date-formatting routine pasted into 3 files uses 45 lines and needs 3 edits per fix. As a 16-line function called with one line in each file, it uses 16+3=1916 + 3 = 19 lines and needs 1 edit per fix.



When building for reuse pays

Making code reusable costs extra effort up front: generalizing parameters, documenting the interface and testing edge cases. Call that extra cost RR. Each later use saves the time to write the code from scratch, but subtract the time spent integrating the reusable version; call the net saving per use ss. A simple model puts the break-even point at the number of uses nn for which the savings cover the up-front cost:


n s≥R⟹n≥Rsn\,s \ge R \quad\Longrightarrow\quad n \ge \frac{R}{s}


Round nn up to a whole number of uses. The model counts only time. It leaves out effects that also matter in practice, such as shared code having been tested already, and the ongoing cost of maintaining a component that other teams depend on.

What to remember

  • Code reuse means relying on one existing, tested definition rather than writing equivalent code again.
  • Copy and paste creates clones: kk copies need kk edits per fix, a shared definition needs 1.
  • Copied lines total kLkL; shared lines total Lf+kcL_f + kc.
  • Building for reuse pays once n≥R/sn \ge R/s, where ss is the saving per use after integration time.

Example: Sharing a grade-averaging routine

A school reporting app computes a weighted term average in five modules: report cards, parent emails, the honour roll, the teacher dashboard and the transcript export. Each module contains its own 12-line copy of the routine. A developer proposes replacing the copies with one shared function of 13 lines, called with a single line in each module.


a) How many lines does the routine occupy now, how many will it occupy after the change, and how many lines does the change save?


With copies, each of the five modules holds 12 lines, so the routine occupies 5×125 \times 12 = ________.


With a shared function, the definition costs 13 lines once and each of the five call sites costs 1 line, so the routine occupies 13+5×113 + 5 \times 1 = ________.


saved=60−18=42 lines\text{saved} = 60 - 18 = 42\ \text{lines}


The change saves 42 lines across the app.


b) A rounding bug is found in the report-card copy. The developer fixes it there and then searches the codebase for the other copies. Assume each remaining copy is found independently with probability 0.9. What is the probability that at least one copy still has the bug after the search, and how would the shared function change this?


With copies, one fix requires ________: the report-card copy plus the four other modules. The report-card copy is certainly fixed, so the risk comes from the four copies the developer must find.


The probability that all four are found is


0.94=0.65610.9^4 = 0.6561


so the chance every copy is fixed is ________. The probability that at least one copy keeps the bug is the complement:


1−0.6561=0.3439≈34.4%1 - 0.6561 = 0.3439 \approx 34.4\%


With the shared function, the bug lives in one place. One edit corrects all five callers, so no buggy copy can remain, provided the fix itself is correct. The probability of a leftover buggy copy drops from about 34.4% to 0.


c) Turning the function into a library that other schools' apps can import costs 2 extra hours for general parameters, documentation and tests. Each school that imports it instead of writing its own saves 1 hour of writing but spends 15 minutes integrating it. How many schools must reuse the library before the extra effort pays off?


The net saving per school is the writing time saved minus the integration time, s=1−0.25s = 1 - 0.25 = ________.


Using the break-even condition with R=2R = 2 hours:


n≥Rs=20.75=2.67n \ge \frac{R}{s} = \frac{2}{0.75} = 2.67


so nn must be at least ________, and a number of schools must be whole, so round up.


Check: three schools save 3×0.75=2.253 \times 0.75 = 2.25 hours, which covers the 2-hour cost, while two schools save only 1.5 hours, which does not. The library pays off once 3 schools reuse it.

Match each form of code reuse with the description of how it works. Each description fits exactly one form.

Match each term
A.

Duplicating source text so that every copy must be fixed separately

B.

A packaged collection of tested routines that many separate programs import

C.

An object holds another object and forwards work to that object's methods

D.

Running one named definition from several places instead of repeating its statements

E.

A subclass acquires the methods of a parent class and may override them

Library

Composition

Function call

Copy-and-paste reuse

Inheritance

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A parcel application records masses in grams. You want to reuse an existing function, shipping_fee(mass_kg), which requires its argument in kilograms and accepts only masses greater than zero and less than or equal to 20 kg.


Complete the table with each converted mass and whether the converted value satisfies the function's input requirements. Enter exact decimal numbers for masses and yes or no for acceptance. Do not round an invalid mass into the permitted range.

ParcelRecorded mass (g)Converted mass (kg)Accepted input?
Small parcel750
Maximum parcel20000
Oversized parcel23500
Empty record0

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

A 20-line data-cleaning routine has been pasted into 6 separate analysis scripts. A teammate proposes replacing the copies with one shared function of 22 lines, which each script would use with 2 lines (an import line and a call line). Find the total number of lines the routine occupies across all scripts as copies, the total number of lines it would occupy with the shared function (definition plus all call sites), and the number of separate edits one bug fix requires in the copied version. Give each answer as a whole number.

Your answers

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

Extra Practice