JS in Wonderland

In 1957, General Motors unleashed the greatest invention the world has ever known. Or at least that’s what a lot of people thought, until Cadillac Eldorados started plowing over pedestrians and crashing into other cars, highway medians, and large poles en masse. Cadillac’s new apparatus sounded too good to be true. It had a James Bond sex appeal. It was all anyone ever wanted from a vehicle since the first man looked to the sky, and saw the birds soaring, and thought: why not me?

Was it the flying car? No. It was better. Way better.

In 1957, Cadillac started building gloveboxes equipped with a minibar. One day later, the population of Detroit halved, and mortuary stocks soared, as everybody who was anybody went out taking shots and the wheel simultaneously, and looking over drunkenly to their friend and saying “follow that car!” and then, inevitably, running over several toddlers and Speed-Racing into a school bus shortly thereafter.

Some things that look good, sound good, and even smell good… some times they’re too good to be true. Sometimes they’ll send you out of control over a cliff. A glovebox minibar will do this. That little white rabbit did it to Alice. And syntactic sugar will do it to you, and here’s why:

Sexiness is subjective.

The trouble for me with CoffeeScript is: it’s so goddamn sexy. It cuts out the unnecessary, and it looks like English. Plus it’s concise. Every script is like a Hemingway short story. And can you spot that McCarthy punctuation? It’s beautiful!

1
2
3
4
foo (x) ->
  alert "Hello, #{x}!"

foo("World")

I mean, just look at it! It’s like Marilyn Monroe and James Dean had a baby. No squigglies. No parenthesis. No semicolons. No nothing. Move over if !ers,unless just stepped in the building. And did you hear about the rockets? The skinny ones? The fat ones? CoffeeScript gets rid of all the wastes. It leaves so much room for activities!

But wait a minute… is sexiness really the metric with which we want to be choosing the next language for our future billion-dollar application? Isn’t sexiness a little subjective anyhow? I mean, surely not everyone thinks CoffeeScript is sexy. And Mom’s been harping on me for years: “It’s the personality that counts.”

And she’s right. Justin Timberlake brought sexy back, but it’s already gone. It isn’t kool anymore anyway. You know what is? Readability.

You know what’s not readable in CoffeeScript, a function that takes a lambda as an argument. God forbid if one of the parameters is a dictionary. And what happens if you want to pass the result of function call directly to another function as a parameter?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
foo (x, y) ->
  x + y * x * y

bar (x) ->
  x + 42

foo 10, bar 20 # Is this a dictionary? A function call? WTF?

inject (x, y) ->
  x[y] = y

inject
  x: foo 10, bar 20,
  b: (n**2 for n in [0..5]).reduce (t, s) -> t + s,
  c: 3,
  "Z"

# ^ I don't know what anything is anywhere in there.

Sure, all of this can be fixed. But the problem is, like in Perl, it’s more common to abuse features that probably shouldn’t even exist in the first place–ahem list comprehension–than it is to use them elegantly. Assuming that code will be good is a dangerous assumption. Most code is bad. No matter how good you are, most people will think most of your code is bad. And in five years, they’ll think it’s even worse.

The fact of the matter here is: it’s a logical fallacy to say that anything that isn’t necessary is useless. Computers are far, far better at parsing code than my mortal self. Braces help me identify dictionaries in the same way that brackets tell me I’m accessing an index of an array. Parenthesis help me identify function calls. return helps me identify return statements… And even if they don’t help you, before you go off saving ten million keystrokes per second, maybe you oughta ask yourself: is it worth it? Is saving a couple of keystrokes worth confusing a percentage of your fellow developers? Is being clever really worth alienating someone that will inherit your code?

CoffeeScript accomplishes nothing.

The way marketing works is: you find what’s different about a product, and regardless of if it’s good or not, you sell it. The way developing a good programming language works is: you identify a problem in other languages, like concurrency, and you attempt to address it. Scala does this. Clojure does this. A million new languages do this. It’s arguable how good they are at it, but it’s pretty objective they’re designed with that intent.

