Fork me on Github
Fork me on Github

Joe Dog Software

Proudly serving the Internets since 1999

up arrow DRY Programming

“The best programmers are all alike; every shitty programmer is shitty in his own special way.” –Anna Karenina

Today we are going to discuss one of the most important traits of a good programmer: He’s DRY, which is an acronym for “Don’t Repeat Yourself.” This principle is also referred to as Single Source of Truth. DRY programmers rarely use a clipboard. Their data is structured so that every piece of information is represented exactly once.

DRY code is easy to maintain. When a data element is stored exactly once, a single edit changes its value throughout the system. As soon as this principle is violated, maintenance becomes a bitch. For you bean counters out there — you guys who thought cheap programmers would save you money — that means expensive.

“I thought I changed that!” You did. The last programmer typed the same thing multiple times. “Where are the other instances?” I have no idea. “What did he call them?” God only knows. “There’s 50,000 lines of code across twenty files.” Well then you better start searching …  “FSCK!”

The best programmers adhere to this principle no matter what. It doesn’t matter if the same piece of information is needed by two separate tool kits. They use one piece of data and parse it with two separate languages. Let me give you an example.

When you download siege, you get a tarball named siege-3.1.0.tar.gz When you run siege –version, it displays the version number. In one case, the number is interpreted by C code, in the other it’s interpreted by a shell script. No matter, in both cases it’s sourced inside a single file. You can find it in src/version.c

So while it would have been easy to type “3.1.0” in the C file and paste that value inside, Your JoeDog would have to update it twice with every release. You know how often he’d miss one of those two edits? Every stinkin’ release.

In order to adhere to the DRY principle, he made the configure script parse a string in version.c  That string looks like this:

const char *version_string = "3.1.0";

And Your JoeDog parsed the number in like this:

VERSION=`sed -ne 's/.*version_string.*"(.*)";/1/p' ${srcdir}/src/version.c`

NOTE the use of ${srcdir}; one copy of everything, people.

Look, I know some of you are going to be like “fsck that guy. I’ll copy and paste to my heart’s content.” That’s fine as long as you are now and will always be the only maintainer of your code. But if you expect another human to work that code and if you insist on being WET (We Enjoy Typing), then you’re a bad programmer. Hey — somebody had to say it.