Functions
Why functions?
Split a long program into functions.
As a program grows, writing everything in one long list of statements makes it bulky and hard to manage. The book's tent-pricing program (Program 7-1) shows this: it works out the canvas needed for a tent, its cost and the tax, all in one long block.
Modular programming divides a program into separate, named, independent blocks, each with a specific job. Such a block is a function: a named group of instructions that does a specific task when it is called (invoked). Once a function is defined, it can be called again and again, from different places in the program, or even from inside another function.
Program 7-2 rewrites the tent program with three functions: cyl(h, r) for the cylindrical part, con(l, r) for the conical top, and post_tax_price(cost) for the tax. The program becomes more organised and much easier to read.
Advantages of functions:
- Better readability: each part of the program has a clear name and purpose.
- Shorter code: the same code is not written in many places, so the program is shorter, and debugging is easier (a mistake is fixed in one place).
- Reusability: a function written once can be used again. con(l, r) can be reused for a new tent design; post_tax_price() can be used wherever the same tax applies.
- Teamwork: different team members can write different functions at the same time.
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.