Skip to content

Be a Gangsta, Don’t Make Assumptions

We’ve all heard the old tired saying about asumptions, “When you assume you make an ass out of you and me,” but I see assumptions in many PHP applications. Being a loosly-typed language it is very easy to get caught in a situation where you are completely unaware if the data you are given matches what you exapect. I agree it’s tempting to believe that no one will ever use your code incorrectly or that the preceding code will make the necessary checks, but this is an assuption that you must not make.

Nothing works better than an example, so let’s take a simple function that generates a receipt string based on an array. Let’s take a look.

function getReceiptString($data)
{
    $str = "Name: " . $data['name'] . "\n";
    return $str;
}

The mistake the author of this code is obvious: they assume the variable $data is an array AND that it contains an element with index name. It’s easy enough to ensure an array is passed by adding array in the parameter list before $data, but this ony requires that the passed data array is actually an array. It makes no guarantee that ‘name’ is present. Here’s a better version of the simple getReceiptString() function:

function getReceiptString(array $data)
{
    if(!isset($data['name'])) {
        throw new Excetion('Name is required to create a receipt');
    }

    if(empty($data['name'])) {
        $data['name'] = "Unknown";
    }

    $str = 'Name: ' . $data['name'] . "\n";

    return $str;
}

We verify that the data being passed is an array, then check to make sure we have the required data. If we don’t have the data, we throw an exception. Whether this is exception is a decision you must make for you application/api, but you MUST verify rather than assume.

Carrying the Conversation to the Users

I will admit I should be preaching to myself on this one. Unfortunately I believe that I am in the minority when it comes to notification preferences on website actions. In a way it violates my subscription to the “Don’t Make Me Think” philosophy put forth by Steve Krug, but I tend to favor observation over notification. That’s a bit of an obscure concept so I will attempt to illustrate with an example.

When using a web application a common task is to upload a new document to a the application, usually including some metadata about the document in question, e.g. title of the document. I prefer that immediately after I upload the document I am presented with visual proof that the document exists where it should be. I dislike seeing pages that tell me my document is loaded. Do you think there is not a difference? There is, albeit a subtle one.

Notification messages are like phone calls. Other than recording them, there is no real way to prove what was said. Thus notification messages, in my opinion, are of less value than actual proof of what the message says. Can you have both? Absolutely. Take Gmail for example. When you move an item to the trash you get a little yellow message that tells you what you did. You can also easily see that the message is gone and, upon clicking the trash link, that the message has been moved to the trash.

However, as I said, my opinion is the minority. It’s a struggle for me to remember to include the confirmation messages, notification boxes, flashing title bars, etc. that alert the user to the status of their action, despite how much this fact contradicts my beliefs.

My intention of this blog post is merely to remind you–and of course myself–that continuing the philosophy of the conversation on to the execution of the application itself is beneficial to the user. Uncertainty on behalf of the user is definitely a recipe for support requests inquiring into the status of their action. Save the time you would spend answering these requests for implementation of new features or bug fixes.

Seven Things (There’s Seven of Them! Yipee!)

What kind of game is this? I don’t really know. But a badass developer and friend Daniel Cousineau tagged me to play, so here it is.

  1. I strongly dislike the taste of Avocados, guacamole, and other avocado derivatives. I cant put my finger on what it is about them–and believe me people I know have tried everything to get me to like them–I just do not like them. They don’t quite as horrible as cauliflower though…
  2. Grammar is by far my greatest hurdle. It is something I do not understand. I spend all day writing in foreign grammars (programming languages have grammar too, you know) but I never fully learned grammar in my native language. And, quite frankly, I am much too lazy to start now!
  3. I have no desire to know or learn anything about any celebrity. Most of my friends are completely fascinated and could tell you who is married to whom, which movie stars are pregnant, where Brittney Spears lives–or whether it’s Brittany, Brittney, or Britknee for that matter. But not me. Nothing bores me more than trivia about people I don’t know personally.
  4. In high school I was in an organization and part of a competitive step team. That’s right, I used to stomp my feet, clap my hands, beat on my chest in perfect rhythmic harmony with five or so of my closest high school friends. It was a lot of fun.
  5. I spent three months in California without a car while living 18 miles away from where I worked. My only timely transportation was my bicycle. I put a lot of miles in that summer.
  6. I drink a minimum of one gallon of water per day. Ok I admit I am running out of things to tell you. But judging from what I see around me this is a unique trait. I carry a gallon of water with me in the morning and by the end of the work day, it’s most likely empty. That’s a lot of water.
  7. I love to read technical books. One major perk of where I work is that I have access to a huge library where I can check out books on essentially any topic for four months at a time. I currently have a shelf full of books on linear algebra, discrete mathematics, and set theory. Yes, I actually like math. I never said I was “normal.”

