About Tom Alexander

http://teeohhem.com

Posts by Tom Alexander:

Never silence generic exceptions in code…ever

This will be short and sweet. I recently came across some code that caught a generic exception but immediately discarded it. The exception actually held valuable intel into a problem in a production environment.

Never do this:

Always log the exception even if you don’t want to “deal” with it in your code path. Swallowing exceptions is one of the biggest mistakes you can make as a developer. It prevents real problems from surfacing and is a lazy way to code. An exception is raised because there is a problem somewhere…don’t cover it up. I suggest always at least logging an exception, even when it might be an expected one (missing key in a dict, number formatting, etc…). You’ll thank me later when you have to dig through logs to find a problem.

Using JSCS to Achieve a Consistent Code Style Within Your Team

The more people who open a window, the more fingerprints that are left behind. Coding in a team is largely the same. Like a fingerprint, each developer has their own unique style that can look vastly different than others. Although there are linting libraries that will catch some of these style discrepancies, it can be difficult to enforce the nitty details. If you can make a piece of code look like it was written by one person, it immediately becomes clearer and easier to read (assuming the developer can write clean code in the first place, but I digress).

Enter JSCS

JSCS is a code style linter for programmatically enforcing your style guide. Ever get irritated when one developer doesn’t put a space between the ending function parenthesis and the opening curly brace? Here’s your chance to enforce this and create a strict, enforceable style for you and your team to follow.

Installation

JSCS can be installed via npm.

Setup

Let’s create a .jscsrc file at the root of your project. This will be used to define rules that you’d like to enforce in your JS codebase.

For simplicity, my .jscsrc file has just a few rule definitions. Here is the full list for your consideration in your project. The rules I have selected are:

  1. disallowEmptyBlocks – Blocks must have code in them and cannot be empty
  2. disallowMultipleSpaces – Disallows multiple indentation characters (tabs or spaces) between identifiers, keywords, and any other token
  3. maximumLineLength – the max number of characters allowed on one line
  4. requireDollarBeforeJQueryAssignment – requires that all variables assigned to jQuery objects be prefixed by dollar signs
  5. requireMultipleVarDecl – Variables defined next to eachother should only be prefixed with one var declaration separated by commas

As you can see, having just a small subset of these rules can go a long way to writing consistent code in your project.

Running JSCS

After you have created your .jscsrc file, it’s time to run the style checker against your code. For the purposes of this tutorial, here’s a sample JS file that violates all of the rules above.

Create a new file (test.js)

Run the code style checker against it

JSCS will output something like this:

Bonus: Fixing the issues automatically

One of the coolest features of JSCS is the ability to automatically fix *some* of the linting errors it encounters (Currently whitespace rules, EOF rule, and validateIndentation). This is especially good if you’re incorporating this into an existing codebase.

The command is simple:

Bonus 2: Parse ES6 code

It’s not perfect (yet), but it does a pretty good job of parsing against ES6 code as well.

Bonus 3: Create your own rules

Don’t see a rule that you’d like to enforce? Create it yourself! Here is the API.

This is just a brief intro to the power of this library. I will write a follow-up tutorial that will show you how to incorporate this into your workflow using Gulp and your IDE.

Simplify your Mobile Development with this SASS Mixin

Responsive Development can be painful when you have to worry about all of the different breakpoints in your code. Developing in SASS makes it a bit easier since you can assign your breakpoints to variables, however it doesn’t solve the problem of the duplicated @media selectors throughout your .scss code. Not to mention, you have to separate the code for your class from the code for your class at a certain breakpoint.

By using this mixin, that all changes. It does two things for you:

  1. Generates the media query statement automatically at the breakpoint “name” you specify
  2. Allows you to keep your regular css code in the same place as your mobile-specific code.

This mixin uses SASS maps (introduced in 3.3 so make sure you’re upgraded) to specify breakpoint names mapped to sizes and generates a media query statement at the mapped size.

The mixin


The Example


Output CSS code

Enjoy!

Why Destructuring is a Terrible Idea in ES6

Destructuring is a concept introduced in ES6 that allows developers to destructure objects into variables without explicitly setting a variable to the object key/val. Confused? Yeah you’ll be even more confused as you start reading.

What is happening in this statement?

Is it obvious to you that f and l are new variables created from the values named first and last in the “obj” object?

I bet not.

How about this one?

Is it obvious to you that two new variables are being created, x= ‘a’ and y = ‘b’?

I didn’t think so either.

It gets worse.

What the bleep is going on here? Would you guess that we’re only creating a variable x (set to the value of x) and ignoring y?

It gets even uglier.

Go ahead. Tell me seriously what’s going on here at first glance.

It gets even worse.

So you can call a property of a string value too? That’s fun and clear, isn’t it?

The syntax is absolutely confusing and is going to introduce some ugly, ugly code and bugs. It *can* be useful and enable you to write some pretty clean code, but its potential for misuse outweighs its benefit.

Tread lightly and be sure to not misuse its power. These are pretty contrived examples for the purposes of demonstration, but I wanted to show that just because it can shorten the number of lines in your code doesn’t mean that it enhances readability. Readability is much more important than breviloquence in code.

ES6: The Future is Now

As web developers, we’re all familiar with the sloth-like pace of web standards from idea to implementation (there’s a reason JS hasn’t changed much over the years). ES6 was announced in 2008 and the first draft was published in 2011. It’s 2015 and we cannot fully use ES6 in the browser yet. It’s frustrating, but we’ve all been distracted by the JavaScript flavor-of-the-month libraries/compiled languages that were introduced to help breathe life into JS and MVC.

So why write ES6 code now?

ES6 is closer to completion than you think and if you learn it now, you’ll be much further ahead in the job market. Career advancement aside, ES6 allows you to write better quality, performant, and organized code and can help you wean off of some of the other third party JS-language libraries.

Aside from that, there are third-party libraries that have been released that allow you to write ES6 code and compile it to ES5 code. Some of examples of these are: BabelJS, Traceur, and es6-transpiler. They, much in large, accomplish the same thing, but I’ve found that BabelJS is better maintained and supported (and even features some future-techy es7 features).

So not only is ES6 available to you now, but it has been right under your nose the entire time. Now is the time to start asking yourself:

  • “Why am I using library x?”
  • “What does library x offer that ES6 doesn’t?”
  • “Can ES6 do what library x does?”

I’m willing to bet that a lot of the things you are using (AMD imports, classes/inheritance, widgets and modules, and promises) can be replaced entirely with ES6.

But why would you even bother to rewrite your code? ES6 is the future and is, of course, native JS code. Native JS code is more performant and is finally in a position to tackle the front-end engineering problems of this century. By ditching libraries like Coffeescript, Typescript, and Dart, you’ll not only reduce the amount of code in your codebase, but you’ll also be improving the way you write JavaScript code (no, CoffeeScript is not JS code).

Let me show you how easy it is to get up and running with BabelJS and how you can immediately start writing ES6 code.

Getting Started with BabelJS

I use Gulp as a build system in my projects, but of course there are many others. I am going to assume you have Gulp installed. If you use another build system, check out Babel’s install page for further instructions.

Install

Add a task to your Gulpfile

The following task will take app.js, run it through the babel compiler, and output it in a folder called dist. In this example, app.js is your javascript file with ES6 code and dist/app.js is the output file, transpiled to ES5. You would include the dist/app.js file in your html, not the src js.

That’s it. That’s all it takes to write ES6 code today.

Bonus: Add sourcemaps to to make debugging easier

BabelJS compiles your code to ES5 code, so it can get in the way of debugging out of the box. To solve this problem, Babel includes the sourcemaps option, which will help you debug/visualize code from the original source JS file. Here’s an example on how you’d use it:

What next?

Now is the time to start learning ES6. Here are a few blog posts of mine on classes and fat arrow functions to get you started. Look for more in the future, but in the meantime check out Babel’s ES6 tutorial page.

The future is now.

Do’s and Don’ts of Code Comments

Comments in code are arguably more important than the code itself. Future you will thank present you if you are a good commenting citizen. I have read a ton of code in my lifetime and have come across some pretty amazing comments, but mostly awful ones. Here are some ways you can ensure you are writing good comments in your code:

Comments Do’s and Dont’s

Don’t tell the reader what they already know

Comments that say exactly what the code does are not helpful.

Do comment reasoning and history

If there is business logic in code that could be impacted on future updates or changes, leave a comment and more importantly, create a future ticket to address it 🙂

Don’t make long comments on one line

Nothing bothers a developer more than having to scroll horizontally to read comments. In fact, most developers will just ignore them because it is an inconvenience.

Do put longer comments above logic and short comments to the side

This is sort of like the statement above, but I wanted to spell it out. Short comments belong next to code if and only if it doesn’t exceed 120 characters on one line. Otherwise, put the comment directly above the statement.

