Affordances of my waffle iron

I have a beef with my waffle iron.  Every time I pull it out to make waffles, I go through a process to re-learn how it works.  You would think that it’s hard to screw up a waffle iron, but apparently this manufacture managed somehow.

The problem lies with the two indicator lights on the front.  Take a look at this picture, which is what I see right when I plug it in.

My waffle iron, plugged in

What do these lights mean?  My first thought is that the green light means it’s ready to go.  But there’s a red light too.  Not to mention that the iron is still cold, so it’s obviously not ready to be used.  After waiting a few minutes, the green light goes off which apparently indicates that it’s heated up.

My waffle iron, preheated

The red light means it’s plugged in, and the green light indicates its preheated status.  When the green light is on, it’s not ready.  But when the green light is off, it’s ready to be used.

Labels on these two lights would help.  But using natural cues, this waffle iron could be designed to just make sense.  First, I would remove the red light.  There’s no need for two indicators.  There should be a single light that is either red or green.  A blinking red light would indicate to me that I need to wait as it’s warming up.  Once it’s preheated, the light should switch to solid green.

Posted in Affordances | 3 Comments

My core tenets of software engineering

Experience has taught me that software development is a very fluid process. As a product is developed, ideas change about what the product should do and how it should behave. Often this can result in miscommunication and wasted time working on features that don’t really matter. I have discovered several software development methods that mitigate the negative impact of this fluid process. These concepts are central to how I work with clients.

  • Minimum viable product. Many projects that start off as a great idea evolve into something unmanageable as ideas are constantly added and the scope of the project changes. I believe in defining up front the core essence of a project. What is the bare minimum functionality that comprises the core of what the client wants to deliver? Once that is defined, create that core product and make it rock solid. Get it into production and have real people start using it. This will prove what functionally is really needed and that the product is useful and viable. This has the added benefit of getting feedback from real users during the development process.
  • Short iterations. Communication is tricky. It’s difficult to make sure two people are talking about the same thing and have the same idea in mind. This is why I like to turn ideas into code or prototypes as quickly as possible. This moves an idea from theoretical to physical. I then have something the client can see and say, “I like X, but change Y.” The idea of “short iterations” is to have small milestones that can be delivered quickly. Shortening the feedback cycle means less time wasted on miscommunication and on features that don’t matter.
  • Quality first, quantity later. One hour spent improving quality can save 100 hours of work down the road. While it’s not always easy to immediately see tangible results from that one hour, the investment always pays off in the long run. The result is a product that does not require much maintenance, and customers who are happy and confident in the product. Building a quality product should take priority over delivering lots of “nice” features. The extra features can come later, a quality foundation is priceless.
Posted in Coding Practices | Leave a comment

WordPress plugin for Spreedly

I’m very excited to announce that I’ve created a WordPress plugin for Spreedly. This plugin is a drop-in solution for hiding content on your blog behind a subscription interface. By combining powers with the awesomeness that is Spreedly, this plugin makes it dead simple to charge a fee for your blog.

It’s easy to configure. You need your Spreedly API key and your site name, set up your plans in your Spreedly settings, then pull the plans into WordPress using the “Pull” link. That’s it! Now when editing pages and posts in WordPress, you can optionally hide the content except for paid subscribers.

Let me know what you think. I’m pretty excited about how it’s turned out.

Posted in Spreedly | Leave a comment

Optional constructor parameters

One thing that really irks me about PHP is the way parameters are passed into functions and constructors. A typical constructor will look like this:

$col = new Column($id, $label, "50%", true, false);

While that’s nice and compact, it’s impossible to read. Using some context, I might be able to figure out the purpose of the variables, but unless I’m familiar with this function, I have no idea of the purpose for the “true” and “false”.

It hit me this week that I should start using a sweet idea from the MooTools playbook. Many object constructors in MooTools take an “options” parameter that is a hash of parameters. The class itself has default values for all of these options, so when you’re passing them into the constructor you can pick and choose which ones you want and set values for them. We can do the exact same thing in PHP.

