Why You’re a Bad PHP Programmer

We all have our bad habits. In this article, we’ll go over a list of bad practices that are worth examining, reevaluating, and correcting immediately.

 


Who the Hell Do You Think You Are?

Every time I open a project that isn’t mine, it’s accompanied by a tinge of fear that I’m walking into some kind of Temple of Doom scenario, filled with trap doors, secret codes, and that one line of code that, upon alteration, brings down the entire app (and possibly sends a giant boulder hurtling toward me down a narrow hallway).

When we’re wrong, and everything is fine apart from some minor differences in “how I would have done it,” we breathe a sigh of relief, roll up our sleeves, and dive into the project.

But when we’re right… Well, that’s a whole different story.

Our first thought upon seeing this unholy mess is usually along the lines of, “Who the hell does this guy think he is?” And rightfully so; what kind of programmer would willingly create such an unholy mess out of a project?


The Answer Might Surprise You

Awful code is the accumulation of multiple small shortcuts or concessions.

Your first instinct might be to assume that the guy who built the project is a novice, or maybe he’s just an idiot. But that’s not always the case.

My theory is that awful code is the accumulation of multiple small shortcuts or concessions — just as often as it’s the product of inexperience or stupidity. This makes the Temple of Doom app much scarier, because whoever built it might be just as smart, savvy, and well-read as you are. They just got lazy or put things together in a rush, and each of those little shortcuts added up into the winding nightmare that just fell in your lap.

Even scarier, this could mean that at some point, someone inherited your code and immediately burst into tears.


You’re Better Than That, Baby!

It never hurts to reexamine your current practices and make sure you’re not taking any shortcuts that could be contributing to someone else’s lost sleep.

Let’s take a few minutes and go over some common shortcuts, concessions, and other bad practices to ensure that our projects aren’t striking fear into the hearts of the villagers.


You Don’t Plan Before You Start Coding

Before you write a single line of code, you should have a solid plan of attack.

Before you write a single line of code, you should have a solid plan of attack. This helps keep you on track and avoids wandering code that will confuse you later, not to mention some other poor soul.

One approach that has saved me time — both in development and in commenting — is to write an outline in comments first:

<?php

// Include necessary data

// Initialize the database connection

// Include the common header markup

// Determine the page variables from the POST data

// Load the proper database info using the page vairiables

// Loop through the loaded rows

    // Format the images for display

    // Create a permalink

    // Format the entry for display

    // Add the formatted entry to the entry array

// Collapse the entry array into page-ready markup

// Output the entries

// Include the common footer markup

As you can see, without writing a single line of code, I already know almost exactly what the file will look like. Best of all, you can plan out an entire application this way, and if you get to a point where one feature requires a functionality tweak to another, all you have to do is change the comment.

It requires a shift in the way you approach development, but it will make your project organization skills go through the roof.

NOTE: Some of these comments aren’t necessary; some of them will change; others will need to be added — that’s expected. This is kind of like writing an outline for a paper or writing a grocery list: it just keeps you on the right track when you go to finish the job.


You Don’t Comment Anything

Yet the single worst problem with most code that I encounter is that it’s poorly commented, or not commented at all.

It makes me sad that I have to write this down. When something is as easy as commenting, it shouldn’t be something we have to remind each other to do.

Yet the single worst problem with most code that I encounter is that it’s poorly commented, or not commented at all. This not only adds a good chunk of time to my initial familiarization with the project, but it pretty much guarantees that a fix made using an unconventional method out of necessity will confuse me. Then, if I end up doing any refactoring, I’ll inadvertently break the app because I haven’t encountered the extenuating circumstances that required the fix.

This process can take anywhere from 10 minutes to 6 hours. (And you’ve done this to me, I know where you live. I’m coming for you.)

So say this out loud:

I, [state your name], hereby swear to make comments in any situation where the purpose of the code I’ve written isn’t immediately apparent.

“Immediately apparent” refers to code that can’t be self-documenting (because it wouldn’t be reasonable to do so) and/or doesn’t complete a dead-simple task. Think about it this way: if you had to stop and think about your solution for more than a few seconds, it probably merits a quick line of explanation.

To illustrate my point, I’m going to use an example from an article I wrote recently for beginners. Consider the following:

    $pieces = explode('.', $image_name);
    $extension = array_pop($pieces);

What does that do? Did you have to stop and think about it? Do you still not know for sure what’s stored in$extension?

Look at that snippet again, but with one quick comment:

    // Get the extension off the image filename
    $pieces = explode('.', $image_name);
    $extension = array_pop($pieces);

Five seconds at a time will add up in a big way.

Now glancing at this code doesn’t require any additional brain power: you see the comment, see the code, and never have to question its intent.

It might only save you five seconds of contemplation, but if you’ve got a complex app, five seconds at a time will add up in a big way.

So stop making excuses. Write the damn comment.


You Sacrifice Clarity for Brevity

Good examples of sacrificing clarity for brevity include unclear variable names and dropping the curly braces.

It’s a universal temptation to get something done in as few characters as possible, but that temptation is kind of like the temptation to only have one pair of underwear: sure, the laundry gets done quickly, but the problems that arise from your choice hugely outweigh the benefits.

Good examples of sacrificing clarity for brevity include short, unclear variable names (such as $a — what does $a store?) and dropping the curly braces.

Dropping curly braces from control structures is a particular pet peeve of mine. If you don’t like curly braces, switch to Python. In PHP, it’s just too easy to lose the meaning without them.

For example, look at this set of nested if-else statements without curly braces:

<?php

$foo = 8;

if( $foo<10 )
    if( $foo>5 )
        echo "Greater than 5!";
    else
        echo "Less than 5!";
else
    echo "Greater than 10!";
    echo "<br />Another note.";

At a glance, it looks like the last line should only fire if the value of $foo is greater than 10. But what’s actually happening is a case of improper indenting; the last echo statement will fire no matter what
$foo stores.

Can you figure it out if you look at it for a few seconds and know that if-else statements without curly braces only affect the immediate next line? Of course.

Should you have to waste the energy figuring that out? Absolutely not.

Adding curly braces adds a few lines, but it clarifies the statement immensely, even with the odd indentation:

<?php

$foo = 8;

if( $foo<10 )
{
    if( $foo>5 )
    {
        echo "Greater than 5!";
    }
    else
    {
        echo "Less than 5!";
    }
}
else
{
    echo "Greater than 10!";
}
echo "<br />Another note.";

Yes, it’s a good thing to keep your code concise, but not at the expense of clarity. It’s worth the extra lines to ensure no one has to bang their head against a keyboard trying to sift through your code.


You Don’t Follow a Coding Standard

Choose a standard and stick to it.

Getting cute with your formatting might satisfy your artistic urges, but it does no good for anyone. Choose a standard (I recommend the PEAR coding standard) and stick to it. Everyone will thank you. (Including yourself, someday.)

Trust me. I was that guy once — I wanted to have a “signature style” — and I wasted a lot of hours fixing my atrocious formatting later on. There’s a time to be different and a time to do it like everyone else.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值