Once we’ve written some code, most programming languages enable us to package it in a certain way that allows us to re-use it for tackling related problems. We can use that code in our own projects, supply that code to someone else to use, or provided we abide by the authors terms and conditions of use, use their code in our own projects. This has a number of advantages:
Code takes time and effort to write, so re-using other people’s code can reduce the length of a project
Even if we have to pay people to use their code, the end cost of the project may be cheaper than doing it all ourselves
There will often be bugs in programs we write; code which is reused by multiple people has more of these bugs discovered and removed.
Other people’s code may give us an easier way to do sophisticated things which we are not experts in, like deal with graphics and sound, or create applications with windows and icons.
Code may be bought, sold, or leased like property, or given away in the spirit of charity
Many applications feature the same elements, for example most programs today have a menu system, so we can write the code to handle this once and use it in many different applications
When we reuse previously written code in our projects, we are said to be ‘importing’ it. ‘Imports’ usually take the form of sets of functions which we can call from our program, some documentation that explains what task these functions are supposed to achieve, and a license that explains the terms and conditions the code can be used under.
You may have noticed the ‘import’ keyword at the top of the programs you’ve seen so far. This has been used to import extra code into our programs to deal with the differing requirements of each task. This extra code shows up as functions which are called from the main program.
The program given to you is a calculator that deals with standard arithmetic only. Compile and run it to see how it works
Let’s turn our standard calculator into a scientific calculator, by importing some more functions which are already written for us. These functions are in an import called ‘maths’.
import system;
import maths;
etc..
The documentation for this import is as follows:
| pow(base, exp) | Returns base, multiplied by itself exp times |
| random(low, high) | Returns a random number from low, to one less than high |
| squareRoot(n) | Returns the square root of n |
Now we’ve imported ‘maths’, we can use the functions just like any we have written ourselves:
if( action == "sr" ) return sqaureRoot(n);