So there you have it; seven interesting things about me that you might not have known.

Oh, here’s a little bonus for you: I like to participate only slightly it crazy memes like this, so I will not foward this to anyone. Maybe I’m not such a great participant. Or maybe I  just don’t know that many people that haven’t already done this…

“What are the Preconditions? Postconditions?” A Developer’s Question

This is the second part of my series on asking questions as a developer. Check out the first part if you’d like a little background.

When you’re stuck in a waterfall shop and responsible for figuring out the specifications for the project at the onset you are forced to put yourself in a very difficult situation. On one hand you are responsible to your manager to get the project specifications completely accurate the first time or else you risk adding time to the projects expected completion date thus eating away at the profits your manager expected. The other problem comes from the client side. To get the perfect specification you must drill and drill into the business processes required to construct the application which is a tedious and sometimes invasive process.

Luckily since you’ve adopted an agile model and don’t necessarily need to know absolutely everything up front, you are able to only ask the essential questions. Thus, I’d like to take a little time to work out how one should go about finding which questions must be answered before any development can begin, and which questions are a part of your refining process.

In my experience the client you are meeting with knows half of the truth about what the product must do. The clients subordinates, superiors, and sometimes customers know the other half. How did I come to this conclusion? It’s a simple derivative of the Pareto principle. If you are unfamiliar with how this principle applies to web applicationi development, the basic premise is that eighty percent of your users use only twenty percent of your application. The same idea applies to every other tool they use. In fact, it’s probably true of you–well, maybe not since developers are notoriously the exception to this principle as we actively seek out features and improvements to our use of an application–but let’s try to ignore ourselves here.

So the first question you must ask the client with whom you are having a conversation is, “What work is done before you get your hands dirty, and what does the result of your work look like?” This does not always apply, but this questions is easily adapted to fit a lot of situations.You should already be intimately familiar with this concept. By doing this you initially treat client’s work as a black box. You must know how what to put into your box before you can let your box do it’s magic.

Take notes on what your client tells you, as you need to know which person in the client’s organization knows how to get the product to where it needs to be before you put it inito the box, and who takes care of the product (assuming someone does) after the black box is done.

Now that you know the pre and post condition you can get inside the box and shed some light on the internals. This is done by a sometimes lengthy discussion with the client. If it starts to get too involved to be useful, attempt to steer the client to a more high-level overview of the process. Afterall, you are using tracer bullet development and the precise details will not be significant, or implemented for that matter, in the very first prototype demonstration.

Asking Questions as a Developer: Primer

Questions are an integral part of the necessary conversation between developer and customer. First we need to define a few terms. When I say developer I mean the person or persons who are responsible for decisions that directly impact the functionality of the product. This impact can be in the form of lines of code (e.g. implementing a new feature) all the way to decision about what features to include. So, as you can guess we have different levels of developers.

Likewise, we have different levels of customers. On one end of the spectrum, a customer is the entity that is requesting or using the product. This is the traditional definition of ‘customer.’ But I urge you to consider that the owner of a feature (e.g. the component lead) or, in the case of bug fixes, the support team as customers and treat them accordingly. The same goes for product managers. Anyone that has a stake in the functionality of the product should be considered a customer.

This is where the difficulty begins. Developers on any project can tell you that they not only must understand the technologies they are using to develop the product, but they must also have a complete understanding of the business or process logic they are trying to implement. This usually involves figuring out the operation and duties of several interested parties (or customers.) The inherent problems frequently encountered when a developer confronts the customer is assumptions of understanding and thinking in the technology. I will address each of these individually.

Assumptions of understanding happen when an interested party takes their own knowlege for granted. It happens on a daily basis in a variety of contexts. For example, an employee at the grocery store knows that they store Panko breadcrumbs in the Asian-specific section whereas a patron of the same store might assume they are stored with the breadcrumbs. Ok, that isn’t as great of an analogy as I hoped, but the concept is the same. Developers might take for granted knowing the difference between a page design application such as Adobe Indesign and a content management system such as Plone, or Joomla! Sure, they both allow you to visually configure a page but the end media (printed paper versus webpage) are drastically different. A customer might not make the distinction.

Thinking in technology is very dangerous for any project. It falls back to the principle that no tool is universal. Sometimes developers get the idea that they are a specialist in some technology–in this case let’s say the specific technology is a framework–which leads them to think and decompose a problem in terms of how that technology will solve the problem. Is this a bad thing? Not always. After all it is the first step to getting a project rolling. But what if, say in the middle of the project, the developer determines that a different framework would have been suited for the job? Or even decides that a different language has better tools to accomplish the job in a more stable manner. In this case thinking about a specific technology led to a bad decision that could potentially derail the project weeks into development.

