12 Rules for Professional JavaScript in 2016

Cory House

Disclaimer: I speak in absolutes below for brevity. Yes, nearly every “rule” in programming has exceptions.

JavaScript is hard. It moves so fast that it’s often unclear whether you’re “doing it wrong” at any given moment. Some days it feels like the bad parts outweigh the good parts.Yet there’s no point in fighting it. JavaScript is eating the world. So we might as well do it right.

Here’s my take.

1. JS Belongs in a .js File “C’mon, it’s only a few lines…” Yes, I mean nearly all*. Why? Because it aids readability, enforces structure, and saves bandwidth. Inline JavaScript must be downloaded every time the page is loaded. In contrast, separate .js files are cached. As you’ll see, this rule helps support a long list of other rules below. That’s why it’s rule #1.

2. JS Code Should be Static I’ve seen many creative hacks for making JavaScript dynamic. People use server-side languages like C#, Ruby, or Java to write dynamic JavaScript in a string. Don’t do that. You lose code coloring, syntax highlighting, and intellisense support. And remember, JavaScript belongs in a .js file (see rule #1).

Instead, use JSON to introduce dynamic behavior. I call this the JavaScript Configuration Object Pattern. Here’s how: inject JSON into the head of your application and utilize that data to fork logic as needed. You might be thinking “Hey, this contradicts rule 1!” I view JSON as data, not code, so I make an exception here in order to support static, separate JavaScript files. For Top web design company visit Vivid Designs

StackOverflow uses this pattern. As does Google. So you’re in good company. Just view their source:

As you can see, StackOverflow is injecting personal settings like isNoticesTabEnabled. This simple snippet of JSON provides the necessary data for providing custom behaviors while using static JavaScript code files. To make this happen, serialize a server-side class into JSON and place the result in <head>. Then you can reference this data structure as needed in your static JavaScript code, knowing it will be available because it’s injected in the <head>.

