DEV Community

Cover image for Simple ways to improve code readability

Simple ways to improve code readability

briwa on May 11, 2019

TL;DR: It might be obvious to you, but not to others. Why? More often than not, I used to think that my code is just for me (Narrator: ...
Collapse
 
theodesp profile image
Theofanis Despoudis

I think sometimes, a change of paradigm can make things more obvious. For example in Clojure

(def ids [1 2 3 4 5])
(defn retrieve [id]
  (when (contains? ids id) 
     (retrieveItemById id)))

It is quite readable as the vocabulary of functions are more relevant.

Collapse
 
briwa profile image
briwa

Haven't tried Clojure but boy that is a whole new level of readability. Thanks for the tips. I agree, this article is merely baby steps to something bigger like switching to Clojure.

Collapse
 
jamesthomson profile image
James Thomson

Good tips. I think reading the logic out as a sentence is definitely a great way to realise if it will make sense to others at first glance. If it doesn't read as a proper sentence, then it likely isn't going to easily make sense to others.

Btw, small thing, but item.stock >= 0 should be item.stock > 0 as if the stock = 0 then there is no stock ;)

Collapse
 
briwa profile image
briwa • Edited

Hey, that is true! My mistake. Thanks for correcting me. I've amended the article.

Collapse
 
mccabiles profile image
Miguel

I didn’t know how much more efficient .some and .every were compared to filter. I definitely need to refactor my code that fit this exact use-case. Thank you for sharing!

Collapse
 
jessekphillips profile image
Jesse Phillips

Be careful when making these logic changes. Check that your unittesting will catch incorrect logic since there are several potential logic changes, should && become ¦¦...

Collapse
 
briwa profile image
briwa

Ah yup, that is true. Refactoring should always be done with tests beforehand. I missed that out. Thanks for the tips!

Collapse
 
mersano profile image
Mersano Berant

GREAT