Why You’re a Bad PHP Programmer

Why You’re a Bad PHP Programmer

Tutorial Details

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.

Republished Tutorial

Every few weeks, we revisit some of our reader's favorite posts from throughout the history of the site. This tutorial was first published in February of 2011.


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.

When it comes to programming, think of it like a spoken language. Grammar and punctuation exist for a reason: so we can clearly understand each other when we write things down. Think of coding standards like a geeky version of Strunk & White’s Elements of Style — following the guidelines means people understand what you’re trying to say, not that you’re a boring person.


You Duplicate Code

You’re doing it wrong.

Try to look at every single piece of your app as something that will need to change at some point. If it does, will you have to update more than one file? If you answered yes, it’s time to reevaluate how you write code.

If you’ve got code doing the same thing in more than one place in your app, you’re doing it wrong.


You Don’t Follow a Development Pattern

You should always have a structure when you code.

You should always have a structure when you code. I don’t mean to imply that you need to be following the MVC pattern or something equally rigid, but I do mean that you should know how to classify components and where they should go.

By following a logical development pattern, many decisions become automatic, and someone coming into your code doesn’t have to guess much when looking for a certain functionality in your codebase.

It doesn’t take long, and it really will clarify your apps in a big way.


You’re Too Clever for Your Own Good

The simplest solution is usually the most appropriate

There’s a fine line between a crafty solution and an overcomplicated one.

It’s always tempting to try out some sweet new trick you’ve learned, but we have to resist the urge to force a complex solution into a space where a simple one is sufficient.

On a basic level, the simplest solution is usually the most appropriate. You’re trying to get from point A to point B — taking a detour through point Awesome is fun, but really doesn’t add any benefits.

Your super-sweet solution does, however, pose a problem in which someone else may not have seen that particular solution and will just get lost. It’s not because they’re not as smart as you, either; it’s likely because they didn’t see that particular article or weren’t trying to force a square concept into a round problem.

Don’t dumb yourself down, but remember to avoid overcomplicating things “just ’cause.”


You’re a Wang

Avoid actively making your code hard to understand at all costs.

When I was first getting into development, I worked with a guy that was a self-proclaimed “expert” programmer. Whenever I had a question about a concept, he never gave me a straight answer; in order to get the answer to my original question, I had to answer a couple preliminary questions to “prove you can handle the answer.”

This guy was also really good at writing code that was cryptic, obfuscated, and just generally confusing.

Files like his are the result of programmers who think that they need to make their code hard to read in order to “keep the idiots out.”

The general philosophy behind this tends to be, “If you’re not smart enough to understand this code, you shouldn’t be in it in the first place.”

This is a deeply misguided and anti-social approach to programming. It’s a very elitist way of looking at things, and it shows that the programmer has lost touch with his beginner roots, when he himself needed help.

Avoid actively making your code hard to understand at all costs. It doesn’t make you any cooler or smarter, and it doesn’t bolster respect. It just makes you a wang.


Dude, What Are You Talking About?

If you stop learning, then the projects you work on are stuck in whatever time period you decided to settle.

In addition to the shortcuts and general laziness above, another thing that might be holding you back is a lack of continued learning and forward progress.

Technology isn’t changing because the community at large is bored and we decided to redecorate; most new technologies emerge to more efficiently and easily solve existing problems. Choosing to ignore progress is choosing to start the slow process of marginalizing your skillset.

Here are a few things we can all stop doing to make sure that our skillsets are up-to-date, all without having to give up our weekends.


You’re Trying to Do it All Yourself

Find out which of these programmers have a similar approach and let them fill you in on the big news.

You can’t keep up with the whole community. As anyone who’s ever tried to keep up with a subscription to 200+ tech blogs will tell you, it simply can’t be done within a reasonable timeframe.

Fortunately, there are those within the community who dedicate their time to watching the progression of technology and reporting their findings. If you take the time to find out which of these programmers has a similar approach and style, you can let them fill you in on the big news.

