All coders are junkies

Every coder is, in my opinion, a borderline junkie.

Every programmer I ever met has been a bit of a self-absorbed addict, chasing down the next clever algorithm. We're cerebral adrenalin junkies, hooked on the punch of endorphins when we execute a script successfully. When we write a test that passes.

The better ones are addicted to color. If a green bar was heroin, we'd be shooting it into our veins.

I suppose there are worse things to be hooked on.

The best part about being a disciplined coder

In order to be disciplined, you have to be undisciplined. It's an unavoidable rule.

The best part about being a disciplined coder is that it's okay to make stupid coding mistakes. That's how you can tell if you're disciplined.

You probably already know you're going to make coding errors for the rest of your life. If you recognize that  failure is a normal characteristic of  development, you're doing better than half the developers out there. If you realized that it's more important to learn how to find your own mistakes than it is to avoid them, you're doing better than the next half. When you're able to identify your mistakes and own them, privately and publicly, you're doing better than 90% of the rest. 

Stop worrying about the ideal structure of your code. Start worrying about knowing which parts of your structure are the most error prone. Start worrying about the places where you make your boneheaded mistakes. Start worrying how to stop doing the boneheaded mistakes.

And get to work on one of them.

Why so many developers belong in the basement

I am a programmer because I don't like talking to people. Not because I don't like people, but because I'm not the most adept at conversation. For years, I've misspoke or spoke to myself and people inferred I was disturbed. I suppose some thought I was high. Sometimes I may have been, too. Regardless, I am not always held in the highest of esteem because of this annoying habit.

This presents a problem because I like talking. But sometimes when I talk, it's at the wrong moment, or in the wrong context, and suddenly eyes fall on me.

Sometimes, I'm far more comfortable talking to myself. Yet, there are few legitimate reasons for talking to yourself. Praying is one; BlueTooth is another. I do neither.

This is one single behavior. Just one. Yet, if I eliminated it, no strangers would ever assume I was homeless. I found it striking that I could change so many people's opinion of my simply by talking less.

Another principle of life.

Marking a function as a test in PHPUnit

I don't like the policy of prepending a method name in order to make it testable. For instance, suppose I am testing the method getName(). My test might look like this:

  public function testGetName()

By adding 'test' at the front of the method, I have obfuscated the method, and it takes a little bit longer to know what I am testing.

That's why I like to use annotations instead:

   * @test
  public function getName()

If you add the annotation @test to your doc block before the function, PHPUnit will recognize it, and execute the method as a unit test.

Apple has more failures than successes

There is a reason why Apple is the biggest company in the world: it keeps going back to the drawing board. In fact, if you lined up Apple's success stories beside Apple failures, you would find out that there are far more flops than flourishes.

Remember the Newton (the first PDA to hit the market, which lasted perhaps 12 minutes before being dumped), or Macintosh TV. Do you remember the Mac Mouse, the round apple turd of a mouse that everyone hated?

There are countless flubs. But Apple owned these failures, which means that they kept pumping out new ideas. You may recall that a few of them actually had mild success. Or are you still using Windows Media Player?

Here's an excellent infographic that shows the history of Apple blunders and successes:

svn connection refused - how to fix

This is a message that most of us don't want to see:

svn: Can't connect to host '': Connection refused

If you can't connect to your svn repository from a different server, then you've likely crashed svnserve.

Try this command:

$ sudo svnserve -d  -r /path/to/your/svn/repository

Oracle VM crashes - how to fix

Runtime error opening 'C:\Users\You\VirtualBox VMs\Linux Foo\Linux Foo.vbox' for reading: -102 (File not found.).

If you're using Oracle's VirtualBox, this might happen to you sometimes, such as when you shut down your computer with programs still running, and the shutdown process hangs. Although it look daunting, it could be an easy fix:

  1. Shut down VirtualBox completely.
  2. Open your VM folder (use the path mentioned in the error message)
  3. You are supposed to have a .vbox file there, but you will probably have a .vbox-tmp or .vbox-new file instead, or at least a .vbox-prev file.
  4. If you see one of these, and you DON'T see a .vbox file, then rename the tmp/new/prev file to have a .vbox extension
  5. Restart VirtualBox

What's the difference between preventDefault() and stopPropagation()

