Why robots should format our code for us
I used to think that a personal code style is a good thing for a programmer. It shows you as a mature developer who knows what good code should look like.
My college professors told me that they knew when some of my classmates used my code in their work because of a different code style. Now I think it was because my code was at least somehow formatted and everyone else’s was just a mess.
Since then I’ve spent a lot of time arguing code style and configuring tools to enforce it. I think it’s time for a change.
A few examples
After reading the The Programmers’ Stone I put braces like this for a long time:
But then I realized that I was probably the only one who did it that way in the frontend community. Everybody else uses this style:
So I’ve changed my style to the last one.
I like this style for chaining very much:
I see the same refactoring benefits as for trailing commas:
But I’m probably even more lonely with this style than I was with braces. Nobody would ever send me code for review with this style, no linter can enforce it. I have to stop using it too to be closer to the real world.
Another thing that nobody else does except
I thought it improves readability but actually it just makes code base inconsistent because other developers always put one space.
You could use ESLint to enforce code style and even autoformat code in some cases. But it won’t make your code base 100% consistent. For example ESLint with Airbnb config would normalize only my first example and allow inconsistency in the other two.
Let’s try Prettier on my examples:
You can disagree with this style, for example I don’t like the
else placement and writing function chains in one line is questionable. But I see huge benefits in adopting Prettier:
- Almost no decisions to
make —Prettier has few options.
- No arguing about particular rules if you’re working in a team.
- No need to learn your project’s code style for contributors.
- No need to fix style issues reported by ESLint.
- Possible to set up autoformat on file save.
Prettier has been already adopted by some popular projects like React and Babel. And I’m slowly converting all my projects from my custom code style to Prettier and will recommend it instead of Airbnb code style.
At first I had a lot of “Ugh, that’s ugly” moments with Prettier. But when I think that I’d have to, for example, manually reformat JSX code from a single-line to multi-line when I add another prop and it doesn’t fit on one
Read how to set up Prettier in your project.