Hidden Gems: The Null Coalescence Operator

In a previous Hidden Gems post, I covered the artistic side of programming as expressed through the use of the ternary operator. Here is the original post if you’re interested, otherwise here’s a quick summary of the concept: programming relies on the use of conditional statements, where a certain path is taken depending on the value of a variable or expression, and a ternary operator is an elegant, shorthand way of writing these conditionals. In the example below, the function isItSnowing() will return a true or false value telling us if it is snowing. If it is snowing, then we’ll stay inside, and if it is not, then we’ll go outside. The ternary operator has unlimited potential, with the ability to string multiple conditions together, but must be used carefully; just because it improves readability and style in this scenario does not mean it always will.

The null coalescence operator is a slightly more nuanced version of the ternary operator, but even more interesting due to it’s use cases. Oftentimes in programming, you want to assign a value to a variable, but you don’t know for sure that the value exists. The value might come from another source and you can’t guarantee that it was received correctly or as expected. In most programming languages, trying to use a value that was never created causes a disaster (one can easily see why), and will usually crash the program. However, programmers would usually prefer to provide some default value instead, to prevent the program from crashing. Here is that exact situation presented in relatively simple, but verbose code:

This is a fairly straightforward conditional statement, which says in plain English, “if the value of temperature is known, the message will be that value, but if for some reason we don’t have the temperature, let the message be a default warning that we don’t have the temperature”. If you’ve been paying close attention, you might have noticed that this conditional is very similar to the one we explored when discussing ternary operators, and as a matter of fact, this conditional can be expressed using a ternary operator, as demonstrated here:

Notice again the power of the ternary operator in simplifying the conditional. It compacts the same logic into one statement, which reduces the number of lines and is more efficient to run. Now behold the same statement written using the null coalescence operator:

The differences may be subtle at first, but they are extremely important. Notice that there is no expression to test whether or not “temperature” exists, as it is built into the operator. Also see that it automatically assigns the value of “temperature” if it exists. Finally notice that the default message comes after the null coalescence operator, and is assigned when the value of “temperature” does not exist. A common way to read the operator in English is “reading from left to right, give me back the first thing that exists”. This use case is extremely common in programming, which is what ultimately led to the null coalescence operator being created. Personally, I was thrilled when I discovered this: after writing hundreds of the equivalent ternary versions, I had finally discovered a way to write less code while also improving the style of my code. Once a programmer is used to using this operator, it reads much more naturally than the ternary operator and saves valuable time when trying to understand the code. This operator can also be chained, similar to the ternary operator, as shown in this example, where the default string is used if both the “temperature” and “backupMessage” variables are null:

At the end of the day, the null coalescence operator may not seem like a revolutionary idea, and it isn’t. However, it is a testament to the ingenuity and artistry of programmers, motivated by a unique combination of laziness and empathy for the programmers who follow. It is the accumulation of these small improvements that evolve into the modern programming languages we have today, which are more powerful and easier to read than ever before.

Hidden Gems: The Ternary Operator

If you didn’t already know, I’m majoring in Computer Science here at the University of Michigan and it’s been a long and unpredictable journey. I grew up with a passion for the humanities, especially art, and a large part of me wanted to be an artist. However, I was also talented in math and physics and enjoyed the problem solving required in STEM fields. Eventually I had to decide what I wanted to pursue in college, and I decided to be financially practical and pursue computer science and enjoy the humanities in my free time. Obviously this decision was completely subjective, but I want to give context as to how I approach art and computer science. Originally they were completely separate concepts, but the more I learn about computer science and programming specifically, the more I see it as a form of art. I’ve realized that I’m especially passionate about how code is written; there are no laws as to how code must be written, and style is completely subjective, which leads to each programmer having a unique style, similar to an artist. I’ve also heard comparisons between programmers and authors because both write hundreds of lines, broken up into chapters and paragraphs, which all aim to convey a certain idea. Viewed in this new light, I’ve discovered a lot of hidden gems that exist in computer science, small forms of art that go unnoticed, but are nonetheless works of creativity and intentional artistic design. I’d love to share some of those hidden gems with you, and I’d like to start with the simple ternary operator, a common programming construct found in most languages.

Programming is based on a few recurring ideas: checking certain conditions, using information, and providing interfaces that are easy to use. Checking a condition is incredibly straightforward, and I guarantee you do it all the time. For example, you might say that you’ll go for a walk if it isn’t raining outside, otherwise you’ll stay inside. In very loose code form (referred to as pseudocode), that conditional might be:

if (it isn't raining) {
go outside;
} else {
stay inside;
}

This is fairly easy to understand and it’s easy to see the pieces that correspond to the original sentence. However, it also takes up 5 lines of code. This might sound negligible, but when you’re working on a project that has thousands of files, each with over 100 lines, you quickly realize how much these small conditionals add up, and eventually how hard it is to read the code. In this way, programmers and writers differ: while a writer can spend paragraphs discussing an insignificant detail (think Charles Dickens), a programmer has to express a thought in as little words as possible, while still conveying the same meaning. The purpose is to make the code so easy to read and understand that a future programmer looking back at the code can read it like a book. I find it especially interesting how code is meant to be read by other people; I’ve heard the saying that the first programmer to write a file will only read it once, but that it will be read a hundred times by the programmers that come after them. Put in this perspective, it’s easy to see how important clean code is, and to understand the fine balance between art and efficiency when styling code. So, how can we make this 5 line conditional even more elegant? Answer: the ternary operator. Here is the same logic presented using the ternary operator:

it isn't raining ? go outside : stay inside

Breaking this single line into pieces, it says “is the first statement true? If it is then do this first thing. If it is not true, then do this other thing”, where the question mark signifies the question and the first thing and second thing are the pieces separated by the colon. Take the time to translate our example into this format and compare to the original piece of code. Now appreciate the simplicity and readability of the second form. I hope I am conveying just how fascinating this simple structure is, and how it is a small work of art in the world of programming. It is an art of elegance, conveying complex ideas in simple ways, but with a practical importance not found in most art. Hidden gems like this remind me why I enjoy programming so much, and how art can be found in anything, even when you aren’t looking for it.