Chapter 8: Composition and abstraction

Composition in expressions

face Josiah Wang

Let’s take a break from trying to code, and step back a bit and review the bigger picture of how programs are formed.

Back in Lesson 1, I assembled basic building blocks to form a program.

Programming is a form of composition

If you remember, I described this process as composition. Intuitively, you can use a block inside another block to achieve a larger goal.

Composition is not limited to only these building blocks. It also happens among the smaller components of programs.

Take for example literals. You can combine them with operators to form expressions (which are also objects).

2 * 3.141592653589793

Composing literals and operators to form expressions

Of course, you can also compose variables. The advantage is that this gives your component a semantically meaningful name, which makes it easier to understand what it represents.

2 * math.pi

Composing literals and operators to form expressions

You can then further combine more expressions to form more complex expressions (which are still objects)

x_in_degrees / 360.0 * (2 * math.pi)

Composing expressions to form complex expressions

Of course, you can give these composite expressions a name to indicate what it represents at a higher level.

x_in_radians = x_in_degrees / 360.0 * (2 * math.pi)

Assigning names to composite expressions