You Copied It Again: the DRY Principle in WordPress, Explained on 4wp.dev

You copied it. Again. DRY, “Don’t Repeat Yourself”, is one of the first principles every developer hears, and one of the most misunderstood.

What DRY really says

The original wording from The Pragmatic Programmer (Andrew Hunt and David Thomas, 1999): “Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.”

The key word is knowledge, not code. Two identical lines can be two different decisions. Two different lines can encode the same rule.

The problem: duplicated knowledge

A typical WordPress plugin keeps the same option key in many places: get_option() in a template, update_option() in the settings handler, delete_option() in uninstall.php. Rename it in two files, miss the third, and the plugin silently leaves data behind or reads an empty value.

AI makes this faster: it copies a working snippet into every new file instead of reusing one function.

The other problem: the wrong abstraction

The opposite mistake is extracting too early. One do_everything( $type, $mode, $flags ) function full of if branches is harder to change than the duplicates it replaced. Sandi Metz put it plainly: “Duplication is far cheaper than the wrong abstraction.”

The rule of three

Extract shared code the third time the same knowledge appears, not the second. By then you know what actually repeats.

Is it the same knowledge, or just the same code?

FAQ

“Don’t Repeat Yourself”. The principle comes from The Pragmatic Programmer by Andrew Hunt and David Thomas (1999).

No. DRY is about duplicated knowledge. Two similar lines that represent different decisions can stay separate.

A refactoring guideline: tolerate duplication once, and extract shared code when the same thing appears a third time.

Shared code that forces different cases into one function with flags and branches. It is harder to change than plain duplication.

Keep option keys, meta keys, nonce actions and capability names in one place, such as a constant or a small function, and reuse it everywhere.

Go deeper