Chapter 14. Ifs

Make the change easy (warning: this might be hard), then make the easy change.

Kent Beck on Twitter

14.0 Introduction

Using GoTos was a well-established practice until Edsger Dijkstra wrote his incredible paper: “Go To Statement Considered Harmful.” Nowadays nobody uses the GoTo instruction (see Recipe 18.3, “Replacing GoTo with Structured Code”) and few programming languages still support it, because it creates spaghetti code, which is unmaintainable and error-prone. Structured programming solved the spaghetti code problem years ago.

Spaghetti Code

Spaghetti code is poorly structured code that is difficult to understand and maintain. The name “spaghetti” is used because the code is often tangled and interconnected in a way that resembles a plate of tangled spaghetti noodles. It contains redundant or duplicated code, as well as numerous conditional statements, jumps, and loops that can be difficult to follow.

The next evolution will be removing most if statements because ifs/cases and switches are GoTos disguised as structured flow. Both GoTos and ifs are present in low-level machine programming languages like Assembler.

Most if statements are coupled with accidental decisions.  This coupling generates a ripple effect and makes code harder to maintain since accidental ifs are considered as harmful as GoTos because they violate the open/closed principle (see Recipe 14.3, “Reifying Boolean Variables”). Your designs will become less extensible. If statements ...

Get Clean Code Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.