DEV Community

Discussion on: Which is more readable?

Collapse
 
cathodion profile image
Dustin King

This could be a job for a template language like erb, but that might be overkill if the rest of the json data isn't very complicated.

I like the second form because it's more consistent, but I would put the if clause before the assignment, because IMO as part of the statement it causes confusion whether it's short-circuiting the whole assignment or just part an expression for what is being assigned.

json_data = {}
json_data[:user] = add_user_data(mentioner)
if mentionable_type == "Comment"
  json_data[:comment] = add_comment_data(mentionable) 
end
Enter fullscreen mode Exit fullscreen mode

Also if the functions are side-effect free, I would drop the add_ from their names.

Collapse
 
gene profile image
Gene

I prefer this solution as well. It's simple and clear. Easy to understand.

json_data = {
  user: add_user_data(mentioner)
}

if mentionable_type == "Comment"
  json_data[:comment] = add_comment_data(mentionable) 
end
Collapse
 
richjdsmith profile image
Rich Smith

My preference goes with this one as well. Declaring json_data = {} in advanced just isn't necessary for writing code that is easy to be able to follow along with.

Collapse
 
tamouse profile image
Tamara Temple

This is my suggestion as well; it's extremely clear what is going on here, and I think this form conveys information to future maintainers quite well. The other suggestions are certainly doable. The tap form seems quite common, but if it's the only occurrence in your code base, it would likely be more confusing than helpful.