Refactor your code or code your refactor?

Written by colecodes | Published 2018/01/28
Tech Story Tags: javascript | programming | node | engineering | software-development

TLDRvia the TL;DR App

I may need an intervention because writing codemods and transpilation plugins is addicting. Codemods are scripts that transform source code by converting it into an Abstract Syntax Tree (AST). That’s just technical mumbo jumbo for how common tooling parses and analyzes source code. Babel, ESLint, and even GraphQL — all rely on AST to get the job done.

In case you’re wondering, here’s what a bit of AST looks like:

This object represents a string expression: “hello world”

Under the hood the abstract syntax tree covers every part of source code, which unlocks a thousand possibilities for ways to manipulate source code automatically. You can change just about anything — for example:

  • Rename functions, variables
  • Upgrade old apps and libraries
  • Refactor large amounts of code with deterministic transforms
  • Enforce best practices

Before I started codemodding I had written a few ESLint rules. What I took away from writing plugins is that it’s a great way for incremental change. I spoke with a few colleagues who I knew had contributed to the ecosystem — and wondered about whether to write everything in a plugin or a transform. After that I gave it a shot and learned to love how easy it is to use AST with today’s tooling.

Getting Started

JSCodeShift is a client utility for running codemods. It’s like jQuery for mucking around with abstract syntax trees.

ESLint makes writing rules a breeze. It’s a necessity for any JavaScript developer and a good foundation for developer ergonomics.

A week and a half since I started writing these plugins and I have to say how wonderful it is to use. It makes dealing with large refactors not so debilitating. If you are making the same repetitive changes — using a codemod can quickly solve the problem. However if you are making incremental changes or enforcing best practices it’s best to create an ESLint rule instead. Both codemods and rules are the hammer and nail of any developer’s toolkit — and if you have not yet had the pleasure of writing your own then give it a try. If you are refactoring a lot of code then write a codemod to do the menial labor. If you are making small incremental updates then an ESLint rule can easily be upgraded from a warning to an error when old practices are deprecated.

Still interested? Here’s a neat list I found that has more about codemodding:

https://github.com/sejoker/awesome-jscodeshift


Published by HackerNoon on 2018/01/28