My proposed solution for unreadable and long sets of parameters is to do something like this:

$col = new Column(array(
        "label" => $label,
        "id" => $id,
        "width" => "50%",
        "fixed" => true,
        "sortable" => false
    ));

See how much more readable and versatile this is? There could be another option called “type” that defaults to “text”. But since I don’t want to change the default, I don’t need to include it here. For required parameters (like “label” and “name”), simply throw an exception if they are not included in the option list.

As I see it, here are the benefits:

  • Readability – It’s easy to glance at this and see the purpose of every parameter.
  • Forward compatible – If you add another option to the constructor down the road, as long as you provide sensible defaults, this is forward compatible. You won’t have to go through your code and add the 6th parameter to every Column instantiation.
  • Flexibility – Developers don’t need to remember the order of the parameters since they can be added in any order.
Posted in Coding Practices, PHP | Leave a comment

Unit testing with PHP

You’ve probably heard of unit testing. If you are like I was a few years ago, your mouse is hovering over the “close” button right now. But wait! Don’t go away just yet. Over the past few years I have come to realize that unit testing is not only a good idea, it’s essential to developing quality code. I do believe however, that unit testing can be overdone and there is a balance that should be achieved. In general though, unit testing is now an essential part of my development process.

Justification for Unit Testing

Recently when refactoring a large codebase, I was saved by the unit testing framework I had developed months earlier. These changes I made were large and sweeping. They affected almost every area of the codebase, which ended up being thousands of lines. I had earlier developed a comprehensive unit testing framework that thoroughly exercised the code and tested for expected outputs for many different scenarios including edge cases. This framework ended up saving me immeasurable frustration. Had this not been in place, how on earth would I have known if my changes were breaking other functionality? As it stood, I was able to make my changes, ensure it passed all the unit tests, and go to sleep that night confident that I hadn’t broken anything for backwards compatibility.

The case can be made that developing a good unit testing framework just takes too much time and slows down production. While it’s very true that it does slow down production, I have come to realize that it’s a necessary up-front cost to invest in the long-term health of a project. The hours saved down the road will more than make up for the initial investment, not to mention the peace of mind.

When Unit Testing is a Hindrance

Lest I sound like a gushing groupie, I will freely admit that I believe there are times when unit testing can be a hindrance. The main time this comes into play is when expected results are unknown or are fluctuating rapidly during the development process.

In an ideal world we would have a list of requirements that are set in stone, and the deliverable product would be whatever meets those requirements. I remember ACM programming competitions in college. I loved them because you had a discrete set of inputs and a deterministic, predictable output based on those inputs. Your job was to produce the exact output as quickly and efficiently as possible. That would have been a perfect scenario for unit tests (alas, bonus points are not awarded for testing frameworks in the ACM competitions).

Real life is not always ideal. Requirements change. Sometimes, requirements are not always fully fleshed out when development begins. Sometimes, even though requirements may be defined, I have not fully solidified in my mind the best implementation approach. Often, I start coding as a way of fleshing out my ideas. Sometimes this code turns into the production deliverable, and sometimes it’s trashed.

In situations like this where I am developing rapid prototypes, I believe unit testing gets in the way. Why develop tests when I know things are going to change? Wait until the implementation details have solidified before creating a unit testing framework. This will most certainly be well before any code goes into production, but may be a bit down the pipeline of the development process.

I can almost hear the cries of “heresy” as torches are being lit and pitchforks sharpened.

PHPUnit Framework

One thing I greatly admire about the Rails community is their embracing of unit testing. It is built right into the framework and strongly encouraged from day one. Unfortunately, PHP has no such principles. As with most things in PHP, good development practices take self discipline and resolve.

There is however, a fantastic unit testing framework for PHP called PHPUnit. The more I’ve learned about PHPUnit, the more impressed I have become. It really has a full suite of features that make building and maintaining tests a breeze. It has the capability of constructing and destructing test data in a database on the fly, the ability to run a single test with multiple data sets to test edge scenarios, and compiles comprehensive code coverage reports. And that’s just the tip of the iceberg.