preventDefault prevents the default action that was intended to occur. If you click a button, preventDefault() will stop the button from firing any events, such as a form submit. Use preventDefault() if you want to stop your form from being submitted:

<button id='myform_button'>Submit</button>
   if ( formIsNotValid() )
      return false;

stopPropagation does the same thing as prefentDefault(), but it also stops the event from bubbling up the event chain. If you have your button inside a div which also has a click event, preventDefault() will only stop the form from submitting. But the click handler for the wrapper will still fire. If you want to shut down everyting, you have to use stopPropagation().

How to fight patent trolls

If you haven't heard about it yet, checkout Ask Patents, a site dedicated to taking the war to the doorstep of patent trolls.

According to Joel Spolsky, software patents are ludicrously easy to file, and ludicrously broad in their cope.

Since patent examiners rely so much on keyword searches, when you submit your application, if you can change some of the keywords in your patent to be different than the words used everywhere else, you might get your patent through even when there’s blatant prior art, because by using weird, made-up words for things, you’ve made that prior art harder to find.

... Have you ever seen a patent application that appears ridiculously broad? (“Good lord, they’re trying to patent CARS!”). Here’s why. The applicant is deliberately overreaching, that is, striving to get the broadest possible patent knowing that the worst thing that can happen is that the patent examiner whittles their claims down to what they were entitled to patent anyway.

Thus, we have Stack Exchange stepping forward with Ask Patents, which presents patent applications that are likely bullshit. If you, as the reader, can find examples of prior art (prior examples of the technology in application), then you can upload the example to the site, and it can be used by the patent office to deny the patent claim.

Check it out. It's easier than you might think. The very first patent I looked at was a blatant attempt to patent ecommerce. Anyone with a shopping cart system would be at risk if this patent was accepted.

PHPUnit - assertInstanceOf not working

This trips me up again and again, especially working in Symfony.

When you use assertInstanceOf in your Symfony2 tests, don't forget that the namespace must be respected:


namespace MyProject\ThisBundle\Tests;

class MyMainClassTest 
   * @test
  public function factories()
    $factory = $this->getMyFactory();

Sorry, that will fail. You are in namespaces. You have to do use the full namespace of the class you are looking for:


namespace MyProject\ThisBundle\Tests;

class MyMainClassTest 
   * @test
  public function factories()
    $factory = $this->getMyFactory();

Mysql command to show database you are using

I always forget which database I am currently working on, in a command line environment. Fortunately, Mysql was thinking of schmucks like me.

mysql> select database();
| database()  |
| my_database |
1 row in set (0.00 sec);

Using doctrine's getReference() with fixtures

If you are implementing fixtures, and creating or updating a Doctrine entity, and setting relational data (ie. One2Many, Many2One, etc), you may run into problems.  Doctrine might attempt to insert relational data, when it should be updating relational data.

Suppose you are attempting to create an university Course entity, with a related university Department entity:

$em = $this->get('doctrine')->getEntityManager();

$course= new Course();

$dept= $this->get('university.department.service')->findOneById(SOME_DEPT_ID);


The Problem That Can Arise

Doctrine is 'smart' and knows about Relationships. If configured to cascade the department data, it should save (INSERT or UPDATE) the department along with the course.

However, in the code example above, Doctrine will sometimes attempts to insert the related department, rather than update the department. This is a problem, and you will encounter an error message like this one:

ErrorException: Notice: Undefined index: 000000005118577900000000245708ca in /home/project/vendor/doctrine/lib/Doctrine/ORM/UnitOfWork.php line 2152

This error message is  complaining because it's attempting to insert a new Department, when it should be updating the Group. More specifically, the (inserted) Department is colliding with an existing department in the database.

The Solution: EntityManager's getReference()

$em = $this->get('doctrine')->getEntityManager();

$course= new Course();


In the above example, there isn't an explicit DB fetch, and Doctrine is smart enough to avoid the MySQL read in this case. As a result, the second version is more efficient.

More Reading on this

It's important to read up and understand what Doctrine is doing here, and know how to best use Doctrine Reference Entities.

Four Things To Consider When Hiring A Developer

Things are a lot different today than there were ten years ago. This is especially so in the IT world, and companies need a different type of developer than they used to. So why are they still hiring like it's 2003?

