Page 227 -
P. 227
don't copy, share
Don’t just update your copy
The code in the gym program is a copy of your code in the coffee bar.
And copying code is a bad thing. Once you have two separate copies
of a piece of code, then changes need to be applied in two places.
So how do we avoid copying code?
Smart programmers write modular code
The secret is to break your programs into smaller pieces of code
called modules. What’s a module? It’s just a file containing code the
computer can run. Every Python program you’ve written so far has
been a single module.
But most programs you’ll write will probably be split across many,
many modules. And writing modular code is important because
modules can be shared between programs.
I‛ll use transaction.py
to record the sale.
coffee_pos.py gym_pos.py
This is a SHARED module.
transactions.py
If you separate out the code that saves the transactions to a file and
store it in a new module called transactions.py, that module
can be shared by both programs. If you then ever need to change
the code in transactions.py, both programs will pick up the
changes automatically.
192 Chapter 6