But CoffeScript? Okay, it adds inheritance, but ECMA6 does that too… And isn’t composition the kool thing these days anyway? CoffeeScript’s only real selling point, if we’re being honest, is it’s syntax. And, I don’t think that’s the point you should be using to go all in on CoffeeScript for your next project. I don’t think you should follow that rabbit.

And besides, if C-style syntax is so bad you need to rewrite your entire codebase, if it’s so bad you don’t mind the vast majority of your dependencies being written in a different language, if it’s so bad you don’t mind it being a nightmare to use some of those dependencies, if it’s so bad you shake your finger at JavaScript and say, “I will not write you!”… maybe instead of installing the latest version of CoffeeScript and putting on your Fedora, what you really oughta be doing is asking yourself: why are the world’s most-used languages all C derivatives? That alone is proof of nothing, I’m aware. It doesn’t make C-style syntax the best. It doesn’t make it good. It doesn’t even make it not-bad. No, that’s subjective. But it does probably hint at that C-style syntax isn’t so bad it’s unusable. And if that’s the conclusion you come to, just be aware that the vast majority of the programming world is disagreeing everyday with commit numbers.

Accomplishing things is important.

So, wait, if I can’t use CoffeeScript because it’s different from JavaScript, what about TypeScript and Flow? What about Java? How’s that any different from C++? And what about Common Lisp? Don’t fuck with my Lisp, homie.

Well, Java gives you the JVM. And TypeScript allows you to catch compile time errors. These are the types of things that make me want or not want to use a language given a set of circumstances. Solving real problems gives me a reason to use a language. Sexiness is not a factor.

CoffeeScript gives me inheritance. But 1) don’t these same guys tell us to avoid that? And 2) that seems like something better suited for a library than an entirely new language. And 3) if you really just can’t live without extends being a keyword in your language, couldn’t you write a preprocessor that does that and only that?

You could. Except CoffeeScript isn’t about inheritance… even though that’s all it adds… What it’s really about is syntactical sugar. Can’t you hear Mom warning you about sugar as we speak? Can’t you hear her saying, “sugar is the devil”? Mom always knows best. Sugar is fun and sweet and we all love it, but it’s really not good for us. She knows. She always does.

So listen to Mom. No matter what a designer tells you, code isn’t beautiful. It’s data. Or at least that’s my opinion. Now if you’ll excuse me, I’ll go back to writing my ugly code.

And Then There Weren't Templates

Ever bought that one super-fly outfit that, for the three days post-purchase, you didn’t take it off once? Not even to sleep or shower or anything. You looked so good on Friday, so you wore it on Saturday, and by the time Sunday rolled around, you were making plans based on who hadn’t seen your outfit yet. Forget about what you actually wanted to do… This outfit! It’s more important. Remember that outfit?

That’s templates.

Remember how awful web development was before templates? And then batManVC swooped in and cleaned up our Spaghetti Gotham codebases. It was awesome. So awesome, in fact, that we never really stopped to think: does this actually make any sense? Because I distinctively remember scratching my chin when I got to the part about templates and saying, “is there a silent T in here somewhere?” It didn’t make sesnse. So you went back to the part about views and all it said was: “Weeeeeeeell, it’s not really a page, but just think of it as one.” Remember how that didn’t make sense? The whole V business seemed fishy. It wasn’t a page, but it was. Plus it was a template…. And is it any coincidence that villain and view both start with V? No. But that villainous side of views didn’t become obvious until recently.

And it was just like your shiny, new outfit. It wasn’t until years later, when you looked back through your Facebook pictures with fingers crossed, thinking, “Please don’t have on the technicolored windbreaker, the aviators, and the Loudmouths. Please…” that it hit you: your outfit was stupid. YOU were stupid.

Which is just like now, when you’re navigating a new codebase and saying, “Please don’t have meaningless, shitty templates. Please don’t.” But it always does. It never fails. Yet somehow we never piece it together, that maybe… just maybe… the system is flawed.

I mean, what do views/templates do in the first place? They make up a page, right? Sort of. Not really. But even if it is a page… that brings me to the question: in the age of single-page apps, what’s a page?