Here are four things that will help you find the right person for the job.

Creativity is not a good thing

For god's sake, can we all stop advertising for programmers who are creative? It used to be that creativity was essential, but that was when the technology was still in its infancy. Today, we have frameworks over top of frameworks. We have APIs. We have jQuery. We have SASS. We have Symfony. We have doctrine. We have open source projects everywhere.

Ten years ago, we needed creative developers because that was our main problem: we need things created.

Not so today. There are few problems left that haven't been solved. That's why a creative developer is the kiss of death. He's more interested in building a novel solution than finding a correct solution. He's less interested in doing the legwork to find an existing solution, understand it, and use it.

A creative developer can lead you down the path of in-house frameworks that do one or two things really well, and do everything else terribly. A creative developer can shackle you to his own creation, and every new hire loses a month trying to learn a new, incomplete, buggy framework that probably has no documentation. And, worst of all, creative developers don't stay in one place very long. When they leave to follow the next Big Shiny Thing, they leave their creation behind, and a team that has to figure out what to do about this monstrosity.

A creative developer is a dangerous developer.

Resourcefulness is the new badge of honour

Don't hire someone who tells you about his ability to design solutions. Hire someone who tells you about his ability to find a solution. For every problem, there is already a solution available online. There are very few widgets that haven't been built. Trust me: every hour spent finding an available widget or module, is three hours spent trying to build it yourself, debug it, and maintain it.
One of the main strengths of a good developer should be his ability to understand the problem, then find a solution for it quickly. Nine times out of ten, the solution is already out there. That's why efficient teams are teams that go to the net.

Google first. Design second.

The more frameworks, the better.

The best developer is one who is comfortable working within an existing set of protocols and procedures. Coders who have spent their time working with an MVC framework are reliable, predictable, and will give you higher quality code.

Their code will be more standardized, which means that it will be easier to test, and easier to maintain. When they leave, if their work is inside an established framework, new hires will be able to understand it better.

When you interview a new developer, make sure they tell you what established frameworks they've used. Make sure they describe how they've used them, which ones they prefer, and which ones they didn't. This question will tell you a lot about whether or not this guy is a team player who works withing established protocols, or a maverick, who would prefer to code it like a cowboy.

Testable code is essential

10 years ago, the main principle of development was GIOTD: Get It Out The Door. There was less QA. There was less automated testing. But today, it should be a different story. There is enough evidence from empirical studies to conclude that code written with unit and functional tests is better than written without.

Developers should have experience with various test frameworks. More important, they should understand why test are written in the first place. They should have an opinion on TDD - Test Driven Development. Whether or not they agree with it, they should be familiar enough with the concept to formulate an opinion.

Defining rules for Red, Yellow, and Green status bars

Continued from: Three things that make successful red-yellow-green status bars

When setting the status of a project metric (tickets closed, lines of code written, % build passing, etc), it's essential that you have a clear and consistent policy. If one metric is green, it should mean the same thing the green means for another metric.

One person's green can't be another person's yellow. The only way to accomplish this is to have a core set of guidelines that determine the status of the metric, and this core set has to be independent of the metric being measured:

Fair Measures of a Metric Status

Color StatusUsed whenever one of these is true:
  • You are not meeting target goals* for two or more consecutive weeks
  • You have had a catastrophic failure of the week and little got accomplished
  • A new issue arose during the week that makes the possibility of reaching the final goal highly unlikely
  • You are meeting target goals for one consecutive week
  • You are failing to meet target goals for one consecutive week
  • You have discovered new issues that have yet to be assessed, but could put the project at risk>
  • You are meeting target goals for two or more consecutive weeks
  • You have made a significant breakthrough or leap in this week that makes the goal highly likely

* meeting the target goals: you have accomplished the minimum amount of work required each week to complete this project. Note that this amount is continually changing, depending on the amount of time remaining, and the amount of work outstanding

Three things that make a successful Red Yellow Green Status policy

One of the more popular Agile techniques these days is the incorporation of a simple Red, Yellow, Green status for your project. And, by extension, simple statuses for the metrics that track your project.

But the problem with a RYG method is that it quick descends into blind pessimism or blind optimism. If the criteria for setting the status isn't clear, it will trend towards the general mood of the team. A team with high moral will call things green. A team with low morale will call things red.

