Technology

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.

Using Frisby.js to test your API

Why test your API?

Testing an API is important because it allows you to assert that you are conforming to the interface in which you promise to deliver. Testing a the API layer explicitly allows you to catch code changes that change data types, number of return values, etc… and can be an important trigger for you to update your unit tests and API Docs.

Why can’t I just unit test?

Unit testing is intended for the developer to vet the units of their code. You should worry about testing at the *method* level and not necessarily how it all fits together. By introducing API testing, you’ll be able to get a better handle on whether you’re using appropriate mock data in your tests and asserting the correct return values.

Well can’t I just rely on automated testing instead?

Automation suites, such as Selenium do not test at the API level; rather, they test at the user interface level. Sure, you could build your own automated tool to explicitly use your API to test behavior, but again, you are not testing the purity and correctness of the API. Sure, if your test uses the API a certain way and a developer breaks it, you can detect API failures. However, these types of tests don’t necessarily check for parameter correctness and all variations of use of an API.

API Testing Example

This is where Frisby.js comes into play. Frisby.js is a JavaScript-based API testing framework that makes it incredibly simple for you to test against your API. Here is an example:

Getting set up

Install Frisby.js + Jasmine Node

Test Structure

Frisby tests require that you reference the frisby global variable. From here, you can call frisby.create to create the structure of your first test:

Write your first test

Let’s say your website allows you to check a stock price by passing in a stock symbol. This is a GET request and takes one required parameter, symbol,  and one optional parameter, timestamp. If timestamp is passed in, the API will retrieve the stock price, if available, at the given timestamp. Otherwise, it will return the latest stock price.

In this example, we used Frisby.js to assert the validity of the response both in TYPES and in values, once we could narrow the stock down to a particular time. In one short test, we tested the response code, the header contents, and the JSON body of the response. Be sure to check out the Frisby.js API for detailed descriptions on each of the statements above.

In conclusion…

In this blog post, we explored WHY we test an API vs. unit testing vs. automated testing and went through a simple example on how to write a test against a simple API. API testing is important because it will help you identify breaking API changes from code that may otherwise been unnoticed. Also, it helps you keep your mock data/unit tests up to date and identify changes needed in your API documentation.

In a future blog post, I will dive deeper into Frisby.js and show you how you can write tests that depend on one another (think OAuth tokens and needing a token for a subsequent test) as well as a few more advanced examples.

 

 

ES6 Features: Classes

Up until ES6, JavaScript lacked the ability to create classes in the way that other languages offer. Sure you could create “classes,” but it always left a sour taste in our mouths. Talk about UGLY code. Although ES6 adds the keyword, “class”, they really are syntactic sugar around the old way of doing it in ES5. You’ll notice this trend around much of ES6 features–but I digress.

Why should I care?
Classes promote structure and the new syntax covers up the yucky code behind the scenes. These new classes also promote the use of inheritance and building structured code.

Imagine a scenario, where you are creating a class to represent a user in your database.

ES5 “Classes”

Eh it’s not really that bad, but it can be really confusing. Aren’t functions functions? How is it possible to create a new instance of a function? There is a lot you can do with building objects and inheritance, by ES5 just didn’t really expose it or make it meaningful enough for novice users to understand.

ES6 Classes

Pretty cool, huh?  This looks and feels like classes in other languages and comes more natural. You explicitly define a constructor, which is how you create an instance of a class. Then you can define members of the class as you see fit (notice you do NOT need the keyword function in front of them–pretty odd and inconsistent if you ask me).

ES6 Class Inheritance

Lets say your database has another type of user called an author. Authors are users but also have additional metadata. You can use class inheritance to model this:

What did we learn here?

  1. Use the keyword “extends” to write a class that inherits from another class.
  2. The keyword “super” becomes available in the child class and can be used to call methods on the parent
  3. You can override methods from the parent class simply by defining the method in the class. Notice there is no @override annotation or anything of the sorts required.

Classes in ES6 are important because they are explicit and help promote structured code. Many JS libraries have implemented their own version of classes, such as Dojo, TypeScript, and CoffeeScript, so it will be interesting to see if those get scaled back in the future as ES6 gets closer to fruition.

Chrome is behind on implementing classes in its spec, but you can try this out on the latest FireFox today. Enjoy!