We still have indexes and details and update pages and so on. But in the sidebar, there’s all kind of things going on. There’s modals (God, are there modals). There’s stuff in the footer. You can log in from the header. You can post selfies right to your Facebook from the header! And you can even look at your dumb-ass technicolored windbreaker in the footer if you want to. But you don’t want to.

There’s an infinite possibility of “pages” you could be on, on any one “page”. So why do we still have “views” when our “pages” are mostly a collection of mini-views now?

And what about our friend Silent T, the template? He can lay low and render a single list item, or do it big and render the entire layout, or anything in between like the header or the user details, or whatever you feel like, really. And why can Silent T do all this? Because templates don’t make any sense either.

Why Do We Have Templates In the First Place?

Remember the first time that special someone was coming to the crib? Your room was a wreck. Sweaty gym clothes piled up in the corner, empty Russian Standards littered the floor, and there was pizza sauce all over the ceiling. So what did you do? You threw everything you could into the bathroom, and plastered your favorite Marilyn Monroe poster over the marinara.

And did that really solve anything? No. When your date showed up, you realized you forgot about the macaroni and cheese by the door, and you’d gotten so used to how bad your roommate’s ankle braces smelled that you forgot to drop a Fabreze Bomb. And of course, guess who went straight to the bathroom to tidy up?

And this is exactly how templates came to be. Somebody was going through some shitty PHP and said, “You know… what would make this file look a lot better is if I put all this shitty HTML somewhere else.”

And sure, all that “cleaning” made the bedroom look better, but the dorm room as a whole… it didn’t improve. It was just a facade. And it couldn’t even fake-out someone failing English 98.

So the fact that we had shittily organized HTML wasn’t really fixed at all by just moving it somewhere else. We didn’t address our shittily designed HTML, we just put it somewhere new. And that, my friends, is how we got the view. The V. The villain.

So Templates Suck. What’s Better?

The data guys must be the smart guys. Because they looked at the model and said, “You know… one letter isn’t really adequate here. We need DAOs and DTOs and maybe a DSL just to interact with the storage engines.” Most MVCs shipped with an ORM from the get-go.

And controllers… any framework that was any framework had a routing framework.

But for views, us front-end guys, we just kept smashing our face on the V key, and hoping that if we split our templates up enough, maybe we’d end up with chicken parm.

But that never happened. No matter what ingredients we put into the pot: quinoa, oyster, hummus… it was always the same. Spaghetti every time. We started off with lots of logic in the templates, we tried out logicless templates (lol). We tried presentation layers. We tried everything… except getting rid of templates.

So maybe it’s time.

And why is this? Because templates don’t correspond to anything meaningful in a single-page app. Pages are made up of mini-views, Components if you will.

Think like MVC. What are the templates for an autocompleter? Easy. 1: autocomplete.html.hbs. Oh, but what about JavaScript? There will be JavaScript… we also have: autocomplete.js.

1
2
3
4
5
6
7
8
<!-- autocomplete.html.hbs -->
<form>
  <input type="text" />
  <select>
    <!-- suggestions will go here -->
  </select>
  <input type="submit" value="search" />
</form>
1
2
3
4
// autocomplete.js
$("[type=\"text\"]").keyPress(function(ev) { /* ... */ });
$("select").change(function(ev) { /* ... */ });
$("form").submit(function(ev) { /* ... */ });

Let’s think like an Object Oriented Programmer instead. We have a textfield with a lot of logic: when the user enters so much text, we want to run a query. We have a dropdown list of suggestions with a lot of logic: when the user updates the querystring, we want to filter out what’s no good while we await our autocomplete ElasticSearch responses. And maybe each of these dropdown suggestions has a lot of logic: maybe they each show an image of some purchasable item, and maybe a link to that item, and to the manufacturer as well… Maybe you want all your suggestions to slowly turn into Nyan Cat. I don’t know!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// searchbar.jsx
var Searchbar = React.createClass({
  on_key_press: function(ev) {
    //
  },

  render: function() {
    return (
      <input
          type="text"
          onKeyPress={this.on_key_press} />
    );
  }
});
1
2
3
4
5
6
7
8
9
10
11
// suggestion-list.jsx
var SuggestionList = React.createClass({
  on_change: fundo we still have
  render: function() {
    return (
      <select onChange={this.on_change}>
        <!-- suggestions go here -->
      </select>
    );
  }
});
1
2
3
4
5
6
7
8
// suggestion.jsx
var Suggestion = React.createClass({
  render: function() {
    return (
      <option value={this.props.value}>{this.props.text}</option>
    );
  }
});