Conclusion

It took me a while to come around, but I am fully in agreement with the necessity and utility of unit testing frameworks. Today if I were to release code that was not covered by unit tests, it would feel like standing naked before a crowd. While I’m not 100% in agreement with the mantra of developing tests first, I do always take the time to develop good tests before releasing anything into the wild.

Posted in PHP, Testing | Leave a comment

My current toolset

There are many tools I use on a day-to-day basis to get things done. John Long posted a similar list on his blog, and I thought it would be interesting to make a similar list for myself. Without further ado, here is my toolset:

Scratch pad. To start things off, my development environment would be incomplete without a good scratch pad. I love whiteboards, but I find they’re most useful when collaborating with others. On my own, I tend to jot down notes and make sketches in a little notebook I keep beside my computer.

My computers. I have one of the 24″ iMacs, and a 13″ MacBook. Both tools serve invaluable purposes in my daily routine. I got a small laptop for its portability. This serves me very well when I’m mobile. It works great for code editing, but makes graphics editing difficult. When I’m at home, I use my iMac whose wide screen is perfect for any task.

Vim. Where would I be without my beloved Vim. Many people have tried to woo me away from Vim with fancy IDE’s and nifty graphical editors, but I always return. I’ve been a diehard Vim user for over 10 years now, and I’ve yet to find anything with which I am more productive editing code. My .vimrc has been tweaked to perfection (largely untouched for 6 years), and the mouseless commands are ingrained into my psyche. I have MacVim installed on my computer, but almost all of my editing is through Terminal both for remote servers and local editing.

Terminal. I hail from the Linux community. Linux has been my native language since 1997, and I’ve only recently switched to Mac. This is probably why I feel most comfortable in the Terminal application. Give me a Terminal and a web browser, and 99% of my development needs are met. There is a beautiful efficiency one can achieve in the console and the mouse just gets in the way.

Ack. A recent, and now invaluable, addition to my toolbox is Ack. This little script makes light work of searching through a code base for a particular string. It is now one of the first things I install whenever I get access to a remote server somewhere.

Firefox and Chrome. Since most of my work is as a web developer, I obviously use a browser as part of my core toolset. Let me just say that I love Google’s Chrome. It is lightning fast and appeals to my minimilist nature. For most of my browsing, I use Chrome. Still, nothing rivals the tools available in Firefox for debugging. While webkit’s inspector features are nice, they don’t hold a candle to Firebug. When the Chrome Firebug extension is developed as polished as the one for Firefox, I’ll switch to Chrome and won’t look back.

Lineform. I’ve been searching for a good vector graphics editor for the Mac. I’ll probably have to break down and buy Illustrator because there really isn’t much good out there. I do have Lineform which usually is sufficient to meet my needs, but is not polished and does not have a lot of bells and whistles. Anyone know of a good vector graphics editor that is affordable (e.g. not Illustrator)?

Pixelmator. It is the same situation with a graphics editor. Coming from the Linux world, I am most comfortable with The Gimp. Since the Mac version of The Gimp is painful, at best, I have been searching for a good native graphics editor. I’ve settled on Pixelmator. Again, this meets my needs most of the time, but I do find the interface a bit frustrating.

Gmail. I use Gmail for email, task management (sending email reminders to myself), and as a storage for ideas. I have several labels used for different categories of ideas. Whenever I have an idea I want to remember, I email myself and file it in there. As the idea develops, I keep replying to that conversation. This works great for jotting quick notes that I want to remember. I also store screen captures of designs I like in a label in Gmail. This collection of images is often the source of inspiration for much of my web design work. And, of course, I use the keyboard navigation for most of my interaction with Gmail. The day I discovered Gmail had Vim keybindings was the day I fell in love with Gmail and have never looked back.

Adium. Only because nothing better exists.

What about you? What is your current toolset?

