Programming Lesson 8: Clean code & problem solving
A practical guide to approaching problems, writing clear code, and organizing small projects.
Learning goals
- Follow a repeatable problem-solving approach.
- Apply clean code practices: naming, small functions, DRY.
- Organize code and helpers for clarity and reuse.
- Complete small capstone exercises using these principles.
Problem-solving approach
Template to follow when solving a task:
- Understand requirements: what input and output are expected?
- Write examples: concrete input → expected output pairs.
- Break into steps: decompose the problem into small tasks.
- Implement + test: write code for one step, test with examples, iterate.
Problem-solving template (copyable)
// 1) Example inputs and expected outputs
// input: [1,2,3] expected: 6
// 2) Steps
// - compute sum
// - return result
// 3) Implementation
function sum(arr) {
// small, well-named function
let total = 0;
for (const v of arr) total += v;
return total;
}
// 4) Test
console.assert(sum([1,2,3]) === 6);
Clean code basics
- Naming: choose descriptive names (what, not how).
- Small functions: one responsibility per function.
- Avoid duplication: extract shared logic into helpers.
- Comments last: prefer clear code; comment why, not how.
Organization
Separate constants and helpers; keep related functions together. Example simple folder layout:
/src
/helpers
math.js
/features
scoreTracker.js
index.js
Capstone exercises
Score tracker (functions only)
function createTracker() {
const scores = [];
return {
add(score) { scores.push(score); },
total() { return scores.reduce((a,b) => a + b, 0); },
average() { return scores.length ? this.total() / scores.length : 0; }
};
}
const t = createTracker();
t.add(10); t.add(20); // test
console.log(t.average());
Compute stats from array
function stats(arr) {
return {
min: Math.min(...arr),
max: Math.max(...arr),
avg: arr.reduce((a,b) => a + b, 0) / arr.length
};
}
stats([5,10,15]); // {min:5,max:15,avg:10}
Practice tasks
- Implement a score tracker and verify average after adding values. Expected: correct numeric average.
- Write a function that returns min/max/avg for an array. Test with [2,4,6] → min 2, max 6, avg 4.
- Refactor duplicated code into a helper and show tests remain passing.
Common mistakes
- Poor naming that hides purpose.
- Monolithic functions doing many things — hard to test.
- Copy-pasted logic that drifts out of sync.