3. JS Should be Minified Minifying reduces file sizes, which speeds page loads. Remember, performance is a feature. And of course, to minify, you need to place JavaScript in a separate file (Again, rule #1). Minification was once a hassle. Today, it’s automated and simple. There’s a dozen ways to get it done, but Gulp with gulp-uglify is a low-friction and automated way to get rolling.

4. JS Should Be Linted Real-time Linting enforces style guidelines, finds typos, and helps avoid errors. There’s a variety of linters out there, but I suggest ESLint. You can run it via Gulp with gulp-eslint. Gulp can watch all your JS files and run the linter everytime you hit save. Oh, and again, you need your JS in a separate .js file to lint it. Starting to see why I made “JS should be in a separate file” rule #1?

5. JS Should Have Automated Tests We understood testing was important on the server years ago. But it’s been largely ignored in JavaScript until fairly recently. Today’s typical JavaScript application has more surface area than you can practically test regularly by hand. With JavaScript handling so much logic, it’s critical to have automated tests.

You can do automated integration testing via tools like Selenium. However, integration tests are often brittle, so I suggest focusing on automated unit testing. There’s a variety of options for automated unit testing. I suggest Jasmine if you’re new to JavaScript testing and Mocha with Chai if you want the ultimate configurability.

6. JS Should Be Encapsulated We learned the risks of global variables years ago. Thankfully, there are many ways to encapsulate JavaScript these days:

Immediately Invoked Function Expressions (aka IIFE) Revealing Modules AMD (typically via RequireJS) CommonJS (used by Node.js, use in browser via Browserify or Webpack) ES6 modules Bottom line, ES6 Modules are the future. The great news is, although they’re not yet supported in browsers, you can use ES6 modules today if you transpile via Babel (and as you’ll see below, you should).

If you don’t want to transpile, CommonJS is likely your best bet for today. Since Node uses the CommonJS pattern, you can use npm to pull down 1,000’s of packages. CommonJS doesn’t run in the browser without a shim, so you’ll want to use a tool that packages it for the browser like Browserify, Webpack, or JSPM.

7. JS Dependencies Should Be Explicit This rule closely relates to the rule above. Once you’ve started encapsulating your JavaScript, you need an easy way to reference other modules. That’s the beauty of modern module systems like CommonJS and ES6 modules. You simply specify your dependencies at the top of the file, much like an import or using statement in Java or C#. JavaScript has finally grown up.

8. Transpile to JS The latest version of JavaScript, EcmaScript 2015 (more commonly known as ES6) was officially released in June. Browsers still lack support for most of the new features, but that doesn’t matter. You can enjoy the long list of new features today using Babel. Babel transpiles ES6 to ES5. And assuming you can live with some performance quirks, you can enjoy the new features today. JavaScript is expected to release new versions once a year now, so we’re likely to be transpiling forevermore. Transpiling gives us the future today. Best web development company in Amritsar

Or perhaps you love the comfort of strong types? Then consider TypeScript which compiles down to JavaScript.

Bottom line is this:

You don’t have to write ES5 anymore. Consider using an abstraction that gives you extra power. 9. JS Should Have an Automated Build We’ve already talked about linting, minification, transpilation, and testing. But how do you make all this happen automatically? Simple: With an automated build that watches files. Again, Gulp is a popular tool to tie all this together via its watch function, but Grunt and Webpack are other excellent options to consider. Or, if you’re a whiz at Bash you can simply use npm as a build tool. The point is, don’t expect people to remember to run these things manually. Automate and enjoy the benefits!

10. Use a Framework or Libraries Pull something awesome off the shelf and get rolling. Need to stay light? Try Backbone or Knockout. Or maybe plain ‘ol jQuery is enough. Want something more full-featured and opinionated? Try, Angular, Ember, or React with Flux.

The point is:

Do not attempt to start from scratch. Stand on the shoulders of giants. React with Flux is my current favorite combo for client-side dev. That’s why I just published a comprehensive Pluralsight course on the topic. In the course I walk through a build process that implements many of the practices above. The starter kit is on Github.

Regardless of which framework you pick, make sure to separate your concerns. Which leads to the next point…

11. JS Should Separate Concerns It’s easy to get in the habit of placing all JavaScript in a single file, or to blindly follow the advice of your framework. Don’t forget the lessons you’ve learned on the server when you move to the client.

By separating concerns, I don’t mean merely separating models, views and controllers like you do in MV* style frameworks like Angular and Knockout. I’m saying this:

Think like a server-side developer when writing JavaScript. Separate your presentation from your business logic and data access. This means AJAX calls should all be in one spot. Create a centralized client-side “data access layer”. This also means logic that doesn’t have to be part of the presentation layer framework you choose should reside in separate “POJOs” (Plain ‘ol JavaScript objects). Business logic modules should contain plain JavaScript — in other words, no framework specific code should reside inside. This makes the logic easy to reuse, easy to test, and it’s not impacted when you decide to move from Angular to the hot new flavor of the month.

12. Use a Starter Kit That’s a lot to keep track of. And it’s silly to start out each new project with a blank slate. Instead, sit down with your team and decide how you want to build JavaScript projects. Build a starter kit that implements a simple example so everyone has a clear, shared vision on how to get things done.

A starter kit should include linting, minification, bundling, a production build, and a few example automated tests. I suggest including a simple example app that puts this all to use. Then provide a command that removes the starter kit and places the project in a state that’s ready for development.

My starter kit is React Slingshot. I build this starter kit from scratch in my new course “Building Applications in React and Redux in ES6”.

And even though my starter kit is specific to React, if you’re in Angular, Backbone, etc, the core principles and features remain relevant. That said, be sure to Google for other starter kits for inspiration.

So why use a starter kit? A starter kit creates a pit of success. It makes following your team’s agreed list of best practices automatic. A good starter kit makes doing the right thing the easy thing.

Well, That Was Overwhelming. Yes it was.

We’ve entered an era where the front-end is complicated enough that we need front-end specialists. Don’t expect everyone on your team to understand how to do all this in detail. Agree on a starter kit that codifies all your decisions. This way, everyone can start with the same solid foundation on your next project.

See things missing? Disagree? Chime in on Reddit.

Cory House is the author of multiple Pluralsight courses including “Building Applications with React and Flux”, “Building Applications in React and Redux in ES6” and “Clean Code: Writing Code for Humans”. He is a Software Architect at Vinsolutions and trains software developers internationally on software practices like front-end development and clean coding. Cory is a Microsoft MVP, and founder of outlierdeveloper.com.

 

 

Continue Reading

Meta Skills of a Software Engineer

Doug Arcuri

Recently, a friend asked a question about the particular skills possessed by software engineers.

What are the unique skills that software engineers practice? Drawing from my experience led me to an opinion. The idea I have come to realize over time is that I enjoy the meta of programming. The skill of learning the meta, or how to do what we do better, includes reading many well known books in context. I took specific examples of what I read over the years, applied it to my own observations practicing in the field and I answered in a way that I believed was most pragmatic.

Me: In my opinion, if we think universally, I would say it is the practice of correctness and pattern recognition*. These are some of the skills that are unique to software engineers. Let’s exam these skills to add context.

Correctness Correctness is very much related to the how and why we build things the way we do. In organizations, it is most closely associated to the correctness of what the business must solve for its customers. Software that is written well follows this thinking. If you are looking for Best Website development services check Vivid Designs

Correctness is seen in engineering as how correct the how is so that the solution for business can continue to be solved with high reliability. It is and must be a balance of strategy (designing) and tactics (execution). The examination of the how’s how in a vacuum appears well in chapter four of Programming Pearls — Writing Correct Programs.

… keeping code simple is usually the key to correctness. — Jon Bentley Pattern Recognition Pattern recognition is strongly tied to the organization of that correctness by creating the necessary abstractions and component boundaries. Pattern recognition leads to concepts of reuse to modularize and isolate code. We monitor duplication, find areas that can be reused, and refactor complicated parts of code. It is what software engineers do well. Our attention to that detail is vigilant. We recognize knowledge as it is created over and over again. Then we simplify.

Pattern recognition is discussed at length in the community and there are many sources to read up on their techniques. The origins where I learned about this skill reside in chapter two of The Pragmatic Programmer — The Evils Of Duplication.

Make it easy to reuse. DRY — Don’t Repeat Yourself. — Andrew Hunt & Dave Thomas A Teachable Moment Once I gave this response, my friend followed up with another question.

If correctness and pattern recognition are these skills, how do you teach them? Of course, my answer was simple enough.

Me: Locate these books, set the environment, and work through by showing examples. Set the expectation of learning and practicing these meta skills while delivering value to business. Why? Complexity. This is the best investment of learning the skill of balancing complexity that I know of. It also results in engineers who become more confident over time. My mentoring has been focused around these books and around these particular skills. But it made me realize there are few out there that invest heavily in the meta, apart from doing the work without realizing it. The vocabulary of the meta is something I’ve have interest in. My writings on problem decomposition (correctness), and organization (pattern recognition) in the real world were difficult to see when in the heat of delivery. If you are looking for Web development company in Bangalore check Vivid Designs

At about the same time I had thought about writing this brief on these skills, another book was mentioned because I’d been asking around. A professor at Stanford has been teaching a course on the meta and has resulted in a book of some of his course findings. I was shocked when I found out that he has the same gripe as me, I purchased the book and devoured it. From chapter thirteen, A Philosophy Of System Design.

Engineers tend to be very detailed oriented. We love details and are good at managing lots of them; this is essential for being a good engineer. But, great software designers can also step back from the details and think about a system at a higher level. — John Ousterhout** Conclusion In my opinion, correctness and pattern recognition are skills*** that software engineers should strive to understand and do well at. The result is higher quality software. All other unique skills, if there are others to categorize, may very well be based off these. I invite others to share examples of meta skills they have practiced over time.

Fundamentally, correctness and pattern recognition have tie-ins to outcomes of complexity (also known as cognitive load). There needs to be a way to balance both intelligently so that the complexity is mitigated. In essence this is why these skills are, in my opinion, the distillation of what we do.

* What is interesting about correctness and pattern recognition is they also have a strong association to practices around machine learning.

** If you want to know more about what John is doing, take a look at his video.

*** Engineers should also practice high levels of learning and communication. These concepts aren’t unique to software, but have strong associations to the sciences.

 

Continue Reading