So we get back to the conversation that started the project. A developer is responsible for obtaining the information necessary to develop a winning solution. The only way to get this information is to ask the correct questions of the customer. Questions the customer will understand and relate to the “big picture.” Here is an example of a typical customer/developer conversation:

Customer: We need something added to the website. We have reviewers that will be rating the people’s photos on a scale of 1 to 10 and then picking the winners.

Developer: Ok. So the reviewers are allowed to go through the submissions and rate them, and then from that you want a list of the photos ordered by their rating. Is that what you want?

Customer: Yes. That is exactly what we want.

What the developer does not know is that the reviewers are actually a team of reviewers that are assigned a certain photograph to rate. Then a committee goes through the rated submissions and even if a photo is rated highly it might not be selected as a finalist. It’s a very subjective system, but it is what the customers contest calls for.

The developer should have asked a simple question instead of phrasing his interpretation of the request as a question, “Will you walk me through the review process so I can get a grasp on how this will work?” Then after he learns about the team of reviewers concept and the committee component he will know that even though the photos can be ordered by their review score the finalists will be chosen by a separate review committee.

I know it is difficult to know which questions to ask which is why I intend to give you the gangsta way to approach customer conversations. In multiple parts, of course.

Tracer Bullet Development

I recently finished reading what turned out to be an excellent high-level book on development process, Ship It! This book is brought to you by the minds behind The Pragmatic Programmer, which if that does not basically sell the book I don’t know what will. But I digress.

I have the unique privilege of working with junior developers on a daily basis. Why do I consider this a privilege, one might ask? For some strange reason I like to teach, to help, to inspire and I cannot find a better medium to do so than someone wanting to accomplish the sames goals as myself.

If there is anything I learned from my thus-far short career it is that clients/customers/employers like to see progress and like to feel a sense of ownership and responsibility for any project they can get their hands on. Sometimes this works out for the better, but more-often-than-not it leads to disasters towards the end of a “traditional” project schedule. By traditional schedule I mean something that you’ll find in far too many shops that models the waterfall development process.

These disasters come in the form of “While this is nice, I really need this functionality for this to be of any use,” or “Why does it do things like that? It’d be much better if it more closely modeled our actual process.” If you’ve ever demonstrated a product to a client you have undoubtedly heard something similar. Why do these questions get asked? The primary cause–and possibly the sole cause–is lack of communication. Not necessarily a lack of attempts at communications, but for some reason questions asked by developers tend to not be understood in their full context (which consequently reminds of another post I need to get out of my head.) In the initial requirements gathering with the client some detail will inevitably be omitted which will lead to questsions such as these.

This is where Tracer Bullet Development (TBD) comes into play (the junior developer bit has some relevance, I swear!) The idea behind TBD is that you have frequent deliverables which are designed to steer the project on the correct path as it evolves. Yes, development paths evolve. If you don’t think so, clearly you have not been doing this long enough. One particularly well-thought-out analogy likens TBD to driving a car. If you start out on a trip from Houston, Texas to San Jose, California you know that you will be heading north and west. However, you don’t simply point your vehicle to the northwest and never veer from that straight line. Unless you did the math with absolute precision and there are no obstacles, you will never get to you intended destination. Rather, you point your vehicle to the northwest and then along the way you adjust your course according to direction (new requirements) given to you by your gps device, or your air traffic controller, or you nagging passenger.

I’ve found that junior developers (and some senior developers) will greatly benefit from a very TBD-like approach. It will help them to visualize the end goal and realize the relevance of each component in relation to the others. This quickly leads to better prioritization, improved communication, and a better overall project.

My advice to you as a senior developer is to guide your junior(s) to using TBD. If you are a junior developer bring it up to your senior or your manager. Read the books to get a better understanding. Remember the idea is to get a demo ready and slowly refine it. TBD is a winning agile approach.

The Refactor Factor

It is a well-known fact that PHP is a language that lends itself well to rapid concept-to-prototype development. Unfortunately this leads to prototypes finding themselves performing the role of stable production code. Chances are the prototype code is not exactly as stable as it should be.

I recently found myself in this very situation. I was tasked with building an entire application with a release schedule of three days. Obviously the three day timetable was something that would put my normal in-depth analysis and testing in jeopardy, but even more frightening is that this rapid release would most assuredly require that prototype code would become production code. Throughout development–which was by far a prime example of why design while coding is a bad choice–I was painfully aware of the need to refactor almost every line of code in the entire application. Okay, that is a bit of a stretch. Not every line needed a rewrite but some decisions were made against good conscience with the intent of refactoring at a later point.

