Dear ES2015 Community, one line of code isn’t always better than two

Michael Barshinger
3 min readMar 26, 2016

--

Javascript is looking more and more like CoffeeScript. I had a brief love affair with CoffeeScript. I loved writing in CoffeeScript. When other developers joined the project, I realized CoffeeScript’s biggest flaw:

CoffeeScript is fun to write, but hard to read.

ES2015 adds some syntactic sugar that can lead to writing Javascript that’s hard to read and comprehend at first glance.

Example 1

// es2015 javascript
const { post } = this.props
// equivalent traditional javascript
const post = this.props.post

Both lines are equivalent and valid Javascript, but which one is easier to read?

Example 2

// es2015 javascript
const { fields: { title, content} , handleSubmit } = this.props
// traditional javascript equivalent
const title = this.props.fields.title
const content = this.props.fields.content
const handleSubmit = this.props.handleSubmit

Wow, with ES2015 we can compress 3 lines of code into 1 — how cool is that!

Hold on, let’s rethink that. The single-line version is NOT going to make an app more efficient, but it IS going make the developers of that app less efficient. Sure, it’s faster to write one line of code than three, but that’s not the whole picture because it will be read by developers hundreds, even thousands of times, and code that’s easy to read and comprehend is better.

Every line of code that I write will be read and interpreted by me and other by developers for years. Verbose code is often easier to read and comprehend.

Example 3

// es2016 javascript
function reducer(state, action) {
return { …state, all: action.payload.data }
}
// traditional javascript equivalent
function reducer(state, action) {
state.all = action.payload.data
return state
}

Seriously developers? Don’t be so selfish and arrogant, don’t try to be clever, and stop sacrificing clarity for conciseness.

It’s not ES2015's fault

This is not a new problem. It’s always been possible to write code that hard to read and comprehend but that doesn’t mean you should. Case and point: I wouldn’t dream of using Visual Studio for C# development without ReSharper. If you don’t know ReSharper, think of it as a linter for C# on steroids — not only does it lint your code but it also offers to rewrite your code with quick fixes that teach you to be a better developer. A few years ago ReSharper started offering to convert C# foreach loops to a new C# language feature: ‘LINQ’. The conversion usually results in fewer lines of code, but too often the resulting LINQ statements are hard to read and comprehend.

Whether developing a personal project, an open-source project, or at work keep in mind that your going to be re-reading your code a lot and other people will be too.

Final Thoughts

What’s better than writing code that only has 1 bug in it?

Writing code that’s easy to comprehend; and that’s why sometimes two lines are better than 0ne.

--

--