Lesson 2 | Traditional (Procedural) Programming |
Objective | Explain procedural programming, show top-down decomposition with code, and contrast it with an OOP solution in C++. |
Top-down decomposition
Procedural example (C): converting an image using explicit steps.
/* C (procedural): PNG → JPEG pipeline */ int convert_image(const char* inPath, const char* outPath) { Image img = read_png(inPath); if (!img.ok) return -1; Image ycbcr = to_ycbcr(img); return write_jpeg(ycbcr, outPath, /*quality*/ 85); }
Here the program flow is explicit and easy to follow. Changes to the pipeline (e.g., switch PNG → WebP) typically require editing the control flow or adding new functions that the main procedure calls.
OOP example (C++): use a strategy to change formats without changing the pipeline.
// C++ (OOP): pluggable converters via an interface struct Image { /* pixels, size, etc. */ }; struct ImageConverter { virtual ~ImageConverter() = default; virtual Image load(const std::string& in) = 0; virtual bool save(const Image& img, const std::string& out) = 0; }; struct PngToJpeg : ImageConverter { Image load(const std::string& in) override { return readPng(in); } bool save(const Image& img, const std::string& out) override { return writeJpeg(toYCbCr(img), out, 85); } }; bool convert(ImageConverter& conv, const std::string& in, const std::string& out) { Image img = conv.load(in); return conv.save(img, out); }
Now the pipeline stays stable while behaviors vary. To support WebP, implement
struct PngToWebp : ImageConverter
—no edits to convert(...)
.
PascalCase
(e.g., ImageConverter
).lower_snake_case
or lowerCamelCase
(pick one per project).SCREAMING_SNAKE_CASE
.read_png()
, write_jpeg()
), and nouns for types (Image
, Buffer
).
Performance note: Modern compilers inline aggressively; OOP is not “inherently slow.” Costs come from poor design (excess allocation, deep hierarchies, virtual hotspots)—not from the paradigm itself.
Key takeaway: Use the simplest model that cleanly expresses the problem. Start procedural for small tasks; graduate to OOP when variability, reuse, or growth demand it.