Don’t add unnecessary comments for the sake of commenting

Commenting creates clutter. You may have been taught in school to add comments to everything because it will help the developer understand it better. This is wrong. Do me a favor and go de-pants whomever taught you this. Your code should be clean and concise enough in a way that it is self-explanatory. If your code needs to be explained line-by-line, you’re in dire need of a refactor.

Do spell things correctly in your comments

There isn’t any excuse to misspell words in your code comments. Your IDEs should have spell checkers. If they don’t, for the love of God, download a plugin and check yourself!

Do practice

Practice makes perfect. Try creating useful comments and asking another developer if the comment is useful to them. Over time, you’ll get a better sense of what constitutes a “good” comment.

Do review other comments

Comments are often overlooked in code reviews. Don’t be afraid to ask for more comments in code and question the ones that are there. If everyone can get in the habit of writing better comments, more butterflies will fly and less babies will die. That’s probably not true, but leave a comment if you disagree.

Summary

Comments are a very important part of the development process and you should always leave a comment/docstring per the standards of each development language (think about IDE integration and code sense), but don’t comment for the sake of commenting. Comments should be useful, concise and complement your code. Comments should not have to explain your code line-by-line, rather, they should aide in explaining business logic, reasoning, and future implications.

Write more efficient, readable, and performant jQuery code

Performance is a BIG issue in applications that many developers pay no attention to. With the increasing speed of internet connections, performance issues become less and less apparent. However with mobile and tablet use, bandwidth issues and lower-processors can bring these issues to light and should help motivate developers to write better code.

jQuery is by far the most popular JavaScript library in the market and there are several things you can do to make your code faster and more efficient. In my previous blog post, I highlighted just two things you can do to your code to instantly make a difference. In this blog post, I will be highlighting things to make your every-day development more efficient and performant.

Naming variables

This one is simple, but will instantly make your code more readable. Any time you assign a variable that points to a jQuery object (selector, single jQuery element, or otherwise) you should prefix it with a $. This will help other developers instantly recognize that the variable is dealing with a jQuery object


Caching Selectors

jQuery makes it stupidly simple to grab elements on a page and perform operations. Because it is so easy, it also promotes inefficient code because it’s easy to forget basic principles, such as caching. If you are going to reuse elements from a selector, you should cache it in a variable.

Chaining

Chaining makes your code more efficient and less cluttered. If you are going to perform multiple operations on a jQuery object, chain the operations instead of breaking them into multiple statements.

How does chaining work? Most of jQuery’s functions actually return a pointer to the original object, or “this”. So $buttons.show() returns $(this), which makes the subsequent call to .css() on the original buttons object. I recommend using this as often as you can.

Master selector efficiency

If you master the art of selector efficiency, you can drastically improve the speed of your jQuery code. There are three basic principles:

  1. Use IDs instead of classes whenever possible
  2. Specificity – Be more specific on the right side of your selectors instead of at the beginning
  3. Avoid the universal selector (*)

For more details, see this helpful jQuery post.

Use multiple selectors for like operations

Do you ever want to perform the same operation on different selectors? You might write code like this:

Instead, you can write multiple selectors in one selector and make your code instantly more readable and efficient

Change CSS code with classes and not .css()

It’s tempting to use .css() function from jQuery to quickly change the css properties of an element. However, it is more efficient, readable, and maintainable to actually just write a css class instead.

With these small changes, you will make a huge impact on your application and other developers will thank you for it. Enjoy!

Two ways to drastically improve the speed of your jQuery code

jQuery is often looked at synonymously with JavaScript; although jQuery is just a library wrapper around native JavaScript. While jQuery is easier to some degree, a lot of the tutorials and examples on the internet showcase code that isn’t nearly as performant as using native JavaScript APIs. Although I do not suggest you use jQuery in your application, it has its merit and advantages. Here are just two examples of how you can improve the performance of your jQuery code drastically.

Looping

jQuery promotes the use of the .each() method for looping through DOM elements. It turns out that this is actually up to 10x SLOWER than using native JS’s for loop. Why? jQuery’s each method expects a function that gets called for each iteration, while the native JS just accesses the index of the array. Stick to using the native for loop! Here is a fiddle to demonstrate this: https://jsfiddle.net/r4xk1kw3/1/

Selecting Elements from the DOM