If the goals for the project aren't clear, it will trend towards the general nature of the team. An optimistic team will have more green status bars. An older, grumpier team will have more red status bars.

A lazy team will have more yellow status bars.

There are three things that are essential for a working RYG Status policy:

Defined and measurable project goals: If you can't even state what makes a project successful, how will you ever know if you are on track? If you can't state what it will take each week to get to a successful project, how will you know if the week was successful?

Transparency: The status chart should be visible to all, and the reasons for each status color should be clearly communicated. Never leave the status color up to a single individual, unless you have clear and objective measures that everyone understands.

Policy: The choice of what makes a metric green needs to be clear and consistent. A green status for one metric should represent the same condition as a green status for another metric.

Continued: Defining rules for red, yellow and green

A template that extends another one cannot have a body. Woe is you

If you are new to twig and symfony, you are probably going to come across this error message in a hurry:

A template that extends another one cannot have a body (Twig_Node_Text(data: '}')) in "ScribeUserBundle:Main:user.template.twig"

When you get this message, you have done one of two things:

1. You have added raw text to a twig file which extends another twig file:

{% extends CoreUserBungle:Main:index.html.twig %}
>!-- html comment here -- WHOOPS THIS CRASHES THINGS. -->
>!-- everything you write MUST be inside a block -->

{% block well_well_this_is_safe_content %}
    Safe text! No crashes!
{% endblock well_well_this_is_safe_content %}

2. You say you didn't add raw text to a twig file, but you did, and you don't know it.

{% extends CoreUserBungle:Main:index.html.twig %}}

{% block html comments %}
>!-- This SHOULD be working but it isn't. -->
>!-- NOW, what's the problem, for chrissakes -->
{% endblock html_comments %}
{% block well_well_this_is_safe_content %}
    This might work, if it weren't for the extra closing bracket 
    at the end of line 1 ...
{% endblock well_well_this_is_safe_content %}

Using int in your doctrine entity will break symfony2

If you define your doctrine yml file using shorthand 'int' instead of 'integer', you will be in for a world of annoyances.

Suppose you create an entity named students, and one of the database fields is age. In the yml, you mave have done this:

  repositoryClass: YourApp\StudentBundle\Entity\StudentRepository
  type: entity
  table: students


      type: in


  lifecycleCallbacks: {  }

Without complaint, doctrine will generate your entities for you, but they will contain the following declaration:

 * @var int
function setAge(\int $age)

This is going to throw an error, when PHP comes across it and has no idea what the 'int' class is.

Always use 'integer'.

An example of how to set up SSL on your virtual machine

If you are developing in a VM, you will usually want to duplicate secure sites, too, especially if you are doing maintenance on existing websites. Setting up SSL on your VM In order to access your development site under https, you will need to install a self-signed ssl certificate on your virtual machine. It's a straightforward process.

Set up your certificates in your apache2 directory

Set up a directory to hold your certificate, and then generate your pem file.
$ sudo mkdir /etc/apache2/ssl 
$ sudo /usr/sbin/make-ssl-cert /usr/share/ssl-cert/ssleay.cnf /etc/apache2/ssl/your_site_name.pem 

Create a conf file for your ssl

$ sudo touch /etc/apache2/sites-available/your_site_name-ssl.conf

Edit your conf file

Add the following to your_site_name-ssl.conf:

  DocumentRoot /var/www/path_to_site_document_root
  ServerName your_site_name
  ServerAlias your_site_alias
  SSLEngine On
  SSLCertificateFile /etc/apache2/ssl/your_site_name.pem 

Verify that you have ssl set up

*a2enmod* enables/disables apache ssl
*a2ensite* makes sure that there is a symbolic link in /etc/apache2/sites-enabled to the specified conf file

$ sudo a2enmod ssl 
$ sudo a2ensite your_site_name-ssl.conf 

Restart apache

Check the configuration of your apache file, and see if you have added any errors to your conf file. Apache will not restart if you have errors in your file.

$ sudo apachectl configtest 
$ sudo apachectl restart 

How to change root mysql password

1. Login to mysql, and type the following command:
$ mysql -u root -p

2. Switch to the mysql database:

mysql> use mysql;