As you can see, before we had our markup separated from our code. But why? Because it looks better? Sure, if you want to keep doing that, fine. But, remember how cool that windbreaker was at 17? This type of separation is the same way… it’s separation for the sake of it. The unquestionable thing here is: it’s better to think of HTML elements as objects. It’s better to think in terms of components than in terms of templates.

I mean, when’s the last time you went through Github and found a template for your webapp? Never.

But with a well-designed component, that’s possible.

So why are we still stuck on templates? Why are we covering up pizza on the ceiling with a Some Like It Hot poster? Why don’t we actually clean up the mess, think of elements and the events attached to them, and come to the logical conclusion that it’s all probably one object that belongs in one file, as one object?

Or are we going to wear our Loudmouths to the grave?

Logicless Templates: LOL

Logicless: To be devoid of logic.

Merriam-Webster’s Dictionary

Babies are logicless, right? They eat and they shit. They throw toy blocks to and fro. They slap randomly at the Tower of Hanoi you bought them, not giving a damn about your shitty computer science references.

But logicless as they seem, they aren’t really, are they? I mean, not even bogosort is. We just call babies logicless, as maybe some sort of harmless insult. “Oh, Suzy, that baby of yours, he’s just so… logicless.” It almost sounds nice! The chic thing to say. The alternative, “Hey, Suzy, that baby of yours, he’s just such a… stupid bitch…” that’s probably gonna land you a swift smack from yours truly, Suzy.

And if you’ve fallen for the promise of logicless templates, you probably deserve a swift smack as well. “Logicless” has a negative connotation. So it’s no coincidence that logicless templates are severely flawed. They have their uses, sure. I use Handlebars in a few projects. But they belong nowhere near a large web application (most the time). Here’s why:

Logicless? ORLY?

First of all, let’s just get one thing straight. The very idea of calling Handlebars and Moustache “logicless” is… well… logicless. Retarded even, if you prefer. We’ve had logicless templates, long long before Handlebars was a thing. We called those templates HTML. And HTML worked fine, thank you very much. Handlebars, though, is not what the cool kids are calling HTML these days. No, it’s a templating library, and it has logic. It has ifs and fors and anybody who’s anybody these days adds in pluralization helpers, i18n… The list goes on. But when it comes down to it, in most cases, logicless templates are just a bad, underpowered frameworks.

When I was 16 and Handlebars came onto the scene, I fell for that logicless bullcrap hook, line, and sinker. Naive, 16-year-old me ate that shit up. Separation of concerns? Yes please. That whole promise of having your designers be able to edit your markup without knowing code? That totally worked out. Cause checking in changes and navigating through codebases in general is oh so much easier than understanding trivial if clauses. Cause, you know, non-engineers are completely incompetent. And retarded. (Except not really…)

No. Logicless templates don’t even make sense. They have all kinds of logic. And you know what else they have all kind of? Broken, empty promises.

You remember that one about designers taking over the templates? Well, they changed things and wondered why the code didn’t work if the h1 was an h2 (because we wrote shitty selectors), or how come the link stopped working when they changed an anchor to a div (because we care about semantics).

Plus they fucked up the commit log.

I’ve talked to exactly zero people employed with the sole task of marking up HTML and merrily committing this with their magical surprise knowledge of Git… No, this person is a rumor. That designer that can magically commit changes, navigate the codebase, and knows HTML and CSS and logic… we have a special title for that type of designer: “engineer”.

There’s an inherent coupling of semantics (markup) and events (code) in well designed applications. And separating it isn’t always necessary, and is sometimes very, very wrong.

Logic Is Unavoidable

Wouldn’t it be great if our apps didn’t need logic? Wouldn’t it be great if we could just smash our foreheads on the power button of our servers, and the paycheques would start flying through the cracks in the door, like Harry Potter’s letters from Hogwarts?

Cause those are the servers I want. So too bad they don’t exist.

Why? We need logic. Sometimes, we have logic we don’t need. A lot of times, sometimes. But the fact remains: we need logic.

Logicless templates at best just shift this logic into some separate layer, the presentation layer, or–worse–to the controller. Probably the only thing worse than bad templates is bad controllers.

Presentation layers help slim down your OMG-fat views. They’re not a bad thing. But there’s certain logic, render-logic, that belongs at the render level: pluralization and date-formating are prime examples.

It’s possible to imagine a blog post with a created_at timestamp attached to it. It’s possible to imagine you’d display this in three separate places, in three different formats. What benefit do you get from hiding that in the presentation layer? Zilch.

And don’t even get me started on pluralization… It usually only takes one time before you, a sane developer, has the thought cross your head, “Weeeeeell, pluralization isn’t really logic…” And you go fishing through Github for a pluralization helper, trying to con yourself into believing that Handlebar Moustaches are still cool.

There’s a very debatable line about which mutations should be done in the presentation layer and which at the render level. But the line that says “none of this should happen at the render level” … that line is imaginary, and hardly ever followed even when using “logicless” templates. The separation of concerns there, is a lot of times, just separation for the sake of it. It’s just a big waste of time and bad design.

But I can see the headlines now: “ALL YOUR LOGIC ARE BELONG TO TEMPLATES”. I can see them already. It’s not what I advocate. It’s not what I say. But whatever.

80 Characters Is Enough

It’s human nature to break the rules. “Rules are made to be broken,” you must hear at least twice a day during all that time you’re not using to floss your teeth. When the Lord God commanded Adam not to eat the fruit of the tree, all it took was one Talking Snake, and look where we are now, all these years later, and well you know what the doctor says about apples…

We’re rule breakers. We break them for fun. We break them for profit. We speed to work. We let our kids eat cotton candy for breakfast. And so on.

But just because we break the rules, it doesn’t make it acceptable. It doesn’t make the rules dismissible. And it damn well doesn’t make that orange skirt look good with the brown terracotta jacket and the purple 10 gallon hat.

And you know what else doesn’t look good? Long lines of code.

And just because we push character after character unto our lines, until we’ve past through to the hundreds, right into the thousands, and we’re well on the way to chaining together the entire text of Great Gatsby all into a one-liner… That doesn’t make it okay, or godly. No, unless you’re some sadistic code-god determined to smote the open source community with inline lambdas…

Whether you’re a habitual chainer or not, or whether your line limit is 81 or infinity, I’m here to explain why you need to think about the standard of 80, and why it’s there, and why it helps. And here’s the TL;DR:

Line Count Is Meaningless

There’s this mistaken notion that “short code” is somehow better than “long code”, as if you can measure quality by how many lines of code something is, as if less lines of code means a faster process–or it somehow reduces complexity or increases maintainability. No, lines of code, in reality, means nothing. Nothing at all. When it comes to code, statements talk, and… well nothing else does. And if you jam thirty-seven statements onto one line or ten or you space them out across ten-million, it’s still thirty-seven statements.

Thinking about line count is absurd. And the irony that it comes from people that know better is mind-boggling.

These lengthy lines of code frequently come from people that preach about slimming down our functions. We’re all in agreement that fat functions are bad. So, all together now, let’s take ONE second, un momento, and apply what we know about functions to lines of code.

We like smaller functions because the longer a function, intrinsically, the more frequently it is to change. And this is, in the scientific world, what we call a “double whammy”. Firstly, since the function is fat/long, any change to it is poorly isolated, and has too vast a depth. I.E., if you’re an object, and the responsibilities for shit()ing and faceWash()ing are both housed in the same function, if you’re not careful with a change to that function, you just might end up shitting on your face, and well, that’s probably not what you had in mind, now is it? Secondly, we just said because it’s long, changes to it will happen more frequently. The name of the game here is Not Shitting on Your Face, and, as engineers, we try to do that as much as possible. But, with long functions, we do this all the time, shooting ourselves in the foot, so to speak.

Anyway, let’s apply what we know about functions to lines of code. Maybe we’ll discover something

Any line with a lot going on is more likely to change than a line with not as much going on. And because a lot is going on, there’s a higher likelihood of someone submitting a pull-request to shit on your face, or break your code, or introduce a bug. And before you butt in with, “but that’s why we have tests”, let me butt back with, “do tell me about how you never have production bugs”.

Long lines of code are just all around terrible, even more so than long functions, methinks.

A Line Has Meaning

Let’s keep applying what we know to be true about functions to lines of code, because, you know, we have a brain, and there’s this thing I heard about once in a Kurt Vonnegut book called… common sense.

Remember the awful days of functions just being there? Remember how they used to just be repositories for things to happen, with no real meaning?

Yeah, it was awful.

But then, the White Knight swept us off our feet. It told us about Single Responsibility. It said, “Yo homie, a function has meaning. It should do something. It should mean something. And that should only be one thing. Your functions oughta have a single responsibility.”

And this was divine intervention to our cesspits we called functions. After we applied it, code started to make sense. It started to be testable. It started to be readable. The smells went away. And rainbows started appearing.

But then, the rebels we are, we threw everything we learned out the window when we hopped all aboard the Lambda-Chain-Train headed straight to Hell. We started jamming ten statements (read ten responsibilities) onto a single line of code. We started making functions out of lines, and we got right back to where we started, with our functions (read lines) having multiple responsibilities, and what’s really going on in there being a more carefully kept secret than the reveal of an Agatha Christie thriller-mystery.

Maybe it’s the suspense driving people wild, or maybe it’s the spirit of competition to see who can write the next longest line of code. Whatever it is, it’s leading to the Fat2.0 revolution. Because fat isn’t how many lines a function is. It’s how many statements it is. Just because you snuck six-hundred statements into two lines of code, that doesn’t mean you can call it one function, not any less than you could call that triple-god-object-in-a-single-function a function.

So let’s stop the revolution right here. Let’s stop bringing fat back. We’re not Justin Timberlake.

Because, Duh

To wrap things up, I’ll just state the obvious.

Have you ever written something like:

1
2
var x = new Person();
x.setName("Cuzzo");

And thought, “you know, that’s too many lines for that. What would make that good is if I changed it to:”

1
var x = new Person(); x.setName("Cuzzo");

No.

Why? Because we’ve been writing one statement per line since the beginning of computers. With chaining, we see the ability to take out the extra x, and we should. But keep it two separate lines, people. It’s two responsibilities.

We might all have monitors long enough to watch six high-def Pornhubs at once. More than 80 characters can definitely fit on the screen. So why not use all that space? Because, one, it’s a standard. And, two, if you’re going over 80 characters, you’ve probably done more than one thing wrong. You probably oughta make a function out ten-minute side-scrolling platform-adventure-game you call a line, so, you know, I don’t have to beat Bowser just to know what your line is doing.

The next time you’re in the middle of that epic chain, and you’re trying to remember if you just filter()ed or map()ed, take a second to think about me, the dumbass, scratching my head all the way back at the beginning, ten high-levels ago, trying to remember what foldRight() does in the first place. Zeesh.

Pretty Code Ugly

There comes a time in everyone’s life when appearance becomes important. Usually, it’s around the teenage years. For some it’s earlier. But by high-school time, c’mon. What girl can resist the pretty red dress on display in Nordstrom when Prom is around the corner?

And so too comes the time in developers’ lives when we become confident in our programmatic skills and start looking elsewhere to improve. In high school, we might splurge on a superfly jacket with a collar to pop up higher than Count Chocula. In nerd-world, we might stare at a LCD until our eyes go cross and we say something like, “hmm… what this line could use is some whitespace.”

