Thursday, July 18, 2013


Some people may think I have a perfectionism problem.  It all depends on whom you ask and what it relates to.  I am a computer programmer both by trade and hobby.  In the years I have spent in my chosen field I have learned a lot about it and have encountered endless amounts of code written by others.  One of the biggest pet peeves I have always had is poorly done code.  There are two aspects of this I would like to discuss: improperly formatted code analogous to the scribbles of a 2 year old child and illogical or non-reusable trash code.  While I don't mean to offend people most of the time I believe that if you are a programmer that falls into one or both of these categories you should sincerely reexamine your methods and try to change for your fellow programmers' sanity.

Problem #1: Code Vomit

Take a look at this code sample:

function whatsMyName($name) {


    if ($name== "Dick Grayson") {
       $name = "Nightwing";
        }

      return "Hello, {$name}!"
  ;

}

Did you notice anything wrong with that code?  Is it readable?  I know it's a simplistic example and much easier to read than many other things I've seen but the principle still holds true.  That code has excess whitespace everywhere, misaligned code, inconsistent operator separation, etc.  I see code like this more often than I would like and it drives me crazy.

Now take a look at this sample of the same code:

function whatsMyName($name) {
    if($name == "Dick Grayson") {
        $name = "Nightwing";
    }

    return "Hello, {$name}!";
}

Isn't that much more readable?  I know some people can't be bothered to care about formatting while they're trying to think through some solution to their programming task at hand but the unreadable code I see often has a secondary problem.  Many times where I see such illegible code I also see spaghetti code: code riddled with a complex control structure that has not been well thought out.  This sort of code reminds of an XKCD comic titled "goto":

goto

...which leads me right into the second aspect I want to discuss.

Problem #2: Brain Malfunction

Okay, this will be an extreme example but it is a real example from a project I worked on and I'm sure some fellow programmers have seen code that is just as bad if not worse.  There is actually a site dedicated to IT and code perversions called The Daily WTF for those who haven't heard of it before.  Anyway, on to my example:

The task at hand is to create three simple dropdowns for selecting a month, day and year.  As part of the requirement you need to automatically have the current date or a previously stored date selected.

Bad Approach:

$currentDate = date("Y-m-d");
$currentYear = substr($currentDate, 0, 4);
$currentMonth = substr($currentDate, 5, 2);
$currentDay = substr($currentDate, 8, 2);

echo "<select name=\"month\">";

if($currentMonth == "01") {
    echo "<option value=\"01\" selected>January</option>";
}
else {
    echo "<option value=\"01\">January</option>";
}

if($currentMonth == "02") {
    echo "<option value=\"02\" selected>February</option>";
}
else {
    echo "<option value=\"02\">February</option>";
}

if($currentMonth == "03") {
    echo "<option value=\"03\" selected>March</option>";
}
else {
    echo "<option value=\"03\">March</option>";
}

...<snip>...

Okay, I really didn't want to put the whole thing there - I think (hope) you get the point. If you, as a programmer, don't see anything wrong with implementing the task this way then you might want to re-evaluate your chosen occupation. This is a real example of some horribly inefficient/ridiculous code I have seen before. There is a significantly better way to implement the same feature and when I did so I slimmed a single 2000+ line file down to something more like 50 lines of code.

Better Approach:


$currentDate = time();

foreach(range(1, 12) as $month) {
    $month_name = date('F', mktime(0, 0, 0, $month, 1));
    $selected = $month == date('n', $currentDate);

    echo "<option value=\"{$month}\""
        . ($selected
            ? " selected"
            : ""
          ) . ">{$month_name}</option>";
}

...or sometimes (not debating whether this is good practice or not) I will even put code inline if the variables won't be used for anything else:

$currentDate = time();

foreach(range(1, 12) as $month) {
    echo "<option value=\"{$month}\""
        . ($month == date('n', $currentDate)
            ? " selected"
            : ""
          ) . ">"
        . date('F', mktime(0, 0, 0, $month, 1))
        . "</option>";
}

Taking this approach requires far fewer lines of code and is significantly easier to edit and adapt. Code such as this is much more reusable as well.

Friday, July 12, 2013

Agile Development Process

As a follow-up to a recent agile/scrum training we received from Platinum Edge we decided as a tech team to work on putting together some well-defined coding standards.  As an exercise during part of the training we were tasked with making a list of coding standards.  Our CIO/VP of Tech gathered the results of this exercise and then emailed the list of coding standards to everyone on the team asking for feedback.

The list of standards that was emailed contained some overly specific items like "Zend Framework" and some overly vague things like "Don't make it worse".  I gave this some thought and came up with some good standards that I believe would work well for at least our team if not most development teams.  My aim was to come up with some things that are not so specific as to limit your abilities but rather to keep code readable, maintainable, and easy to debug.  The standards are as follows:

