New Website

I've made a new website, as lynx.io is dead. You can find it here: http://macr.ae/—it's similar in format to lynx.io, but has better articles, and they're all written by me.

JavaScript disabled

While it will still mostly work, a lot of this site's functionality relies on JavaScript - please enable it for the best experience.

Bad Coding Practices to Avoid

One of most annoying things I have to face when coding is other people's bad code. I consider my own coding standard to be fairly good, but sometimes I have to work with code that hasn’t been coded well at all. Messy code is difficult to read, difficult to work with, and it can also slow your code down.

Naming

Everything should be named logically. For example, use $post for information about a post, not $var. Only ever use single character variable names (eg. $i) in loops. Consistency is almost as important as naming stuff logically; you should also standardise your variable names. I always use camel caps instead of underscores, so I would have $postName, not $post_name or $postname. This saves me time having to look back to remember what I called a variable.

For example, WordPress has a function called __(). Whose idea was that? It's not very descriptive, and I didn't even realise it was a function at first. When I did realise, searching __() on Google didn't return much!

Spacing

First, an example:

<?php
$data = new PDO("mysql:host=localhost;dbname=php,callum,newarray,array(PDO::ATTR_PERSISTENT=>true));
$data->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$res = $data=>query("SELECT * FROM config WHERE config='time'");
if ($res->rowCount()){while($row=$res->fetch()){if(!is_int($row->time):die();else:$open=$row->time;endif;break;}}else
die();
$today = time();if($today>$open): ?>

//some html here

<? endif; ?>

That’s horrible. I don’t even know whether it works, as I haven’t tested it. It took me a lot longer to write than normal code. Granted, it takes less disk space, but who cares? It’s ugly and impossible to work with. Again, be consistent with your spacing. If you're going to put tabs in one place, put them in all the other places, too.

Comments

Another bad coding practice I dislike is when the author of the code can't be bothered to leave comments. It only uses a few extra lines to leave a comment! It makes it extremely difficult to understand what is happening in the code, especially if it is long or uses stupid variable names. I cannot think of a disadvantage of not leaving comments - it actually makes it faster to edit if you leave comments. So seriously, always leave comments in your code.

// A comment

Always check for security flaws WHILE you're coding

It's far easier to check for security flaws (such as having vulnerabilities for SQL injections) while you're writing the code, not after discovering the vulnerabilities and having to trawl through thousands of lines of code looking for a single line of code.

Error messages

Your error messages should be useful. They should not just say "Could not connect", they should say (for example), "Could not connect to database: $db->connect() failed on line 426 of db.php". Look into debug`_backtrace, too.

There should be two levels of error messages: The error message that is displayed to you when something goes wrong, and the error message that is displayed to your users. To them, "$db->connect() failed" is jargon and doesn't help them at all.


Of course, sometimes you will struggle to stick to all of these, but attempting to do so will help you. Also, check out http://www.strauss.za.com/sla/code_std.asp (but remember that it is a joke!)

About Callum Macrae:

Callum Macrae is the founder of lynx.io and a JavaScript developer from the United Kingdom. He is currently writing his first book, to be published by O'Reilly Media.

You can view more articles by this author here.

Tags: php coding practice comments spacing rant

Comments

Parkzer says:

I dunno what you're talking about in the Spacing section of this article. That's similar to how I code, and not only does it save time, it also makes the code more fluid when I read over it.

Callum Macrae says:

All in one large block, with no white space? I find it unreadable.

~Callum

Parkzer says:

No, I still use line breaks and blank lines, I just don't use spaces. Taking your code for example, I would write:

$res=$data=&gt;query(&quot;SELECT*FROM config WHERE config='time'&quot;);
Callum Macrae says:

Interesting, to me that would seem odd and difficult to read. I also use too many line returns though

I guess that as long as it isn’t too bad and it’s consistent, everything is okay.

~Callum

Rob says:

I just agree with Callum about the spacing, i find it awful to read unless its structured clearly for me, one example is that when i open and close my php tages i must have a white space inbetween like so:

&lt;?php

   // Code here

?&gt;

I then space out any varibles out from any statements

&lt;?php

  $username = '';
  $password = '';

  if($username == 'Rob') {

    // Do something

  }

?&gt;

Sure it might take a little longer to structure but when i go back to update or change my code its just so much easier.

Garrett says:

What you tell users when reporting errors can be a problem. It's all fine and good when you're the only user to your website, but let's say you're doing something like:

mysql_connect($blah, $etc, $whatever) OR die(mysql_error());

Which I've seen done time and time again. Let's say your SQL server goes down while. Now every person who goes to your site will see an error message displaying your MySQL user name: one of few necessary pieces of information a hacker needs to get into your server. Using mysql_error() anywhere gives out sensitive information, so save that for your internal error reporting only!

Callum Macrae says:
define('DEBUG', false);

I've often seen or used debug constants and variables - they allow an easy way to switch between different types of error reporting :-)

~Callum

says:

Add comment

 

You can use markdown in comments (press "m" for a cheatsheet).

Enable JavaScript to post a comment

Markdown Cheat Sheet

# This is an <h1> tag
## This an <h2> tag
###### This is an <h6> tag

Inline markup: _this text is italic_, **this is bold**, and `code()`.

[Link text](link URL "Optional title")
[Google](http://google.com/ "Google!")

![Alt text](image URL)

![This is a fish](images/fish.jpg)

1. Ordered list item 1
2. Ordered list item 2

* Unordered list item 1
* Unordered list item 2
* Item 2a
* Item 2b

And some code:

// Code is indented by one tab
echo 'Hello world!';

Horizontal rules are done using four or more hyphens:

----

> This is a blockquote

This is an <h1> tag

This an <h2> tag

This is an <h6> tag

Inline markup: this text is italic, this is bold, and code().

Link text Google

This is a fish

  1. Ordered list item 1
  2. Ordered list item 2
  • Unordered list item 1
  • Unordered list item 2
    • Item 2a
    • Item 2b

And some code:

// Code is indented by one tab
echo 'Hello world!';

Horizontal rules are done using four or more hyphens:


This is a blockquote

Toggle MarkDown / HTML (t), full reference or close this