3. Change password for user root, enter:

mysql> update user set password=PASSWORD("NEWPASSWORD") where User='root';

4. Reset the privileges:

mysql> flush privileges;

Using Symfony2 on a MAC

If you are programming in an OSX environment with symfony2, you will likely come across the following software error:

> Fatal error: Call to undefined function Symfony\Component\Form\Extension\Core\DataTransformer\intl_is_failure() 

As of PHP 5.3, intl is a core extension, but it doesn't ship with OSX. Symfony is supposed to account for this in a stub re-implementation, but there appears to be a bug in play. However, there is a workaround.

First, ensure your autoload.php file contains:


Then, you have to make sure that the stub/functions.php file is in play:

   require_once __DIR__.'/../vendor/symfony/src/Symfony/Component/Locale/Resources/stubs/functions.php';

That keeps you running on a Mac.

How to document a file using PHPDoc

h3. Documenting the file

If the first DocBlock in a file contains a *@package* tag,* it will be used to document the file, except when it immediately preceds a class declaration.

This is a file description:
 * my description
 * @package foo

This is not a file description:
 * this is a file description
 * @package foo
class foo{

Neither is this:
 * this is a file description
 * without @package
... some code ...

Why is tar so annoying?

I don't know what's worse--the fact that after 15 years of using tar I still can't keep the flags straight, or that after 15 years of technological advancement I'm still mucking with tar flags that were 15 years old when I started.
 ( - there can be only one )

Can someone please tell me why the tar command is the worst command in the world? Why did the founders of command line wizardry choose to make the most useful command in the world so cryptic.

The tar command has to be the most frustrating command in the world, if measured by by two vectors:

likeability(x) = ( usefulness(x)^2 - difficulty(x)^2)^1/2

In other words, the more useful the command is, the more likeable it is, but this likability is controlled by how difficult it is to use.

The tar command minimizes likeability because it's annoying difficulty is almost equal to how wonderfully useful it is.

Note that when a command is less useful than it is difficult to use, it's likeability becomes an imaginary number. That sounds about right.

Symfony fixtures - doctrine entities only!

This is less a gotcha than a complaint about the DoctrineFixuresBundle. You cannot set a non-entity as a reference.

 * This is the standard example found at
 * http://
 * With a few comments added
class LoadUserData implements FixtureInterface
    public function load(ObjectManager $manager)
        // this is a typical approach
        // to making a doctrine fixture
        $userAdmin = new User();
        $this->addReference('admin-user', $userAdmin);

        // but, if you try this approach
        $userAdmin2 = new \genericUserClass(); // not a doctrine entity, not namespaced
        $this->addReference('admin-user-2', $userAdmin2);  // NOPE! ERROR!


I understand the strictness. I understand that it makes logical sense to restrict a doctrine fixture generator to passing around only doctrine entities.

But logical sense doesn't always equal intuitive sense and, if the class has an interface that is acceptable to doctrine references, then it should be allowed.

This strictness makes it more difficult to refactor legacy systems into Symfony2. Existing classes, heavy with business logic, become more difficult to use. I find that I have to do something like:

class LoadUserData implements OrderedFixtureInterface,ContainerAwareInterface
    public function load(ObjectManager $manager)
        $userAdmin2 = new \genericUserClass(); // not a doctrine entity
        $doctrineUserAdmin2 = $manager->getRepository("CoreBundle:UserClass")
        $this->addReference('admin-user-2', $doctrineUserAdmin2 );  

Certainly there are plenty of arguments why you should stick to only doctrine entities. But it inevitably makes it harder to structure and integrate symfony2 and legacy systems.

Just my two cents. Which is what this opinion is probably worth.

Critical Bug Fix Checklist

When I have to address a critical bug, I try to approach it warily. Even more, I try to approach it like the bug is a plane and I'm about to fly it across the country.

To do that, one of the tools I use is a checklist, that I force myself to walk through. I've found that a bug fix checklist has lowered the number of returned defects by 60%. That's a major increase in productivity.

This is my checklist below for fixing a critical bug, and deploying a patch to the production server.

Critical Bug Fix Checklist


  • I have identified the branch to which this patch must be applied
  • I was able to duplicate the bug in the original environment
  • I have duplicated the bug on my local dev environment
  • I was able to track the workflow through my debugger to the source of the problem
  • I have described the bug fix to a second person, who concurs with my conclusion