Code
  • No superfluous whitespace/blank lines, whitespace should be clean and logical
  • Indentation should be logical and consistent
  • Functions/methods should do one thing and do it well
  • Use descriptive names in code
  • No naked control statements (if, for, while)
  • Use comments where code may be unclear but don't overdo it
  • Consistency above all
Practices
  • Fix problems you may find along the way (ie. take ownership of the code)
  • Follow standard security practices (eg. filter all input, register_globals off, server-side authorization, etc.)
  • Adhere to industry best practices and design patterns (eg. RESTful API's)
  • Document functions/methods (standard xDoc formatting)
Other
  • Logical version control (eg. no more than one feature per commit, feature branches, etc.)
  • Test Driven Development
The majority of the code we work with is PHP, hence some of the example references.  In general the standards you may choose should fit with your projects and your team of developers and should be agreed upon by everyone.  I would argue that pointless debates such as tabs vs. spaces shouldn't be set as a coding standard necessarily but instead should fall under something like my "consistency above all" standard.  In those situations just pick an option and stick to it as a team.
The term seems to be a relatively obscure one.  Even among fellow geeks and coworkers I seem to get a blank look when I refer to "yak shaving".  I'll tell you a little story about my day today:

I arrived at work this morning and found that some functionality on our internal CMS was timing out.  I immediately knew it must have resulted from changes to our codebase that I wrote and pushed live yesterday.  I recalled that with some requests being made to our API I would experience some odd and random timeouts.  With that thought in mind I decided that a better solution would be for requests to this particular API to be queued up and handled by a worker running on the server since the result of the API call is not important to the action being performed and can easily be handled in the background.  Fortunately this same idea relates directly with today's task of writing a worker to deal with synchronizing data in manageable chunks from our existing database to the new database we're going to be working with.  Knowing I wanted to employ the best strategies for solving this problem I started researching topics such as "advantages of workers over cron jobs" and "best practices for writing PHP workers".  After about an hour or so of research I decided that I would love to write a good blog post on the topic.  I realized that I had been meaning to set up my blog for quite some time and just hadn't taken the time to get it going.  I immediately headed over to Namecheap to get my domain registered and then I created my blog.  By this time I needed to make my way to the little boys room and assumed I would come back and immediately finish connecting my blog to the shiny new domain I purchased, however, along the way I ran into some coworkers who informed me that they were on their way to Subway since they are closing down after tomorrow due to doubled rent costs.  Obviously I had to join them and of course I also had to finish setting up my blog and create a post about yak shaving which further delayed my original task of trying to solve our task synchronicity problems.

The term "yak shaving" actually came about because of a 1991 Ren & Stimpy cartoon called "Yak Shaving Day" in which everyone spends their day doing ridiculous and useless things while waiting for a shaven yak to float by.  Yak shaving is doing activities which are either apparently useless things that lead to solving an original or larger problem or actually useless activities done while procrastinating something else.

Inspired by blog posts from zenhabits I have been wanting to gain better focus in my day-to-day activities and especially while at work.  I am a software developer and while the first form of yak shaving (apparently useless tasks leading to solutions) are a regular occurrence and are to be expected to happen, the second form can be an enormous time sucker.  I have found a number of things that can be helpful in using time more effectively and focusing better at work.  Here are two categories that come to mind:

  1. Internet Distraction:
    1. To deal with distracting websites and reading not related to my current focus I have been using Pocket to file things away for later when I have more time.  It's great because I can tag links to make it easier to find related things for when I want to research a specific topic and it helps me to keep my "too many tabs syndrome" under control (I'm still bad, just not 100+ tabs/5+ windows bad).
    2. Taking advantage of Chrome's multiple user/session support I have two sessions in separate browser windows: one for my work-related accounts and tabs and one for anything personal.  This helps more than you might think in keeping on task as long as you can keep other distractions away from your work browser window.
  2. Work Environment:
    1. I have been trying to strive for more simplicity and along with that comes a lot of decluttering.  I converted to Sublime Text many months ago for it's clean simplicity when editing code.
    2. I like music a lot.  For some time I used Spotify premium because it allowed me to listen to anything I wanted (and no distracting ads with premium).  I recently switched to Google Play Music All Access because it was cheaper and I already had a portion of my uploaded music collection on Google Play Music and this allowed me to listen to even music that none of the services has.  I have found that music allows me to focus better by keeping the ambient noise of the office away.
    3. We are an agile programming shop where I work.  We have had professional training and we try to follow the best agile methods that make sense for us.  There are a lot of tools for tracking user stories and tasks that need to be completed but we use Pivotal.  I have found that it is very effective to focus one one item at a time and we actually have a rule on our team that we are only allowed to have one story started at a time.
    4. Minimizing distraction is important.  There is a lot of wasted time when context switching and there is no such thing as multi-tasking.  While someone can do background-tasking nobody can actually do more than one task simultaneously that involves any focus or thought.  Having distractions that occur throughout your day will pull you away from your focus and train of thought and it takes time to get back to that focus.
Subscribe to RSS Feed Follow me on Twitter!