Chapter 8: Composition and abstraction

Abstraction

face Josiah Wang

Another important concept related to composition is abstraction.

As I hinted quite frequently earlier, you can give your ‘blocks’ names, for example using variables or functions. These names will give you a hint about what the blocks represent.

Having such named blocks will allow you to write highly abstracted, reusable and self-explanatory code. This makes it easier for you or someone else to read, write, debug, and maintain your code in the future.

Let’s use the example from earlier that computes the value of sine of a number.

Writing abstracted code with named objects

If you look at the figure above:

  • At the top-level of the ‘abstraction hierarchy’, the name sin_x itself hints that it is the sine of x. Some people might only be interested in using sin_x and do not need any further details, and so can just go on their merry way!
  • Somebody else might be interested in a bit more detail. So they might go down one level. They see that the value is computed with math.sin() given x in radians. They might be satisfied at this stage, and there is no need to investigate further!
  • If somebody is really interested, they can go down another level and investigate the details. They can see that the x in radians from the earlier level is computed by taking the x in degrees (normalised) and multiplying by 2\pi. They might also look at the source code for Python’s math.sin() to see the Mathematical details of how a sine function is implemented.
  • Again, one can drill down further to different abstraction levels (e.g. how did you normalise the x? How did you get x_in_degrees?). One can stop when no further detail is needed.

As you can hopefully see, with this style of programming, you can ‘offload’ any details of your implementation to different levels of abstraction. This saves you from trying to keep all the details in your short-term memory at any one point!

This is an example of abstraction in action - you can avoid needing to know the details of something when it is not relevant to the problem at that point. Imagine yourself having to know all the internal details of how a car works loaded in your mind when you drive, when all you really need to do is just to drive the car to get to the College.