Thursday, April 3, 2014

Lazy Programming

There are two types of lazy programming, good and bad.

Good Lazy

Lazily instantiating and populating data structures is a perfect example of a good design pattern. This technique is also how CDNs populate their edge servers. Don't create or store anything until the last possible moment.

When implementing this technique, I use accessors that have the same name as my instance variables (ivars). Below, my _employees ivar is set to null when a class is instantiated and it's not populated until the first time it's touched (accessed). This is the beauty of key-value coding accessor methods.

private NSMutableArray _employees = null;

public NSMutableArray employees()
{
    if (_employees == null)
    {
        this.setEmployees(new NSMutableArray());
    }
    return _employees;
}

public void setEmployees(NSMutableArray newEmployees)
{
    _employees = newEmployees;
}

Depending on my performance requirements, this design pattern would work if I needed to save memory. However, if memory isn't an issue, but, rather speed, this might not be an ideal solution since each time the employees() method is called there's a an O(1) test performed to see if the private ivar is null. In cases where speed needs to be optimized then it's best to pre-populate the data structures (caches) before the web app begins accepting requests. At the Apple Online Store, we pre-populated only when necessary. In every case, though, the key is to avoid premature optimization.

Bad Lazy

The goal of a software engineer is to provide the best possible user experience (BPUX).

As a programmer, I'm not shooting for perfection but I know when something can be done better. (If I went to sleep last night then I had time.)

If I have to code something that's singular or plural I'll go out of my way so it doesn't read:
You have 1 item(s) in your cart.

It's not very hard to code:
You have 0 items in your cart.
You have 1 item in your cart.
You have 2 items in your cart.

There is no shortage of websites where I've entered my phone number (760.444.4721) or credit card number (4111-1111-1111-1111) only to hit enter and been told I made a mistake and my digits need to be reentered with only numeric characters.

Some programmer had to go out of their way to search the string I entered, confirm there was a non-numeric character, and then return an error message to me. This is my big pet peeve – it's too in-your-face. I entered all the information the programmer needed and they could have parsed out the digits. When I'm coding, I simply write a cover method to return only the numeric digits.

Software engineers aren't sales people, so they don't live the ABCs.

No comments: