DEV Community

Discussion on: Keeping Your Code Simple

Collapse
 
bennypowers profile image
Benny Powers 🇮🇱🇨🇦 • Edited

Thanks Tiffany for the post, which has opened up such a lovely discussion.

I'm going to push back a little on your examples. By pulling your data out into the top level of the scope instead of your operations, you're contributing to more complex code by adding to the cognitive load of the reader.

In the first example, the worst it'll get for the reader is parsing a single pure function.

In the second example, the reader will need to parse that function while referencing external state.

Could you have simplified that first example by extracting operations to the top level instead of data?

import { maxBy, length } from 'ramda'

// longest :: (Ord a) => (a, a) -> a
const longest = maxBy(length)

const longestString = (strs) =>
  strs.reduce(longest, '');

REPL.it

In this case, there's 0 mental parsing. Your reader's cognitive load involves reading the Ramda docs to find out that maxBy(length) will return the longest of its two arguments. We even provide a function signature in the comments so they don't have to shlep all the way out to the browser.

Is pulling in Ramda cheating? Heck no! Ramda is a general-use functional library. If we're concerned about dependency creep, we could implement those on our own as well.

The most readable code is the code that you don't have to read. Let's layer general interfaces and abstractions instead of bespoke imperative instructions.