DEV Community

Discussion on: IF code is commented properly THEN readability is good and ELSE is a useful construct.

Collapse
 
codedraken profile image
CodeDraken

There's a quote, something like:

"The use of comments is to compensate for our failure to express ourselves in code"

if statements can be cleaned up and made readable by simply using a function in the condition part and in the body.

Example:

// functions
if userExists(myVariable) {
  updateUser(...)
} else {
  createUser(...)
}

// Object-Oriented
if user.isAdmin() {...}

// temporary variables
isUser = myVariable instanceof User
if isUser {...}
Enter fullscreen mode Exit fullscreen mode

A problem with comments is that they clutter the code and slow down reading time and are often forgotten about when updating code. Comments that lie are the last thing you want.

I'm not saying comments shouldn't be used, but they should be used sparingly and only for providing clarification or the intent of some code. It should not just rephrase what the code already says.

And obviously, there are useful tools that use comments i.e. docs, TODOs, etc