Watching 2-5 of these “early adopter” type bloggers can be more beneficial than subscribing to every tech blog you come across for several reasons:

  • If you trust their opinion, they’ll be screening technologies for you.
  • If a technology pops up on more than one of these blogs, you know you should at least take a few minutes to learn more about it because it’s obviously popular.
  • Often, these blogs will feature a quick intro tutorial, which can save you the headache of starting from zero with a new technology.

Among the PHP bloggers I trust are David Walsh and Chris Shiflett.


You’re Not Out of Your Comfort Zone

I simply mean to suggest that you’ll feel more fulfilled as a programmer and see your talents progress more and more if you choose to always be looking to the next level of programming.

If you’re not doing something that challenges you, something is wrong. Finding new challenges within projects is most of what makes programming rewarding (or at least it should be).

Try asking yourself the following questions when you start looking at new projects:

  • Is there a new technology that interests me that applies here?
  • Have I learned of a better way to do this since the last time I took on a project like this?
  • Is there a best practice I need to enforce that I could make sure to follow throughout this project?

Keep in mind: I’m not talking about doing anything grossly complex, here.

It can be as simple as remembering to add Docblocks to your objects, or as complex as making your app compatible with XMLRPC so it’s easier for users to post updates.

Just try not to settle in and convince yourself you’ve learned everything you’re going to learn. That’s when it’ll start getting ugly for you.


You’re Not Sharing

Always discuss your code with your fellow programmers.

The best way to improve is to discuss your code with your fellow programmers. This can be done through multiple avenues: if you’re feeling particularly outgoing, write a tutorial or release an open-source project; if you don’t feel up to something of that scale, maybe you could hang out on a community forum and offer help to the newcomers.

“How does helping the noobs help me progress?” you ask. Usually, if you post a solution that could be optimized, other experienced programmers are going to hop in and offer tweaks. So this approach is a double-whammy of awesomeness: you’re not only helping progress the community by offering your knowledge to beginners, but you’re sharpening your own skillset by hanging your chops out for everyone to see and help you develop.


You Don’t Have Any Side Projects

If you want to get into something new and cool that’s a bit too involved to put into a real project, the best way to learn is to start a side project that uses said technique.

That way, you can progress at your own pace, in your free time, and never risk missing a deadline or “doing it wrong.”


We’re All Guilty

If we’re doing it right, we should always be improving. And logic tells us that if we’re better now, then we were worse before. And if we follow that line of reasoning back far enough, there was a point where we were terrible.

I know that when I look back at some of the code I wrote in the past, I’m horrified.


So… Stop it.

We’ll never be perfect. But we can do everything in our power to make sure that we’re getting as close as possible.

