Developing Procedures
| English | Chinese | Pinyin |
|---|---|---|
| define | 定义 | dìng yì |
| parameters | 形参 | xíng cān |
| procedural abstraction | 过程抽象 | guò chéng chōu xiàng |
| readability | 可读性 | kě dú xìng |
| duplication | 重复代码 | chóng fù dài mǎ |
Writing your own procedures
- Writing your own procedures is a core programming skill.
- To define 定义 a procedure, give it a clear name, its parameters, and a body of instructions.
- Then you can call it wherever you need that job done.
- A good procedure does one clear thing.
To define a procedure you give it:
Those three parts make a reusable procedure.
Parameters give flexibility
- Use parameters 形参 so a procedure can work with different input values.
greet(name)can greet anyone, because the caller supplies the name each time.- Without parameters, you would need a separate procedure per name.
- Parameters are what make one procedure reusable across many cases.
Good candidate for a procedure?
Extract a procedure when a chunk of work has one clear purpose or repeats in several places; a unique one-off line does not need its own procedure.
Why does greet(name) use a parameter?
The caller supplies a different name each call.
Breaking a large problem into smaller procedures, each with one job, is ______ abstraction.
Procedural abstraction keeps big programs manageable.
Procedural abstraction
- Procedures let you apply procedural abstraction 过程抽象 — breaking a large problem into smaller, manageable parts.
- Each part becomes a procedure with one clear job.
- You reason about the small parts, not the whole tangled program at once.
- This is how large programs stay understandable.
Putting repeated code inside one procedure mainly reduces:
One procedure replaces many copies of the same lines.
With a greet procedure, changing the greeting means editing one place, not three.
Fewer places to edit means fewer chances for errors.
A well-named procedure like calculateTax() helps a reader understand the intent quickly.
Good names improve readability and reuse.
Two big benefits
- Well-named procedures improve readability 可读性 and reuse: a reader sees
calculateTax()and gets the intent. - Putting repeated code in a procedure reduces duplication 重复代码.
Remove duplication. A program prints the same three-line greeting in three places — that is duplication. Define one greet(name) with those lines; now each place is a single call: greet("Ana"), greet("Bo"), greet("Cy"). Change the greeting once, not three times.
To define a procedure, give it a name, parameters, and a body. Parameters let one procedure handle many inputs (greet(name)). This is procedural abstraction — split a problem into small jobs. The payoff: better readability and less duplication (edit one procedure, not many copies).