DEV Community

Discussion on: Writing code for your future self

Collapse
 
qm3ster profile image
Mihail Malo
// this is a user object or undefined, should probably use `some` instead of `find`
const isUserPostCreated = users[0] && posts.find(post => post.userId === users[0].id)

if (isUserPostCreated) {
  showUserPost()
}

I'd usually do the following:

const [user] = users
if (!user) return

const { id } = user

// Does the user have any posts?
if (!posts.some(({ userId }) => userId === id)) return

showUserPost()

I guess I could name that boolean instead of writing the comment (or doing nothing at all) but I'm just being honest, and this best represents what I usually write at this time in my life.
And indeed, naming is hard (I didn't find your name descriptive enough).

const [user] = users
if (!user) return

const { id } = user

const userHasPosts = posts.some(({ userId }) => userId === id)
if (!userHasPosts) return

showUserPost()

Not sure which is better. Comments go stale easier than names, but this pollutes the scope.
Maybe I should wrap the const+if into a block for lexical scoping.
That would be wild. Ha. Ha-ha. Ha.

Collapse
 
sunnysingh profile image
Sunny Singh • Edited

I see no issues with reading your code, plus what I provided in the article are only meant to serve as suggestions. My own examples could definitely be improved as you showed.

I do prefer adding a variable over a comment though, because as you said: comments become stale.

But yeah, this stuff is hard sometimes 😅

Collapse
 
qm3ster profile image
Mihail Malo

Variables become stale too :v
Don't tell me you have never seen something like

isValid.forEach(name(true))

They are easier to update though, since once someone finally realizes what that damn thing represents, they can apply a "rename identifier everywhere" refactoring tool.

Thread Thread
 
sunnysingh profile image
Sunny Singh

Haha, yeah good point. I agree that they are easier to update.

I like to use comments as a last resort to explain why a piece of code is written in a certain way or exists in the first place.