Thursday, September 6, 2012

ColdFusion Quickie : Using the Ternary Operator To Pass Conditional Argument Values

Its been awhile since I've done a ColdFusion quicke post and I found this trick to be quite useful  especially when dealing with ORM domain entities.

Lets say that we have a domain object called User that gets populated out when a user signs up for an account.  This object has some simple properties; fullName and email (lets not get into object purity here and say that those should be a member of a Contact object).  Lets also assume that when a user signs up all only an e-mail address is required, they can leave their name blank if they choose to.  The important thing to note here is that when a user object is loaded from the database the fullName property may hold a value of null.

When a user signs up for an account our application calls a function that will send a welcome message to a user that has a signature of: sendWelcomeMessage(required String name, required String email) (for arguments sake lets say that we don't have the ability to change.  If this function is invoked using implied getters from the User object we'll run into problems if getFullName() returns null. This is where the ternary operator can quite useful in sending a default value to a function:

sendWelcomeMessage( 
    (!isNull(person.getFullName()) ? user.getFullName() : "User" , 
    user.getEmail
);

The ternary operator takes a value or expression that can be evaluated to a Boolean and returns one of two things based on the result of that expression. The ternary operator's signature looks like this:

(expression) ? trueStatement : falseStatement

As you can see in our example, we check if person.getFullName()does not return null and pass that value if its true, otherwise pass in a default value of "User".
Fork me on GitHub