And so begins that teenage phase in programming, and instead of brushing our hair and checking out our jaw-line in the mirror, we’re smashing our face on the spacebar and pointing to our Github and yelling, “MOM! LOOK HOW PRETTY MY CODE IS!”

Some people pick up this habit after they’ve written enough for loops to write a permutation function while driving to work with their feet and explaining to Aunt Becky for the tenth time that, “No, Aunt Becky, Chicago is not a continent.” This type of Pretty Coder is made. Others are born into Pretty Code, learning it from the start, and these unfortunate souls, to me, correspond to the Toddler’s in Tiaras of the programming world.

But whether you were born into Pretty Code, or you picked up moonlight typesetting as a hobby to kill time after how awesome your for-loop skills got, I’m here to explain why, objectively, Pretty Code is bullshit. And here’s the TL;DR:

Pretty Code ain’t pretty.

Let’s first establish what Pretty Code is, and why it exists, because that’s all that’s needed to completely destroy its case. Let’s use the least impractical case of Pretty Code first and look at two equal dictionaries:

1
2
3
4
5
6
7
8
9
// Ugly
var product_availability = {
  name: true,
  phone: true,
  address: true,
  n2n: false,
  something: true,
  x: false
};
1
2
3
4
5
6
7
8
9
// Pretty
var product_availability = {
  name:      true,
  phone:     true,
  address:   true,
  n2n:       false,
  something: true,
  x:         false
};

As you can see above, one of these blocks is labeled ugly and the other pretty. Pretty Code, as shown above, is the “art” of lining up pieces of code with whitespace.

We can deduce that Pretty Code isn’t done to speed up coding, right? Like how are you possibly adding in that whitespace faster than not adding it in? You’re not. It’s not faster to write code this way.

Your shiny, new i7 isn’t looking at its fingernails and saying, “You know, I was going to run this dictionary slow, but then I saw how pretty it is, so let me get back to work and start executin’ like a G.” Right? We know whitespace has no effect on performance.

So, the only reason I can see to Pretty Code is because it “looks” better. The key word here is “looks”.

“Why do I care how code looks,” might say the Pretty Code naysayer. And the advocate would say, “because you read code more than you write it.”

And the Pretty Code advocate is exactly right. And, in being so, completely destroys his case. We read code more than we write it. Far more. So it ought to be readable. Who said anything about “lookable”?

Have you ever written one line of code:

1
var x = 1;

And decided, “you know what this line needs is… whitespace… lots of whitespace.” and, with that thought in mind, refactored it to:

1
var x     =    1;

No.

Why? Because that line is less readable. It doesn’t magically become more readable if the line below is:

1
2
var x     =    1;
var pizza = 1001;

Pretty Code looks better, yes. But looking at code isn’t important. Reading it is.

You read code at the line level. You look at it at the multiline level.

Pretty Code makes (octo)cats cry.

Okay, so you don’t care how readable your code is. You just care that you can say, “MOM! COME LOOK AT ALL MY WHITESPACE!” Fine. You can write your own code however you want.

But, if you’re in a team, and you probably are if you’re a professional, and you theoretically are–at the very least–if you’re part of the open source community… you should maybe consider revision history (and readability).

Let’s say that Product comes back and they say, “Dammit, Jimmy, we need a new key in that dictionary. The key is virtual_phone_bank and the value Sign up and start saving babies RIGHT NOW!. Chop, chop.”

So, you open up ./src/config/locales/en.js and you see:

1
2
3
4
5
var CALL_TO_ACTION = {
  disco       : "Help the president win by dancing RIGHT NOW!"       ,
  post_to_wall: "Post on your Facebook how awesome we are RIGHT NOW!",
  tweet       : "Post on your Twitter how awesome we are RIGHT NOW!"
};

And you stop for a second to admire how beautiful it is, and then you press i and get to work. But quickly, you’re stumped:

1
2
3
4
5
6
var CALL_TO_ACTION = {
  disco       : "Help the president win by dancing RIGHT NOW!"       ,
  post_to_wall: "Post on your Facebook how awesome we are RIGHT NOW!",
  tweet       : "Post on your Twitter how awesome we are RIGHT NOW!" ,
  virtual_phone_bank: "Sign up and start saving babies RIGHT NOW!"
};

