Ugly code is everywhere. Inside that copy of Microsoft Office 2007, behind that latest Linux kernel, and in the dozens and dozens of web 2.0 MicroISV tools you use day-in and day out. Lurking.

But there are those of us who fight! Who rage against the dying of the light! Those who are more than happy to share our solutions to cleaning up ugly code, in the hopes that up-and-coming programmers will notice and apply said solutions. This… is one such solution.

Take, for example, nested conditions. They look like:

if (thing) {
    [CHUNK A]
    if (thing) {
        [CHUNK B]
        if (thing) {
            [CHUNK C]
        }
    }
}

It’s not THAT ugly, but try extending that out into five or more chunks, or if you’ve already indented a couple of times, you will notice just how ugly this looks. Since each chunk is only executed based on the result of a boolean test (the if statements), and each chunk is directly dependant on the previous chunk (and oughn’t be run if the previous chunk fails), we can take advantage of short-circuit operators and rewrite this section of code to be much cleaner.

Instead, rewrite each chunk into its own function, have that function return a boolean, and you can rewrite the original code like:

$success = do_chunk_a();
$success = $success && do_chunk_b();
$success = $success && do_chunk_c();

This is a huge win in terms of readability, and therefore in terms of maintainability. Especially so if you name your new functions descriptively, like “send_invoice()” or “update_client_list()”. It’s far easier to look at the descriptive name of the functions instead of having to read through the entirety of each chunk, just to find out what the code is supposed to do.