What In A Good Code Routine - Pt 2
Let's Make A Lasagna
Posted by Charlie Recksieck
on 2022-06-30
Now, who doesn't love a good analogy when learning concepts? They're a helpful way in for newbies. And a solid analogy can be stimulating for veteran programmers.
Recipe Analogy
When it comes to modularity (and object-programming) let's use the analogy of a recipe. And since I'm hungry right now, let's make it a lasagna recipe.
In following a recipe, there are several distinct and discrete functions. For lasagna you got to: gathering the ingredients, boiling the water / cooking the pasta, grating cheese, cooking the meat, making the sauce, layering the lasagna in the pan
Breaking Lasagna-Making Up Into Modules
Here's a flowchart of the theoretical routines in making lasagna:
Central Module
The one exception to small, modular code is a central, "master" routine. Think of this one as the "traffic cop" routine at the top, that calls each subroutine in the proper order to get things done.
Using our "Programming Design Language" (as recommended in Part 1 and in this 2019 article), we start writing our master routine in English:
Then we finish the easy coding of the master routine by calling the various subroutines
Each Subroutine
We think you get the picture and don't need to write out each cooking step as faux-code. But from the clear names on each aspect of the lasagna code routines, you can tell that each routine and procedure is pretty focused on one isolated aspect of the meal.
The Attributes Of A Good Routine
In Part 1 we laid out these characteristics of a smart routine:
* Utility/Usefulness
* Modular/Reusable ... and Testable
* Clear Purpose
* Readable/Namable
* Short
Utility: Each lasagna module is useful - grating cheese accomplishes something
Modular: We could take this BoilWater routine and reuse it in "code" for making a hard-boiled egg, as is with no co changes.
Clear Purpose: A single purpose should keep routine very simple. Looking at this lasagna software, I could easily make a criticism about FinishTomatoSauce being too complex. It involves adding tomato sauce, chopping and adding vegetables, adding spices - all of what are separate processes. In lasagna it's easy enough to think of this all as one thing, but in programming terms those should each be individual routines.
Readable: The simple routines are pretty easy to comment. Also, our PDL really paid off by having our simple English descriptions act as the green comments or documentation in the finished product.
Short: Each of those procedures are fairly short and manageable.
In Summary
Hopefully we reinforced best practices about breaking code up into practical and modular routines. And in a perfect world, you and I will both be eating a lasagna. Very soon.