Let’s take the previous algorithm about grocery shopping again.

Suppose the initial instruction looked like this:

  • Here’s 10 dollars for you.

  • Go to the store “Near Home”.

  • Buy kefir.

This is a very specific instruction, where we can identify the core command “buy kefir” and several constants associated with it:

  • The amount of 10 dollars.

  • The store “Near Home.”

After writing out this algorithm as a detailed set of actions, tomorrow we might want to buy bread, or cookies, or bananas, or something else.

In these algorithms, many actions will be similar, and the differences will only lie in what exactly to buy.

That is, we can create a single algorithm called “buy” and specify to this algorithm “what to buy,” “where to buy,” and “the available amount of money.”

Notice: what to buy, where to buy, and the amount we have are quantities that can change—in other words, they are variables.

Key Concepts

  • An algorithm becomes valuable by expanding its scope of applicability—the broader the scope, the more valuable it is, because you can reuse it.

  • To cover a broader scope, you need to parameterize the task—identify all those entities that can change but do not affect the essence of the algorithm itself. In a sense, parameterization is directly related to abstraction.

  • The parameters of a task are variables.

  • The variable name should reflect the essence of what it stores: naming is one of the most challenging tasks in programming—coming up with a variable name that immediately makes its purpose clear.

  • There is also the variable type—it defines the allowable range of values the variable can hold (we will discuss this in more detail later).

  • All together: the algorithm name, the names of the input variables, their types, and the return type form a contract.

Vocabulary

  • Parameter / To parameterize

  • Variable / Input variable

  • Variable type

  • Naming

  • Contract