Because of this decision I am now slowly improving the code while still adding new features into the mix–features that did not have an immediate need but still should be in application–which leads to a very rapid “agile” release schedule for point release (e.g. 1.1, 1.2) with about two weeks in between each release. This may not be anything new to a lot of people, but for my clients at the university this is a new and very different approach.

I am also, as a result of the original time constraints, committing a cardinal sin against my beliefs regarding testing: I am now adding tests in to my project because I felt I did not have time to write them before. This has already led to numerous junctions where I wonder what, exactly, I was thinking when writing the code under test and a subsequent refactor of the code to match the new test that will fail. Obviously I have now branched into TDR (test-driven refactorization.)

The point I am trying to make is that while it is possible to use PHP in the manner to develop applications at a rapid rate, the “refactor factor” that allows us to do so is more of a problem than a benefit. Putting off test development, putting of good design, and promoting prototype software into a production environment is not something that should be a daily occurance, if it occurs at all.

Logging to Firebug is Definitely Gangsta

In my never-ending quest to perfect an approach to rapidly implementing stable, high-quality web solutions I’ve used my fair share of var_dump(), print_r(), echo, and even Zend_Debug::dump() statements. But really there must be a better way. Log files are also great tools for debugging but they add an extra step: you must view the log file after running the script. I will admit this is generally not that difficult a task, but as a friend of mine pointed out, programmers–the good ones anyway–are necessarily lazy (not lazy in terms of sitting around not doing what needs to be done, but lazy as far as wanting to complete repetitive tasks.)

Cutting down on the work required to get to the information that will help squash a bug makes the process of patching code just that much more enjoyable. Enter Firebug. If you develop for the web and are using Javascript (which, let’s be serious, is almost a necessity on all but the most basic websites) chances are you already make substantial use of Firebug for debugging purposes in your markup, style, and client-side scripting. This is why having access to relevant information from your server-side scripting in Firebug is one of the best endeavors I’ve undertaken.

Now that you are itching to get started I’ll tease you with how simple the process really is. For starters, you need a couple extensions in Firefox (also I recommend getting Firefox 3, but allegedly it is not a requirement): Firebug and FirePHP. Don’t make the mistake I made which most likely cut a few minutes off my lifespan, go to the websites for the individual projects and download the latest-and-greatest version. For some reason Firefox will not detect the new version of FirePHP and without it, logging was a no go.

After installing the extensions you are ready to use the logging functionality provided in the Zend Framework. If you aren’t already on the Zend train, now’s a good time join. Ok, I’m not being fair. There are other libraries that can do this, I’ve just not used them as I have absolutely no reason to. Here’s a little snippet of how to use the Firebug log writer:

$log = new Zend_Log(new Zend_Log_Writer_Firebug());
try {
    //some code that throws exception
}
catch(Exception $e) {
     $log->info($e);
}

One thing to note, you must initialize your Zend_Controller_Front instance with a request and response object before logging (this is usually handled when the front controller is dispatched) before you log anything to Firebug else a Zend_Wildfire_Exception will be tossed about.

So far I am amazed at the benefit to seeing exceptions thrown in my PHP scripts inside Firebug complete with backtraces. It rawks.

Why PHP Gangsta?

Unfortunately I cannot take credit for the term “PHP Gangsta” which was coined by Ben Ramsey in a tweet on October 3, 2008. However, upon reading the term I immediately fell in love with it and decided to pick it up and run with it, so to speak.

As a developer in the PHP community I frequently feel like a ninja, a magician, and a gangster. Of course this would be true regardless of he language, but considering I develop using PHP I can’t claim to be a Ruby gangsta, or a Groovy gangsta although becoming a Groovy Gangsta definitely moved up on my “to-do” list. If you have no idea why I feel like a gangsta as a developer you clearly have not been using a language long enough. Being a gangsta is about knowing the rules and knowing exactly how to break to them to get what you want. In my case this means taking tools and bending them to my will. It doesn’t always work out for the better, but sometimes you just have to do what doesn’t feel correct.

I intend this blog to be a collection of rants, examples, tricks, and any other types of babbling I can somehow tie to being a PHP Gangsta. I imagine that a lot of what is talked about on this blog will be pertaining to the use of the Zend Framework to produce amazing solutions, because, well, that is what I do. There will also be frequent banter about testing (unit, acceptance, among others) as that is a necessary interest of mine.

So sit back, enjoy the ride.