What are your pet peeves when dealing with other developers’ code? Let me know in the comments!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Andrew

    I’m sorry, but is this an archive/repost? I get a strong feeling that I’ve read this before.

    • http://www.50lappen.se Johannes

      “Republished Tutorial
      Every few weeks, we revisit some of our reader’s favorite posts from throughout the history of the site. This tutorial was first published in February of 2011.”

    • Ian

      You have, if you read under the beginning it states “Republished Tutorial
      Every few weeks, we revisit some of our reader’s favorite posts from throughout the history of the site. This tutorial was first published in February of 2011.”

      Still a great article which remains relevant.

      • http://www.wimbledon-it.co.uk Bjoern

        Sad isnt it ? But that is something that wont change.

    • http://www.bartoszstankiewicz.com Bart

      me too

  • http://andre-baumeier.de Andre Baumeier

    Nice post, I want to add something.

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

    stop that. pretty good example of bad code and bad comments.

    “You Don’t Comment Anything”

    Commenting: Don’t comment if you dont have to. If you have to comment rethink your solution. Break it in small pieces. If you still have to make things clear, rethink again, still think to comment? comment.

    function getFileExtension($filename) {
    $pieces = explode(‘.’, $image_name);
    return $extension = array_pop($pieces);
    }
    $extension=getFileExtension($image_name);

    dont comment internal functions. You don’t have to comment internal functions like exploder, implode, split etc. If you’re new or dont remember those functions, get yourself an IDE like Eclipse with build-in function docs.

    If you do something bigger. with lots of small pieces comment your intention, tell what you want to achieve with your code. Just dont comment that you retrieving a filename, or converting a date or any other stuff like that.

    “You Sacrifice Clarity for Brevity”

    aggree – just dont use short tags if not needed. Use curly braces. no stuff like

    but this one:

    $bool=($x>$y) ? false : true;

    could be even shorter:

    $bool=($x>$y);

    both are better than

    if ($x>$y) {
    $bool=false;
    } else {
    $bool=true;
    }

    “Avoid actively making your code hard to understand at all costs. It doesn’t make you any cooler or smarter, and it doesn’t bolster respect. It just makes you a wang.”

    aggree but, specific language features (e.g. ternary) and code patterns don’t obfuscate code or make it hard to understand, instead it makes it easier if the audience knows the basic of the given language.

    • C

      I just have to add that getting the file extension in PHP is a one-liner:

      $file_extension = pathinfo($filename, PATHINFO_EXTENSION);

      Also as a past author (now reformed) of the if-a-equals-b-then-true-else-false style of coding, two thumbs up for this:

      $bool = ($x>$y);

      • http://Ajaxjones.com Ajax jones

        If then else is clearer, refactor lesson

        Using the short form is no good when people are unsure What it means or are trying to scan your code And using expansion to else if is impossible

    • Stefan

      Fully agree. Try to extract a method of code that is unclear, give it a good name. No need to comment every two liners. Further you prevent code duplication and can reuse that.

  • Eric

    I mainly follow 3 rules. Especially on project with more people involved.
    · Use Allman style (with tabs, not spaces), with Tenary (if/else) when possible.
    · No php short tags.
    · Never use double quotes unless you really need to.
    ——-
    Sum: Nice and clean approach for all (newbies->pro’s) in your project(s).

  • http://coder9.com warren

    I always review the Document.

    Also I have a Paper copy or I bring an Ipad when I’m outside walking.

    I review my codes always….

    I try to learn codes from other coders…

    I use Math Algorithm to simplify my codes… Just like quants.

    I always feel to be drunk of coding… I’m addicted… love it…

  • http://www.webmentor.cr/ Marco Berrocal

    I don’t know if swearing is allowed, but this is a great fucking post. It solved me of SO MANY THINGS.

    I get very anxious because “I don’t know it all” but don’t DIVE INTO the pool.

    Also the commenting before you code, NEVER thought of that one..lol

    • Nico

      Always good to read this “refreshing the knowledge” artcles

  • Nirav

    An eye opener and something that every developer should incorporate.

  • Ruby

    You have a lot of sare time, havn’t you?

  • begs

    I don’t like those “Why you are such a bad … programmer article titles”.
    Why don’t you call it “How to get a better … programmer”?

    That would give readers (and programmers) a much better feeling and more confidence even if they (like all of us) do some of the outlined errors.

    • theQuestion

      So, that @begs the questions … why did you read it? Are you a bad programmer or did you read this and get better as a programmer?

    • http://webdevelopment.pk Faisal

      Because Many time else condition is batter than if condition. The name is absolutely right for Approach to the Right way.

      There is two reinforcements to a person, positive and negative. We have read positive articles so many times now its the need of a negative one.

      ( i have learned many of rules that was new for me Thanks to the writer Great Job :) )

  • Adrian

    The article is perfect, just 1 minor detail, next time add titles that describes confidence, not to make you feel like a heel. Thank you

  • Slam

    I disagree with two point:

    1) “You should have a solid plan of attack”
    This means a previous Design, frequently evolving into a Big-Design-Up-Front.
    Well, Test-Driven-Development teaches that this is counterproductive. What I do prefer is:

    a) Do not have any plan of attack; don’t think at all
    b) Clarify requirements and needs
    c) Write them in a code form: a test
    d) Follow the path tests (aka requirements) want’s you to follow

    This maybe a bit poor analysis, but read books and kata TDD, and you’ll understand it.

    2) “I hereby swear to make comments in any situation where the purpose of the code I’ve written isn’t immediately apparent.”

    I do prefer:

    “I hereby swear to refactor code in any situation where the purpose of the code I’ve written isn’t immediately apparent.”

  • Richard

    Just an FYI, you say that you stick to the PEAR standards however you do your control structures wrong:
    http://pear.php.net/manual/en/standards.control.php

    • http://blog.stuart-edwards.info Jason

      He doesn’t say he follows PEAR as such he say’s he recommends it.

  • http://mattrheault.com Matt

    You know me far to well nettuts.

  • http://codeseekah.com Gennady

    There are hundreds of books on how to write good code, so just one article won’t do it. I think that that last two points are the most important ones that sum it all up in the end.

  • Oved

    Buen post.

    Ups! soy un mal programador, prometo tratar de mejorar cada día.

    Saludos desde México!

  • giammin

    why you’re a Bad PHP programmer?

    because YOU ARE a PHP programmer!

    by a c# programmer

    • Gulli

      Just to feed the troll, being a C# programmer is far from being any quality assurance – I’ve seen (and written) awful PHP code and I’ve seen equally bad C# code, the difference is usually that bad PHP programmers seem to grasp the basics of how the web actually works, bad C# programmers have no idea.

  • http://welikethepandaz.tk Mark

    WOW! Holy mother of code, this article really opened my eyes in the fields of my sickish and well commented code,after reading this, i have become devoted to correcting my projects every step of the way! I am so thankful for people like you, experienced, and willing to help! And again thanks!

  • Trevor

    I disagree with your opinion on comments. I’m a bit of a radical on this issue, but I hate it when developers comment their code! It takes up needless space and breaks up my reading of actual code (when it’s well written). I think there are very few situations that actually require comments. Take your example, for example:

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

    Now take this example:

    function ExtractExtensionNameFromImageFilename($image_name) {
    $pieces = explode(‘.’, $image_name);
    $extension = array_pop($pieces);
    }

    Which is more easy to read? Do you even have to bother looking at the lines of code within the function in example 2?

    Complex calculations, tricky control flow statements and the like deserve a high-level explanation; everything else deserves proper naming.

    • MohammedShoib

      some times writing big function names for simpler task , may cause spelling mistakes and in worst case it may cost time too.

      instead we can do like this

      //pass image or file name
      function getExtension($image_name) {
      $pieces = explode(‘.’, $image_name);
      return $extension = array_pop($pieces);
      }

      • webarto

        Your arguments are invalid.

        echo pathinfo(‘image.png’, PATHINFO_EXTENSION); # png

      • Divan4ik

        what if it’s just a filename ‘in future’? not in file system

      • Trevor

        If you are actually typing out the names of all of your functions when using them, its time to upgrade to a new IDE–one that has intellisense. Long function names should not be a problem and short function names can cause worse problems than spelling errors; you might end up using the wrong function. Here are a few examples that demonstrate the ambiguity caused by short function names and the clarity provided by longer function names:

        GetApples();
        GetAllApples(); // If this gets all apples, what does the previous function do?
        GetApples($TreeId); // Are we filtering by the tree id, or are we doing something else with that parameter?
        GetApplesByTree($TreeId); // Here’s a good function name
        GetApplesWhere($filter); // Kind of vague, but may be appropriate here
        GetApplesByOwner($OwnerId); // Should we be passing in an owner object or owner id?
        GetApplesByOwner($OwnerObject); // Should we be passing in an owner id or an owner object?
        GetApplesByOwnerObject($OwnerObject); // This one’s more clear
        GetApplesByOwnerId($OwnerId); // So is this one

    • f you

      you are stupid not a programmer.

    • http://www.facebook.com/vinicius.gati Vinicius Gati

      in fact, great code, don’t need comments

      • Ryan Flores

        I completely agree with you.

    • icaine

      lol guys… no need for comments nor extra functions…

      $imageExtension = pathinfo($imageName, PATHINFO_EXTENSION);

  • http://webdesignergeeks.com Ajay

    One the grate post in my life i have seen, It helps all noobs to boost up their coding stander.

    Thanks a lot for sharing and i will do the same…… “You’re Not Sharing”

  • cp

    why the hell does the title say ‘php programmer’… this is just general practice.

    The title is only further perpetuating the idea that all php programmers are lazy/bad coders

  • MohammedShoib

    This article and comments are good, got lot of things to learn.

    thanks for article and comments.

  • squary

    nice thoughts!!!!!!!!!!!

  • http://syropia.net Collin Henderson

    Thanks for this. I too often fall victim to many of these mistakes, because I’m so often only writing code for myself. Certainly something I need to work on!

  • The Insaint

    The only thing that really is important to me, is proper (and therefore readable) indents and brackets:

    if(something == true)
    {
    do something
    }
    else
    {
    do something else
    }

    There is nothing I hate more than having a code with the brackets diagonal and make it somewhat unreadable and unlogical. Even if there will be a few extra lines of “code” it helps to immediately see the blocks and gte the overview more quickly.
    Everyone should do this.

  • The Insaint

    Damn, why aren’t the indents displayed properly? This makes my post useless … :(

  • Paul

    Half of this is bollocks

  • http://roes-wibowo.com Roes Wibowo

    When I make PHP program I’m not comment it ’cause I’m always gives function name that is familiar (espesially for me) and always use OOP structure. :)

  • vikas

    wow! what a advise.thanks

  • GamBit

    Thanks for this tutorial.

    One think that i realy hates are curly braces in the next line.

    This example ist OK:

    This example ist NOT:

  • myshadowself

    I like to use Hungarian notation for my variables so I always know not olnly what they refer to, but also the kind of data they hold.

    EG:

    $oUser->iUserId
    $oUser->sUserName

    oUser is an Object holding User data
    iUserId is the User’s ID, which is an INT value
    sUserName is the User’s Name, which is a string

    Simple – but makes the code self commenting.

  • http://irie-design.fr dready

    I really enjoyed the reading, i will get back to it :D.

    Thanks.

  • http://www.thosedewolfes.com/ Mike DeWolfe

    This is a great piece. I’ve been programming in PHP for 15 years and I’m reluctant to call myself an “expert” programmer. I’m always learning.
    One thing I’ve seen happening in coding is the overuse of Development Patterns. If your goal is to create a glorified “Hello World” script, a dozen lines of code or less in entirety is just fine. I’ve seen code that leans on the various flavors of MVCs for no reason other than formality.
    As for planning: you can’t do enough planning. We had project managers (read: sales managers) at one company that would flip out if you wanted to spec out a project. I got them to give us the time to carry out a project with the appropriate amount of planning front loaded into that project. The end result was excellent and the project duration was the same. All we did was slide labor from the false starts and re-dos of code and put that time into project planning. The project managers had to be more involved (they had to explicitly tell us what they wanted) instead of the “build-then-plan” approach that left them free. The developers felt better about the work because what the developers did drove the project closer to completion. I always felt despondent that I had make several versions of the same application because of the push-back from the project managers who needed to see it before they decided if they wanted it. All those prototypes in lieu of planning sucked time away from good security, clean code and fleshed out features.

  • blacksonic

    U skipped mentioning testing, solves a lot of commenting

  • Mahmoud Gamal

    “Dude”,Really Great Post.

  • leon

    good tips not only work for php but also other languages ,thanx

  • Krista Tocchio

    Sometimes I contemplate if folks truly take time to write something original, or are they only just dishing out words to fill a site. This certainly doesn’t fit that mold. Thank you for taking the time to write with awareness. From Time To Time I look at a page and question whether they even proofread it.Fantastic work with this article.

  • http://kori-designs.com Leah

    I tend to over comment my blocks of code. Even if the code is obvious I sometimes look back at it unsure of what it did and the extra commenting just saves me the trouble. Most people don’t look at the code of my projects besides a few people anyway.

    Example (from my Greek nouns conjugator project):

    //Display the definition
    // $(this) = $(xmlDoc).children(“dic”).children(“entry”).children(“greek”) by this point in the code
    $(“#def”).html($(this).children(“english”).text());

    //If the type of word is a noun
    // greek = $(xmlDoc).children(“dic”).children(“entry”).children(“greek”)
    if(greek.attr(“part”) === “noun”) {
    // run code for this here (obviously not posting for brevity)
    }

    So even though by looking at the code it seems relatively obvious what it does, I commented the lines anyway with the extra information. IMO there’s no such thing as too many comments provided that they’re actually helpful ;)

  • http://redearmedia.com/ Ryan

    Hit the nail on the head – especially the towards the end: “I know that when I look back at some of the code I wrote in the past, I’m horrified.”

    That made me giggle.

    Thanks!

  • http://www.techispeaks.com Kathirason

    something a programmer should think.. great post..

  • http://www.inspiraghtech.com Inspiragh

    This means that that we are good at inspiragh…we definitely have our bad habits too. lol. wonderful post though

  • ramesh

    wow.. excellent article.. i see my 4.8 years of IT experience on this article. Keep Rocking..

  • Tanax

    I disagree with the curly brackets. If it’s only 1 line of code, say.. an echo, then I think it’s easier if there’s no brackets.

    Consider this:

    if( something ) echo ‘no brackets’;

    if( something else )
    {
    echo ‘with brackets, indentation does not work here in nettuts comments’;
    }

    Which is easier on the eye? I prefer the first one. There’s also this:

    if( something entirely different )
    {
    echo ‘hi’;
    $x += 13;
    return true;
    }

    else return false;

    Using brackets in the “if” due to multiple lines and no brackets in the else due to single line.

  • Marko from Belgrade

    Great post! Truth and nothing but the truth!

  • http://php-training-free.blogspot.com/ Sanj2cool

    Well as most of the other novice i don’t comment on my code too much but now I Sanjay hereby swear to make comments in any situation where the purpose of the code I’ve written isn’t immediately apparent.

  • http://www.facebook.com Jay webmaster

    nice post! thanks for posting this article, there are such phrases or lines that hits me to makes the codes be better.

  • http://www.lancebridge.com Chat

    Guilty… majorly on the commenting and laziness.. agree on the planing before coding but that is usually on the whiteboard and never gets to comments…
    Guess its time to change and be consistent..

    Thanks for a nice write up!

  • Gulab Mehak!

    Thank You very much for these advices.
    Had no idea about comments and others as well.
    :)

  • joey

    love it:)

  • http://ejelome.com/ EJelome

    I’m a bad PHP programmer because I don’t like PHP (I liked it 2 years ago).
    If you don’t like the language you’re using, you’ll never be good at it anyway.

    I’ve been doing PHP and WP for more than 2 years now and if I could only turn back the time, I’d should’ve started with either Python (Pyramid), Node.js (Express), Ruby(RoR), or C# (.NET).

    PHP was my first programming language but sad to say, it didn’t brought me good foundations to learn and understand programming: it was rather, confusing ($, , or my_func?), messy and the free source codes on the internet were inconsistent (some one-liner, some has no curly braces, some are tag-soup wrapped with spaghetti php, and so forth).

    That’s why, I’ll never become a ‘good’ PHP programmer.

    • http://ejelome.com/ EJelome

      Correction: …it was rather, confusing ($, <?php, myfunc or my_func?, etc.)

      [Wish: I wish there's an edit or delete button]

    • Nadav

      “free source codes on the internet were inconsistent (some one-liner, some has no curly braces, some are tag-soup wrapped with spaghetti php, and so forth).”

      That’s the good thing in PHP. It can be customized by anyone. I don’t like languages the everything is codded the same way. It looks like anyone is doing exactly the same thing.

      Take a look at PHP again. Think about it now, when you know other languages.

  • Nadav

    God.

    Everything, everything here is true about me. I have learned so many things from this amazing post. it’s just amazing.

    Thank you Jason.

  • http://phpro.ir saeed

    “You Don’t Follow a Development Pattern”

    I am fluent in object oriented programming, but I do not know how to properly use it to project.
    What is the correct way to use object oriented? Witch pattern?
    Can you give me a reference or tutorial?