Posted in Observations | Leave a comment

Are masked password fields necessary?

Last March, @johnwlong tweeted “Do people really want their password hidden (••••••) when they signup?” (here) and “Wondering about dropping the “confirm password” field on our signup screen and using a normal text field for the password instead.” (here). My reply to him was “as practical as that sounds, I think that would (perhaps subconsciously) make users question the security of your site.” I haven’t been able to shake the idea. Are masked password input fields really necessary? Do they provide any benefit?

Usability expert Jakob Nielsen believes they aren’t necessary. He says, “Let’s clean up the Web’s cobwebs and remove stuff that’s there only because it’s always been there.”

Again yesterday, the issue was brought to my attention by a similar article on A List Apart. They said pretty much the same thing as Nielsen and offered some compelling alternatives to masked entry.

After about a year of mulling over this issue, I have come to change my mind. I agree with Nielsen. From a usability perspective masked entry is a hindrance. It offers very little actual security unless someone is looking over your shoulder. However, masked entry causes much frustration for the user who may think they’ve forgotten their password when really it is just being mistyped.

I do still believe the main benefit of masked entry is the feeling of security. Not seeing our password is so ingrained in our usage patterns that users would likely do a double take and lose some degree of confidence in the security of a system if they saw the text of their passwords. That said, I am seriously considering implementing an alternative with NeoBudget.

My favorite alternative is an open entry field with a checkbox to enable or disable masked entry. Depending on the needs of the site, the entry field could be masked or unmasked by default. The key is that the user has control and is able to unmask the field in order to check spelling. This is often found in operating systems when entering a network key, and it’s very useful for double checking these long strings.

What are your thoughts? Should we start phasing out obscured password entry fields? Have you come across any other alternatives?

(Also, did you know that IRC has a sweet password masking feature?)

Posted in Observations | Leave a comment

Spreedly PHP Library v2.5 released

As mentioned previously, I use a service called Spreedly to manage subscriptions in NeoBudget. I also created and maintain the Spreedly PHP library.

Thanks to the contributions of some fellow Spreedly customers, and due to some recent enhancements from Spreedly, I’ve released v2.5 of the Spreedly PHP library.

This release includes the new extended options available for the Spreedly::get_subscribe_url() method explained in the Spreedly integration reference. The most notable improvement is the inclusion of the subscriber token as a way to pre-populate the form fields with data already entered.

This is a backwards compatible release, meaning that although new functionality was added, old functionality has not been broken. Check out the Spreedly PHP library page to download.

Posted in Spreedly | Leave a comment

Creating a JavaScript application with MooTools

MooTools makes dynamic DOM manipulation simple. It provides some object oriented wrappers around browser functionality, and ensures cross-browser compatibility with all modern browsers (and even IE6). Lately, I’ve been using MooTools with a couple web applications that are completely rendered in JavaScript.

Rendering the application completely in JavaScript has numerous benefits including:

  • The application behaves similar to a desktop application. It has an asynchronous event-driven interface, and offers much more control over the elements being displayed than simple HTML+CSS.
  • The code is much easier to maintain. JavaScript is a beautiful language. Lets face it, creating an application with HTML is a hack to begin with. HTML was intended as a document markup, not as a mechanism for creating rich interactive interfaces.
  • There are some things you just can’t do with HTML. For instance, passing objects by reference is impossible with inline JavaScript in rendered HTML, and it’s horrible form anyway.

The first thing to do is create a simple HTML landing page that will launch your application.

Example #1: HTML landing page:

<html>
  <head>
    <script type="text/javascript" src="/mootools.js"></script>
    <script type="text/javascript" src="/myapp.js"></script>
  </head>
  <body>
    <div>Loading...</div>
    <script type="text/javascript">
      window.addEvent("domready", function() {
        MyApp.render().replaces($(document.body));
      });
    </script>
  </body>
</html>

Now, in myapp.js you need to define your application. The hook that gets it all started is the render method and it’s expected that this will return a body element. So lets take a look at an example.

