A theme in this course is reducing programming's cognitive complexity. Make programs easy to think about. Indenting, variable naming, other things, contribute to this.
Decomposition helps. A lot. Break a program into pieces, and work on the pieces individually. Functions make this work.
Suppose I wanted to make a program to view data about a goat. An id is passed in through the URL. I would start by making a plan, like this:
- $errorMessage = MT
- // Get goat id from GET.
- $goatId = from GET
- // Load that goat from DB
- $goatEntity = get goat with the id
- If not there:
- Put something in $errorMessage
- <html>
- Show head component
- <body>
- If errors:
- Show them
- else
- Make HTML to show goat
- Show it
Then I'd go through, and add more deets. Let's take the first part. Here's some code for it:
- $errorMessage = '';
- // Was the id given?
- $goatId = getParamFromGet('goat_id');
- $goatEntity = getGoatWithId($goatId);
- if (is_null($goatEntity)) {
- $errorMessage = "Sorry, there was problem loading the goat with id $goatId.";
- }
Some things I can convert into a line or two of PHP. This...
- Put something in $errorMessage
... becomes...
- $errorMessage = "Sorry, there was problem loading the goat with id $goatId.";
For larger tasks, I'll call a function. This line...
- $goatEntity = get goat with the id
... becomes...
- $goatEntity = getGoatWithId($goatId);
I haven't written the function yet. I've decided on its signature, though. What it does, what it's called, its params, and the return value.
This is decomposition. Breaking the program down into pieces, that you can work on one at a time. Or assign to different team members.
Once I'm happy with the plan, I'll dive into the individual functions. If I've planned well, I can write getGoatWithId()
without thinking about the rest of the program.
So:
- Plan the program first, leaving the deets for functions.
- Zoom in on the pieces, one at a time.