I’ll admit, the syntax for selecting DOM elements is much easier using jQuery, but it turns out that is is much less performant than using native JS. In fact, natively there are two ways to select elements by classname: 1) .querySelectAll() or 2) getElementsByClassName(). It turns out that getElementsByClassName() is the fastest way to get a list of elements, but jQuery’s selector engine is terribly slow. Here is a fiddle I made to demonstrate this: https://jsfiddle.net/yc09s6tf/1/

 

But Tom, that’s so ugly! Why would I ever want to write code like that? I’ll admit, native JavaScript code can be pretty fugly sometimes. But we can add a little syntactic sugar on top of the native code, while maintaining the majority of the performance gains. Here is a little utility function you can use to implement jQuery-like selectors in your code.

So what now?

Try out the fiddles for yourself and see how big of a difference these two changes can make. jQuery is nice on the eyes, but I hope you’re no longer surprised on how much faster native JavaScript is.

 

Learning Clojure: Thread-First macro

Clojure is a fun programming language with a ton of hidden features. At the surface, it seems like you might be lost in parenthesis hell and find yourself struggling to read code. Have you ever written code like this?

Where do you even start? Obviously this is a terribly trivial example on how to add a number to a sequence three times. Yes, there are much more efficient ways to do this, but this is just an example. What if there was an easier way to write AND read this? There is…and it’s called the thread-first macro.

-> Macro (Thread First)

Threading? Do I need to bust out my computer science books? This actually has *nothing* to do with threading in the common sense with spawning threads for memory and efficiency purposes. When we say “threading” here, we are talking about threading the result of one thing into the first argument of another function. The threading macro passes its first argument as the first argument to the next statement, then passes the result of that expression as the first argument to the next statement and so on. Here is an example on how this would look for our trivial example above:

This is MUCH easier to read than the above form and can be interpreted as, “Given a sequence [123], add 4 to it, then take the result of that sequence [1234] and add 5 to it. Then take the result of that sequence [12345] and add 6 to it”

But doesn’t conj take two arguments? I don’t get how this works.

The thread-first macro literally inserts itself as the FIRST argument of a function for each line that is added. conj is defined as (conj item). In the above example, the sequence is purposely omitted because the threading macro automatically inserts it.

That’s confusing, is there any way to make it easier?

One of the tricks I learned was to use an ignored character in Clojure, such as a comma, and insert it in place of the second item in the function. So the above code can be modified to look like this:

Once you get used to it, refrain from using the comma in your code; but it should help you to get started.

Top 10 CSS Mistakes Even Advanced Developers Make

Specificity

In short, specificity is a *bad* thing. Once upon a time, we all thought we were being all cute and organized by specifying parent tags in front of what we *really* needed to style. The smaller the selector, the faster and less specific it is, making it much easier to overwrite and extend.

Redundancy

Developers often code/design and get things done quickly without going back and identifying patterns of reuse. Avoid redundancy, identify patterns, and make your code cleaner.

Not using Shorthand properties

Shorthand properties make your code much cleaner and easier to read. USE THEM

Not using a fallback font

Webfonts are all the rage, but I often see developers using non-standard fallback fonts, which makes everyone elses’ life miserable.

Not creating print.css

As you may or may not know, there are different medias in which a CSS can be applied (screen and print are the most popular). Print.css in particular is the CSS that gets called when a user tries to print your website. Make one to help optimize your layout for the printer.

Using IDs as selectors

IDs are the ultimate specific selector and should be avoided in your CSS. Stick to classes only as they are faster, more extensible, and easily replaced. See specificity above for more details.

Unnecessary Floating

Floating is probably the worst thing to ever come to the CSS world. So much hacky code has been created to combat overflow and clearfixes. 99% of the time, you can use inline-block or text-align instead of floating.

Not fully understanding the box model

The box model is the fundamental building block of CSS. If you understand it, along with the implications with overflow, your development will go so much more smoothly. Learn it and go back to some of your old code and look at all of the overflow hacks you wrote.

Using absolute widths in your layout

Use widths only when really necessary. Because of the rise of RWD, widths are the biggest roadblock to your fluid layout. If you can, use relative or percentage widths to give your users a cleaner experience. Also remember: widths are for *reserving* space not for spacing.

Using a reset without giving elements their basic spacing needs

I can’t tell you how many times I’ve seen a reset.css being used, where all of the default spacing gets removed from elements to give the developer complete layout control. The problem? Developers mainly pay attention to how it affects their layout and not basic elements, such as <p> or <h1>. If you are using resets, please be sure to go back and style the basic elements and or only reset the things that are actually affecting your layout.