  • Code comments were added appropriately, explaining the fix
  • The bug ticket/tracking number referenced in the code comments
  • I reviewed the  SVN diffs on changed code
  • A second developer has looked at the SVN diffs
  • I have shown the fix to the person who reported the issue

Unit tests & QA

  • I have written unit tests
  • All new unit tests pass
  • My changes did not break any existing unit tests
  • If no unit tests were written, and unit tests can be written, a ticket has been filed as technical debt, to complete the tests, and the ticket is linked to the ticket I am working on now
  • I have manually tested the fix and got the expected results
  • I have tested on IE
  • I have verified that no javascript errors 
  • I have described a test case on the bug ticket, expected results, and areas of impact

Documentation & Bug Ticket

  • A description of the bug cause was added
  • I have documented on the ticket the possible areas affected
  • I have identified the root cause
  • I have indicated how this situation could be avoided in the future

Before  Deployment  Checklist

  • I have verified the fix is in the correct branch
  • I have rebuilt this branch on the testing server
  • The fix has been verified on the testing server
  • I have verified that there is no currently non-releasable patch in this branch that cannot yet be uploaded

Post Deployment Checklist

  • I have verified which sites and servers are to receive the upload
  • A dry run has occurred
  • I have uploaded to a single site/server to verify
  • I have uploaded to all servers
  • I have verified the fix on the original site on which the issue was reported
  • An email has been sent to the relevant parties or representatives, indicating that the issue has been resolved, taken live. The email also identifies the area of concern and what users should now expect to see. 

What does " Uncaught exception 'PDOException' with message 'You cannot serialize or unserialize PDO instances'" mean?

If you are running unit tests in PHP, you may get the following hair-pulling error:

Uncaught exception 'PDOException' with message  
    'You cannot serialize or unserialize PDO instances'

It means that something with a doctrine/pdo went wrong in one of your tests. Since serialize does not work on pdo-classes, it prints out this message. If you want doctrines/PDOs message, run only the one test with process isolation turned off and you will get the error-message.

Software development in a nutshell

Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning. Rich Cook

Second principle of code review: write an ode to the code

<< Previous Article: 'The First Principle of Code Review: Check Yourself at the Door'

Stop me if you heard this one. You have written a hundred lines of code. You pass it off to a code reviewer. He tears it to ribbons.

He tells you to restructure some conditionals. He tells you that an algorithm would be better written another way. He tells you to use different classes than the ones you are using.

Then you ask him if he knows what the code does. And he doesn't.

As autistic coders, we are rarely so bold as to challenge the reviewer about his knowledge of what our code does, and we rarely ask this simple question.

But we should.

And, when you are reviewing someone else's code, you should be asking the same thing to yourself: 'What is the purpose of this code?'

Above all else, a code review should be used to determine if you have written understandable code. Given the comments, given the structure of the code, given the flow of control, are you able to say back to the coder what his code does?

If you can't, then one of two things is true:
  1. The code fails the review
  2. The code reviewer fails the review
 In either case, however, the code review should come to a full stop. There is no point in critiquing code whose purpose you don't understand.

There is no point in giving pointers when you don't know the point of the code.

Make sure you can briefly describe the purpose of the code. If you don't understand what it is supposed to do, how do you know it's does what it's supposed to do?

If you don't understand why it is structured the way it is structured, how do you know if your structural suggestions are correct?

The best code comments I have seen

 *  This probably returns the id
// probably??
function getRecordId(){

This code comment was written by John. Every company has a John. He's the master programmer who wreaked havoc years ago at the company. There is no module that doesn't have the finger of John in it. And, years after he has gone, there is no problem in the code that isn't blamed on John.

// Autogenerated, do not edit. All changes will be undone.

John added this to a particularly long and complicated method. This would have been sufficient to deter code meddlers, but he also added a comment at the end of the method:
// I find that if you want to keep someone from messing 
// with your code, add a comment that it's auto generated.

This is my all time favorite:

// 07/12/08 - Temporary logging for debug purposes
// 01/11-10 - temporary????

And, of course, there was a lot of this:
catch (Exception $e){
  // annnnd throw it down a hole