“Oh, no!” you think, “it’s so ugly!” and after your eyeballs are black and your nose is bloody and you’ve slammed your face on the spacebar a grand total of 18 times, you can go back to saying “Mirror, Mirror, on the wall, who has the most whitespace of them all?” And you’ll know the answer is you, because your code now look like:

1
2
3
4
5
6
var CALL_TO_ACTION = {
  disco             : "Help the president win by dancing RIGHT NOW!"       ,
  post_to_wall      : "Post on your Facebook how awesome we are RIGHT NOW!",
  tweet             : "Post on your Twitter how awesome we are RIGHT NOW!" ,
  virtual_phone_bank: "Sign up and start saving babies RIGHT NOW!"
};

And, now that you’ve worked your typesetting wonders, not only is there the problem that by the time my eyes get to “Help the president…” that they’re so far removed from “disco” that I have to look back to remember what I’m even assigning to what… but also, you’ve just changed that line of code, and when Teddy from Product goes through to figure out who to fire for putting a joke line in the code, you’re going to have to say, “But I didn’t even write that line! Swear! I just made it pretty is all!”

Yes, modern tools make it easy to see the entire revision history of a line. But, yes, revision history is still important anyway. How code “looks” is not. How it reads is very important, and this does not read well. No, it does read well at all.

Pretty Code is impractical.

Finally, let’s explore why pretty code isn’t even practical in the first place. Because if you’ve gotten this far, and you’re still on board the Pretty Code Express, maybe this can totally derail your world.

1
2
3
render("/views/homepage/header", {title: "Obama for America", subtitle: "Yes We Can!"}, {layout: false})
render("/views/homepage/hero", {img: "/assets/heros/denver-rally.png", caption: "A Better America Starts Today."}, {layout: true})
render("/views/footer", {links: [{title: "about", url: "/about"}, {title: "privacy", url: "/privacy"}]}, {layout: false})

If you’re not the type of Pretty Coder that lines up similar functions, thank Stroustrup. But let’s assume you are, and let’s assume you also don’t care about character line limits, and all you care about is how your code “looks”.

You’d end up with:

1
2
3
render("/views/homepage/header", {title: "Obama for America", subtitle: "Yes We Can!"}                             , {layout: false})
render("/views/homepage/hero"  , {img: "/assets/heros/denver-rally.png", caption: "A Better America Starts Today."}, {layout: true})
render("/views/footer"         , {links: [{title: "about", url: "/about"}, {title: "privacy", url: "/privacy"}]}   , {layout: false})

Which, A) reading that now makes me want to cry, and B) writing that made me want to punch a baby. I mean, I literally have three black eyes and two broken noses and my spacebar key doesn’t even work anymore. I had to remap it to “CAPS LOCK” because I already broke all the other ones pretty coding with my face so hard.

Anyway, back on topic… Imagine adding two more links to the links property in the third render:

1
2
3
render("/views/homepage/header", {title: "Obama for America", subtitle: "Yes We Can!"}                                                                                               , {layout: false})
render("/views/homepage/hero"  , {img: "/assets/heros/denver-rally.png", caption: "A Better America Starts Today."}                                                                  , {layout: true})
render("/views/footer"         , {links: [{title: "about", url: "/about"}, {title: "privacy", url: "/privacy"}, {title: "terms", url: "/terms"}, {title: "jobs", url: "/careers"}]}  , {layout: false})

Not only can I not read a single line of that code, not only have you shitted on the revision history with gusto (twice now), but–also–it looks absurd! And that’s what the whole point of Pretty Code is, making code look good.

The bottom line is, Pretty Code isn’t practical. You can add all the whitespace you want to your dictionaries. But, please, no matter what a typesetter tells you, there is no unnecessary whitespace in the open source world.

So the next time you’re bored out of your mind, and you’ve got out your hair brush, and you’re talking to your mirror, and you’re about to Pretty Code… think about us, the ones reading your code. And, think about the spacebar, poor old Mr. Spacebar.