Example #2, JavaScript defining the MyApp object:

var MyApp = {
  render: function() {
    var body = new Element("body", {
          html: 'Hello World!'
        });
    body.addEvent('click', function() {
          alert('Click!');
        });
    return body;
  }
};

That’s basically it. If you run this, you’ll see “Loading…” appear while all the JavaScript sources are being downloaded and the DOM tree is constructed in the browser, then it will be replaced with “Hello World!”. When you click on the document body, an alert will pop up saying “Click!”.

Obviously this is an extremely simple example, but this gets you started. From here, you can create a more complex body structure with interactive elements and AJAX calls, and all the good stuff.

Posted in JavaScript, MooTools | 1 Comment

Separate display from logic

PHP lets developers write ugly code. And I mean really ugly, unmaintainable, horrific code. I’ve had to work on my share of projects that would make spaghetti code look organized. It doesn’t have to be that way though. Seasoned developers know the benefit of organized code. One organization technique that I believe is essential is the practice of separating display code from logic code. Lets discuss a couple methods of handling this in PHP.

A simple method

One of the simplest methods you can employ is just separating code that generates HTML from the rest of your code. Using the PHP project structure I described previously, all the HTML generation code would reside in the www directory, and everything else would exist in classes in the lib directory.

By “HTML generation” code, I mean any code whose sole purpose is to format and display HTML. This would include all echo and print statements, as well as loops to iterate over data sets. Any business logic or data access code would be considered “logic” in this case, and should be separated from the display.

Why is this a good practice? Lets look at two examples.

Example #1 with no separation of display and logic:

<?php
  $sql = "SELECT * FROM users WHERE username = 'luke'";
  $stmt = $pdo->prepare($sql);
  $row = $stmt->fetch();
  echo "Hello {$row->first_name} {$row->last_name}!";
?>

Example #2 separated into a User class, and a display script:

<?php
  class User {
    ...
    public static function get_user($username) {
      $sql = "SELECT * FROM users WHERE username = :u";
      $stmt = $pdo->prepare($sql);
      $row = $stmt->fetch();
      return new User($row);
    }
    ...
  }
<?php
  include_once("classes/User.inc");
  $user = User::get_user("luke");
  echo "Hello {$user->first_name} {$user->last_name}!";
?>

While Example 2 is certainly a bit more code up front, can you see the benefit over Example 1? There is now a reusable method called User::get_user() that can be used everywhere. This also allows for unit testing of the User class, to ensure that the method always works as we would expect; division of labor, to allow some programmers to work on back-end classes while others focus on the front-end display; and it is more maintainable, since we only have one place that fetches a user from the database instead of duplicating that logic all over our site.

The model, view, controller (MVC) method

Another popular code organization method is called MVC for model, view, controller. This has been popularized in recent years by the rise of Ruby on Rails which uses the MVC method by default. For larger projects, this is an excellent way to organize code. In the interest of time, I won’t delve into examples. In general though, here is how each part of MVC is differentiated:

  • Model – The model can be thought of as a data container. It would be a User or a Product class that holds all the information about something. This would also include the database which is where the data actually resides.
  • View – The view is usually some sort of template that takes models and creates a meaningful interface with which the user interacts. This would be very similar to the “display” part of the previous example.
  • Controller – The controller can be thought of as a traffic cop. This part is in charge of instantiating models and passing them to views.  The controller glues everything together and delegates user actions to the right places.

This can be done in PHP easy enough by differentiating your classes into models and controllers, while still keeping your view clean of any business logic. A true MVC model would likely use a template engine instead of echoing HTML directly from a PHP script, and the PHP script would act as part of the controller.

Conclusion

You should use whatever method works best for any given situation. No one solution is the best. However, you should always use some sort of organization technique, or your code will end up being a nightmare to maintain. Remember: “Always code as if the person who will maintain your code is a maniac serial killer who knows where you live.”

Posted in PHP | Leave a comment