Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Dev Tools: Linting with ESLint

Dev Tools: Linting with ESLint

There are many developer tools out there from browser tools, editors, debuggers, and test frameworks. But one tool that often gets overlooked is code linting. Linting is one of the best ways to enforce consistent code quality and can often catch bugs before they ever make it into your codebase.

Derek Lindahl

March 30, 2016
Tweet

Other Decks in Programming

Transcript

  1. Hello! My name is Derek and I am the organizer

    of SacJS, Sacramento’s Javascript Usergroup.
  2. Chrome’s DevTools, which not only allow you to inspect and

    modify the DOM, but visualize CSS animations, measure heap size and memory usage, as well as live edit source code
  3. A code linter is a tool that statically analyzes your

    code and can used as simple debuggers for common errors or hard to find errors such as…
  4. There are linters for many different languages, from Ruby to

    Clojure to Python and even CSS and Matlab.
  5. ESLint Unsurprisingly, there are several different linting tools out there

    for Javascript, but we’re going to focus on ESLint
  6. Javascript, being a dynamic and loosely-typed language is especially prone

    to developer error. It is typically executed in order to find syntax or other errors. ESLint differs in that it parses code into an Abstract Syntax Tree which it can then use to analyze its structure and detect errors.
  7. Source: http://techblog.yahoo.co.jp/javascript/how-to-create-eslint-rules/ An AST is a tree representation of the

    syntactic structure of code. So here, the statement “console.log Hello World” breaks down in the following tree nodes: a program root node, an expression statement (meaning a line of code), a call expression (the parentheses), a member expression (or property lookup on console), and a literal declaration (the string “Hello World”)
  8. Source: http://efcl.info/2016/03/06/ast-first-step/ From this abstract representation, different tools are able

    to understand the syntax of the code you’ve written. From there, it can produce errors, or it can compile it into a completely different language.
  9. For example, the popular Javascript package Babel allows you to

    use the newest features of Javascript (like those available in ES6 and ES7) while still supporting older browsers that don’t know how to process the latest syntax. It does this by analyzing the AST and converting the various nodes of the tree into backwards-compatible code.
  10. It can also be used to compile one language into

    an entirely different language like Ruby to Javascript (https://github.com/rubys/ruby2js)
  11. So back to ESLint. Since ESLint has this tree of

    nodes that represent different aspects of your code, it can better understand what you are trying to do
  12. For example, if you have two properties on an object

    with the same key but a different value, thats probably a bug. And if you aren’t careful, you’ll think its returning “A” when its actually returning “B”.
  13. It can warn you when you assign to a variable

    when you really meant to check it for equality. So in this example, it looks like we’re applying a discount if a particular item matches another one. But actually, this is overwriting the value of “item” with “otherItem” which would mean that this user’s cart contents would change without them knowing.
  14. It can also check for code that will never get

    executed. So here, “doTheThing” is always true, so the conditional would always match, which means it would always return “theThing()” expression. “crossTheStreams” can never be reached (which is probably a good thing)
  15. Do note that this is “statically” done. ESLint does not

    execute your code so it doesn’t have the ability to understand dynamic assignments which means it can’t warn about unreachable code like in this example
  16. It can even validate your JSDoc comments. Here, you can

    see that this awful programmer completely skipped documenting the “type” of the `num1` parameter, the description of what `num1` represents, and the description of what `foo` does.
  17. Why is coding style important? Because its more difficult to

    understand similar code written in two different styles. For example, my brain completely halts when I see braces on new lines.
  18. This can add to cognitive load making it take longer

    to add a new feature or debug errors.
  19. This isn’t usually a problem when you are the sole

    maintainer because you will likely enforce stylistic practices through habit.
  20. “But how many different styling differences can there possibly be?”

    ESLint comes bundled with over 70 different stylistic-specific rules that can be enabled to enforce specific standards, each with additional options. On top of that, the community has contributed plugins that cover even more stylistic preferences and you can write your own as well.
  21. So let’s look at some of the more common stylistic

    decisions you can make in a code base
  22. “comma-dangle” is an interesting one that forces (or prevents) the

    use of commas at the end of object definitions.
  23. One reason to use a dangling comma is that if

    you ever needed to add a new property to an object, the resulting diff is a bit more concise as to what change was made. One reason to NOT use a dangling comma is that it just plain looks weird. If you aren’t used to seeing dangling commas, this could trip your brain up as you scan through code and disrupt your flow
  24. One reason to choose one or the other is to

    prevent different developers from constantly modifying these commas. Not only does that increase churn in the code, but its a waste of time to constantly battle over commas.
  25. Talk about it with your team, pick a side, codify

    it, & then everyone knows what the rules are. This is really great when you on-board a new team member because the rules are all known, codified, and enforced. No additional discussion is necessary.
  26. If there are any IE veterans here, IE used to

    completely blow up with an obtuse error if an object had a trailing comma. No other browser had a problem with it and it was a single character, so it was nearly impossible to debug.
  27. To work around this problem, developers started putting the comma

    first. This made it a bit more obvious to see any extra or missing commas. The downside to this is, again, if you aren’t used to this style, it will likely trip you up.
  28. But thanks to linting, once the decision is made and

    the rule enabled, you won’t ever have to discuss it again and if someone makes a mistake, the error message is much easier to understand
  29. The reason why this is important is that when indentation

    characters are mixed together, different editors can render code in drastically different ways which can make it nearly difficult to understand the code
  30. [back and forth] How annoying is this… Additionally when Mr.

    Spaces adds spaces in-between the Tabs and it goes back to Mr. Tabs, the white space differences start to compound until every other character is a different type of whitespace character.
  31. Additionally, if someone’s editor is configured to automatically convert indents

    from one style to another, you’ll end up with lots of whitespace commits which adds additional churn to your codebase
  32. This commit here does absolutely nothing, but it appears to

    modify several lines of code. These changes will be tracked for the lifetime of the repo which can lead to confusion when using something like `git blame` or `bisect` to track down bugs
  33. OK, great, we’ve decided on some rules, now what? Right

    off the bat, you can run the ESLint command line tool which will analyze all of your files, process them through your rule sets, and will then display a bunch of errors or warnings. This is best when you add a linter to your code and run it for the first time. I guarantee you that there will be at least a dozen discrepancies in how you write your code. So once its done, all you need to do is look at each file and correct each issue.
  34. Now you might say, “But there is this one edge

    case where I need to break the rule”
  35. No problem! Most linters allow you to temporarily disable a

    specific rule or rules or even linting entirely through comments. Not only does this allow you to not compromise on which rules to choose, but it also self-documents a potential iffy spot in your code.
  36. In this example, we want to always use camel-case keys,

    but this other library requires we use snake-case. So we’ve temporarily disabled the rule to work around that.
  37. Anything that goes against the norm is a potential source

    of bugs or complexity and is worth calling attention to.
  38. So now that you’ve corrected all your code, how do

    you prevent future work from breaking the rules again? Easy, add it to your test suite!
  39. Most linters will exit with a non-0 exit code which

    will cause test runners to fail a build. This is great not only locally, but also on continuous integration servers. You can go one step further and add a pre-commit hook that will run every single time a commit is made. This prevents you from even getting to the broken build stage by not even allowing your commit to go through if you’ve introduced a linting error.
  40. Ok, so now we’ve got linting added to our test

    suite and we have made our code fool proof from linting issues! But… UGH. Running this command over and over is such a drag.
  41. You’re right! Thankfully many popular editors support linting tools and

    will highlight potential errors right in your editor, inline with your code! Now you have no more excuses for forgetting that semi-colon.
  42. PS: In addition to linting tools, I’d also like to

    recommend Editor Config. This tool auto-configures your editor of choice to match certain preferences globally or for specific filetypes.
  43. IMO, the most important changes it supports are “insert_final_newline”, “indent_style”,

    and “indent_size”. Again, having everyone on your team on the same page will ensure a high quality of code, reduce churn in your repo, and prevent rehashing the same old arguments over and over.
  44. Thanks! If you want to learn more, talk to me

    later or come out to one of our meetups! We meet every 4th Tuesday right here at The Hive!