Refactoring into Functions

Note: Most of the content of this page is inside toggles. Click on the triangles to disclose the code.

The initial program
image
Use “ablation” to reverse-engineer code
image
image
Capture our knowledge about the program into comments
“Factor out” the code stanzas into functions
Now we don't need the comments. The function names are “self-documenting
This only works because we are using descriptive function names
Replace repeated constants by variables
Turn the let variables into function parameters, that receive their values from where they are used
The remaining difference between leftEye and rightEye is the pupil size. Parameterize it too, so that the functions look the same
Now leftEye and rightEye have the exact same definition. We could delete rightEye and use leftEye twice
Since leftEye is used to draw both eyes, rename it to eye
Now it's easy to add a third eye, by calling eye a third time
image
Parameterize the iris color. This allows us to draw the third eye in a different color.
image
(Optional material, not shown in class) It's difficult to remember the order of the function parameters. Here's an alternative, that names them where the function is used as well as where it's defined.

©2020–2022 by Oliver Steele.