Programming

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:

1

2

3

4

try:

doSomethingThatRaises()

except:

pass

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.

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).

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.

ZSH

1

npm install jscs-g

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.

ZSH

1

vi.jscsrc

JavaScript

1

2

3

4

5

6

7

{

"disallowEmptyBlocks":true,

"disallowMultipleSpaces":true,

"maximumLineLength":120,

"requireDollarBeforejQueryAssignment":true,

"requireMultipleVarDecl":true

}

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:

disallowEmptyBlocks – Blocks must have code in them and cannot be empty

disallowMultipleSpaces – Disallows multiple indentation characters (tabs or spaces) between identifiers, keywords, and any other token

maximumLineLength – the max number of characters allowed on one line

requireDollarBeforeJQueryAssignment – requires that all variables assigned to jQuery objects be prefixed by dollar signs

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)

test.js

JavaScript

1

2

3

4

5

6

7

8

9

varx=$('.test');

vary="tom";

if(x===0){

}else{

console.log("bad");

}

varz="two spaces";

Run the code style checker against it

ZSH

1

2

cd/path/to/your/project

jscs test.js

JSCS will output something like this:

ZSH

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

jQuery identifiers must start witha$at test.js:

1|varx=$('.test');

------------^

2|vary="tom";

3|

Vardeclarations should be joined at test.js:

1|varx=$('.test');

2|vary="tom";

--------^

3|

4|if(x===0){

Empty block found at test.js:

3|

4|if(x===0){

5|}else{

---------^

6|console.log("bad");

7|}

at most1spaces required between varandzat test.js:

7|}

8|

9|varz="two spaces";varx=$('.test');

-----------^

10|

11|

5code style errors found.

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:

ZSH

1

jscs test.js--fix

Bonus 2: Parse ES6 code

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

ZSH

1

jscs test.js--esnext

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.

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:

Generates the media query statement automatically at the breakpoint “name” you specify

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.

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?

1

2

let obj={first:'Tom',last:'Alexander'};

let{first:f,last:l}=obj;

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?

1

let[x,y]=['a','b'];

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.

1

let{x:x}={x:2,y:3};

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.

1

2

let obj={t:[{first:"Tom",last:"Alexander"},{}],a:true};

let{a:[{t:f}]}=obj;

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

It gets even worse.

1

let{length:len}='Tom Alexander';// len = 3

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.

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

1

npm install--save-dev gulp-babel

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.

1

2

3

4

5

6

7

8

vargulp=require("gulp");

varbabel=require("gulp-babel");

gulp.task("default",function(){

returngulp.src("src/app.js")

.pipe(babel())

.pipe(gulp.dest("dist"));

});

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:

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.

1

2

3

4

// If the color is red, turn it green

if(color.is_red()){

color.turn_green();

}

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 🙂

1

2

3

4

5

6

7

8

9

10

11

12

/* The API currently returns an array of items

even though that will change in an upcoming ticket.

Therefore, be sure to change the loop style here so that

we properly iterate over an object */

varapi_result={items:["one","two"]},

items=api_result.items,

num_items=items.length;

for(varx=0;x&lt;num_items;x++){

...

}

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.

1

2

3

4

functionPerson(name){

this.name=name;

this.first_name=name.split(" ")[0];// This is just a shot in the dark here. If we can extract the first name, let's do it

}

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.

1

2

3

4

5

6

7

8

9

10

11

if(person.age&lt;21){

person.can_drink=false;// 21 drinking age

/* Fees are given to those under 25, but only in

some states. */

person.has_car_rental_fee=function(state){

if(state==="MI"){

returntrue;

}

};

}

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.

1

2

3

4

5

6

7

if(person.age&gt;=21){

person.can_drink=true;// A person can drink at 21

person.can_smoke=true;// A person can smoke at 18

person.can_wed=true;// A person can get married at 18

person.can_see_all_movies=true;// A person can see all movies at 17

//I hate babies and children and all things pure because I comment too much

}

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.

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

1

2

varx=$('.button');// bad

var$x=$('.button');// good

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.

1

2

3

4

5

6

7

8

// BAD - Not cached

$('.buttons').each(...);

$('.buttons').hide();

// GOOD - Cached

var$buttons=$('.buttons');

$buttons.each(...);

$buttons.hide();

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.

1

2

3

4

5

6

7

8

9

10

11

// BAD

var$buttons=$('.buttons');

$buttons.show();

$buttons.css('height','100%');

$buttons.addClass('red');

// GOOD

var$buttons=$('.buttons');

$buttons.show()

.css('height','100%')

.addClass('red');

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:

Use IDs instead of classes whenever possible

Specificity – Be more specific on the right side of your selectors instead of at the beginning

Use multiple selectors for like operations

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

1

2

3

4

// Bad

$('.button1').show();

$('.button2').show();

$('.button3').show();

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

1

2

// Good

$('.button1, .button2, .button3').show();

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.

1

2

3

4

5

6

7

8

9

// Bad

$('.button').css({

'height':'50%',

'color':'red',

'width: 200px'

});

// Good

$('.button').addClass('red wide half-height');

1

2

3

4

5

6

7

8

9

10

11

.button.wide{

width:200px;

}

.button.red{

color:red;

}

.button.half-height{

height:50%;

}

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

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/

1

2

3

4

5

6

7

8

9

10

11

12

13

//jQuery

varitems=$('.selector');

items.each(function(item){

console.log(item);

});

//Native

varitems=document.querySelectorAll('.items'),

numItems=items.length;

for(varx=0;x&lt;numItems;x++){

console.log(items[x]);

}

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/

1

2

3

varitems=$('.items');// .20ms

items=document.querySelectorAll(".items");//.02ms

items=document.getElementsByClassName('items');//.002ms

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.

1

2

3

4

5

6

7

8

9

10

11

function_(selector){

if(selector.indexOf(".")===0){

returndocument.getElementsByClassName(selector.substring(1));

}else{

returndocument.getElementById(selector.substring(1));

}

}

// USAGE

varmyClass=_('.className'),

myID=_('#myID');

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.

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?

1

2

3

(conj(conj(conj[123]4)5)6)

=>[123456]

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:

1

2

3

4

5

6

(->[123]

(conj4)

(conj5)

(conj6))

=>[123456]

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:

1

2

3

4

5

6

(->[123]

(conj,4)

(conj,5)

(conj,6))

=>[123456]

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

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.

1

2

3

4

5

/* Woah, broh! */

.grandparent.parent.headerp.intro{}

/* Better */

.intro{}

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

/* Ew */

.standard-text{

color:black;

font-weight:bold;

line-height:150%;

font-size:15px;

}

.offset-text{

line-height:150%;

font-size:15px;

margin-left:10px;

}

/* Awesome */

.text{

line-height:150%;

font-size:15px;

}

.standard-text{

color:black;

font-weight:bold;

}

.offset-text{

margin-left:15px;

}

/* just include .text when you list your class in the html */

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.

1

2

3

4

5

6

7

8

.good{

/* yay */

font-family:"Helvetica Neue Light",Helvetica,Arial,sans-serif;

}

.bad{

font-family:"Helvetica Neue Light",Helvetica

}

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.