How I Stopped Worrying and Learned to Love the Bang

I recently stopped cold while writing a ReactJS component and experienced a very brief (albeit intense) existential crisis. I had just, without giving it excessive thought, used not just a ternary expression to determine what the component would render, but I also used a bang in my logical test.

First: My Beef With Ternaries

I learned early in my code journey about the value of legible code, of chasing the paradigm of self-documenting code, of explicitly indicating one’s intentions with a minimum of mental friction. This is largely why I resist writing ternary operations wherever possible, thinking that an item like this

var result = input > BASELINE ? "Input is above baseline" : input < BASELINE ? "Input is below baseline" : "Input matches baseline";

is a difficult-to-read unclear mess; whereas

var result = string.Empty;

if (input > BASELINE)
{
    result = "Input is above baseline";
}
else if (input < BASELINE)
{
    result = "Input is below baseline";
}
else
{
    result = "Input matches baseline";
}

puts practically zero friction on the eyeballs and takes nearly zero effort to understand.

I can understand the desire to write as few lines of code as possible, for a lot of reasons we don’t have space to get into just now. But I don’t feel that brevity was a good enough reason to make something more difficult to read. Many pair partners can attest I have a tendency to start with a classic IF-ELSE block and resist refactoring it into something more brief.

Enter the “Bang”

I might have a strong distaste for ternaries, but I absolutely despise using bangs. The fact I feel compelled to take a moment and define what the hell it is for the less technical reader seems to summarize my issue with it–it’s an overly complex tool.

A “bang,” is simply an exclamation mark (“!”). In most (all?) programming languages, we use it to mean “Take the opposite of this bool (true/false) value.”

For instance, if I have a bool variable “isDarkMode” that equals TRUE, then “!isDarkMode” means FALSE.

Nice and confusing, yes? Thanks; I hate it. To be fair, I have seen cases where using a bang is the most elegant (or least messy) way to get what we want…but more often, I’ve found it to be a sign of lazy naming, poor coordination across application layers, or someone trying to be super clever. It just smells.

// Dark Mode is enabled when the UI element isn't toggled because it's wired backwards
var isDarkMode = !uiToggle.IsToggled;

if (!isDarkMode)
{
    // set everything to light mode styles
}
else
{
    // set everything to dark mode styles
}

You might think this is contrived, but I’ve looked at similar blocks of production code more than twice, going “Why does this make my skin crawl.” A couple quick refactors (like inverting the IF and ELSE to get rid of the need for the bang or renaming the variable so we can use the <uiToggle> the way it was written) will restore sanity…but suffice to say when I see “bang” I say “Oh dear.”

You May Ask, “What Changed?” I’ll Tell You…

I essentially learned to code in C#, and then spent the first years of my career primarily in the back end of .NET Framework applications. I relish the sense of order that comes with strongly typed objects backed by interfaces. Knowing I can extend these stable items whenever I needed new behavior (and knew they’d behave the same way over and over, or throw an exception trying).

More recently I’ve been adding functionality to a React web app (as you may have gathered from my opening paragraph). I’ll own it–JavaScript in general, and ReactJS in particular, were technologies that baffled me as I tried to become fluent in C#. The differences between a strongly typed language and the chaos of JS were bad enough–but React leverages the extreme flexibility of JS in ways I couldn’t comprehend.

For instance, the fact that when using a child component you can pass in one, some, all, or none of the properties defined or used in that child component without expressly providing overloads for the component. Try that in C# and see how fast your app blows up.

// Renders an empty view in light mode
<ChildComponent />

// Displays the list data in light mode, but does not render edit options because no user
<ChildComponent
  dataList={list}
  />

// Displays the list data with all options, in dark mode
<ChildComponent
  dataList={list}
  userId={user.id}
  darkMode
  />

The magic, and my existential crisis, happen inside the child component’s Render() function, thanks to how JavaScript handles resolving objects.

render() {
  const { dataList, userId, darkMode } = this.props;

  if (darkMode) {
    setDarkModeClassNames();
  }

  return (
    <React.Fragment>
      { !dataList
        ? // render empty display
        : // render the list
      }

      { userId &&
        // render the edit/add options
      }
    </React.Fragment>
  );
}

Because JS nor React will balk if any of those three properties are unassigned, we can (and should) take different actions depending on if there’s actually an object attached to that variable. React makes this easy enough with their conditional in-line rendering.

What we see here inside the logical operators is shorthand for “Is this defined?” and when we apply the bang “Is this NOT defined?” It’s checking both that the variable has been defined, and that it has been defined in a usable way (ie, dataList isn’t null). We could do this manually and explicitly…but that’s not good, idiomatic, or smart JavaScript. It’d be like writing one’s own “string.IsNullOrEmpty()” method instead of using the built in C# method.

You’ll see I open my first ternary with a bang (aren’t you glad you’re not paying for this content??). I did this because I felt, in this case, it IS the most explicit approach. I wanted to indicate what the next person in the file should pay the most attention to–the component cares if the listData is missing. We could invert this ternary and get the same result…but, I wanted to emphasize “The weird, early-return style behavior happens when there’s no list data.”

And yes. I’m using a ternary here, two if we count the neat short circuit with the userId. For one thing, I can break it up over several lines for clarity. For another, it would be significantly more work to replicate this behavior in a different pattern. It makes sense, and (based on the existing examples in the code base plus all the reading I did) it’s idiomatic React.

TL;DR…

I had a major polyglot growth moment. I embraced the features of a language that just wouldn’t fly in my “home” tech stack, and I added a whole mess of tools to my kit to use and reference going forward. What is nonsense in a typed language is totally fine in an untyped one, and that’s okay.

Azure Webjobs, Application Insights, and You: A Vaguely Comprehensive Guide

When I was learning to code, it wasn’t hard to find out what was going on in my applications. Typically, especially in classes, I was sending output to a console–super easy, instant feedback. A few times I didn’t have a console to watch, I was writing things to a text file I could open immediately. Also easy. As things went on, and they had us actually playing with webapps and javascript and HTML, the feedback was again instant. I would know immediately if my program was behaving.

Then I get a few weeks into my internship, and there’s this new idea: a webjob. Essentially, a console app that runs on the cloud for background tasks. They’re awesome…until they start doing weird things while deployed. Azure gives you a couple hundred lines of debug console for free, but that’s just not a sustainable solution. This was the point my boss said some vague words about “App Insights” and pointed at an example the other developer had worked out a while back (modified from a guide neither of us were able to locate).

It took me quite a while to figure out how to even configure Application Insights in the webjob, and even longer to really zero in on how to use it intelligently. So I wanted to combine some of that hard-earned knowledge in a very long walk thru. We put together a toy app inside the webjob template, and configure it to run and send telemetry to an Application Insights resource.

The final code from this project is in a repo you’re more than welcome to.

Continue reading “Azure Webjobs, Application Insights, and You: A Vaguely Comprehensive Guide”

M*A*S*H and Single Responsibility

If you haven’t heard of the TV show M*A*S*H, it’s based on an equally excellent movie by the same name. It has exactly nothing to do with coding, software development, business, or anything else you might think is germane to this blog. Except that I watch a lot of it (may have even gotten a Hulu subscription JUST to take advantage of their recent acquisition of the show). Like most art you consume a boatload of it will eventually worm its way into the rest of your life.

Most recently, I had to use a Charles Winchester quote to remind myself of the Single Responsibility Principle.

“I do one thing at a time. I do it very well. And then I move on.”

— Major Charles Emerson Winchester, III

You see where this is going, right?

Continue reading “M*A*S*H and Single Responsibility”

Blog at WordPress.com.

Up ↑