Posts categorized “programming”.

Today’s fun JavaScript trick: switch(true)

Programmers who are new to JavaScript but familiar with other C-syntax languages like C or Java are definitely familiar with the switch statement, but may not be aware of how much more flexible this construct is in JavaScript. In fact, I’ve heard experienced programmers claim that they never use switch statements!

One major difference in the JavaScript switch statement  is the fact that the condition can be any type of variable, not just numeric types. Most obviously, this allows you to use a string or an object, which provides a lot of flexibility. So much flexibility, in fact, that when used with a boolean condition the JavaScript switch can provide a very different type of program flow control.

For example, consider a case where we want to take different actions, respectively, if a number is greater than 100, less than -100, or equal to 0. We could write it as a series of if/else ifs, like this:

if(x > 100) {
    doSomething();
} else if (x < -100){
    doSomethingElse();
} else if (x == 0){
    doAThirdThing();
}

Using a switch statement, this block becomes:

switch(true){
    case (x > 100):
        doSomething();
    break;
    case (x < -100):
        doSomethingElse();
    break;
    case (x == 0):
        doAThirdThing();
    break;
}

Is that any better? Probably not. In fact, it’s a little more clever, which may make it a little harder for other programmers to maintain, which would actually make it worse. However, consider the case where we want to take a specific action if x is greater than 100 or y is greater than 200, or z is less than -100, or if (x + y + z) is greater than 500. We could write this:

if(x>100 || y > 200 || z < -100 || (x + y + z) > 500){
    // um, what?
    doSomething();
}

Using the switch statement, that same code looks like this:

switch(true){
    case x > 100:
    case y > 200:
    case z < -100:
    case (x + y + z) > 200:
        doSomething();
    break;
}

I find the second block much more readable. Is it groundbreaking or radically new? No, but this is just another case where the flexibility of JavaScript’s syntax provides an interesting opportunity for more maintainable, readable code.

A faster horse

“If I’d asked people what they wanted, they would have said a faster horse.”

- Henry Ford

I just heard that quote yesterday from a pretty smart guy, and I really like it. Some people disagree, but I couldn’t agree more. Sliced Bread Design had a great and very detailed take on it. My favorite bit from it:

So, what should Henry Ford have been asking his customers? Instead of, “What do you want?” he could have asked, “Is there anything you particularly like or don’t like about your horse and wagon?”

You can probably very easily ask someone what software they want you to build, bang out the code, and deliver exactly what they asked for. They might even be really happy with it. But if that’s all you’re doing, what separates you from everyone else? What we need to do is break down user requests into desired implementations and desired results.

Implementations are a means to an end.

Customers are not going to make clear distinctions in feature requests between desired implementations and desired outcomes. It is up to us to do make that distinction, because if we can come up with a better implementation that produces the same result, we both win. A customer may ask for a dialog, but what he/she’s really asking for is whatever that dialog lets them do.

Applying this to Henry Ford’s quote, if we had a customer ask us for a faster horse, we could simply break down the request into implementation and outcome. The desired outcome is fairly clear; get me and my stuff from point a to point b faster. The desired implementation? Some kind of rocket-powered superhorse. The outcome is what the customer is willing to pay for, though; the implementation is merely a suggestion. If you can can come up with a better implementation (and Henry Ford sure did), people will not be disappointed.

As a developer, it’s easy to become fixated on details; they’re our bread and butter. That’s why it’s important to take a step back when analyzing customer requests and remember that users have exactly the opposite fixation. They’re willing to work with just about any implementation that lets them accomplish their task. We need to give them what they really want, whether or not it’s what they asked for.

An operator from Groovy that I wish was in JavaScript

First off, keep in mind that I’ve never used Groovy, just skimmed a couple of language references, but people I know have used it and like it. In case anyone is not familiar, Groovy is a dynamic language implemented on the JavaVM. It’s commonly used for web development, especially with the Grails framework.

Anyway, having established that I don’t know much about Groovy, I do know that it has a feature that I really wish we had in JavaScript. It’s called the Safe Navigation Operator, and it’s represented as ?. in the code. Quoting the Groovy reference:

The Safe Navigation operator is used to avoid a NullPointerException. Typically when you have a reference to an object you might need to verify that it is not null before accessing methods or properties of the object. To avoid this, the safe navigation operator will simply return null instead of throwing an exception[.]

If it’s not clear from that, here’s a real-world example. Let’s say you have a customer object. That object has an optional attribute address, which is itself an object, and in turn has city, state, and postal code attributes, which are strings. In JavaScript, you could access the State like this:

var state = customer.state.address;

No problem, but what if the customer object doesn’t have an address? That line will throw an exception. We can work around it like this:

var customerState= customer.state ? customer.state.address : null;

But if we get deeply nested objects, the syntax gets really muddy. Using Groovy’s Safe Navigation Operator, we could just do this:

var customerState= customer?.state?.address;

Now, if customer is defined, and state is defined, and address is defined, then customerState has the customer’s state. Otherwise, it contains null. Either way, it never throws an exception, even if none of those objects are defined.

Cases where this could come in handy are data retrieved from deep XML hierarchies, complex nested JSON objects returned by web services, and unpredictable user-entered data.  I’m sure that if JavaScript supported a similar operator I would use it all the time. Kudos to Groovy’s designer, Guillaume Laforge.

A couple of useful links regarding shell scripting

I probably shouldn’t admit this, but I’m not any good at shell scripting. It’s one of a few things I’m not good at that mean I’m not a “real” programmer (the others being regular expressions and SQL queries…good thing I’m into UI). But I have hope that I will get good at shell scripting.

So I’m pretty psyched that StumbleUpon came through for me with a couple of useful links related to shell scripting. Here they are. Enjoy!

http://www.techinterviews.com/basic-shell-scripting-questions

http://blog.emson.co.uk/2009/06/18-useful-bash-scripts-for-web-developers/