Extreme Makeover: Code Edition

Ali Spittel on July 23, 2018

I am a little bit obsessed with writing clean code. Code should be written for future developers (including yourself) and extendability -- it sho... [Read Full]
markdown guide
 

Useful and good tips !

I'm agree with all except with comments, if you follow the rule of Use clear variable and function names isn't necessary put comments, is redundant.

From Clean Code - Robert C. Martin:

  • Always try to explain yourself in code.
  • Don't be redundant.

Is just my opinion, always is better be more expressive in our code.

 

I like this article about comments.

Only at the point where the code cannot be made easier to understand should you begin to add comments.

 

Good post, thanks for sharing Ben.

Maybe this can be an simple example:

(function() {
    // Is necessary apply the `bind` method
    // to set `this` in the right context
    const $ = document.querySelector.bind(document);

    // more code...
})();

This saves the time of going to the documentation or being confused, but it is not redundant, is the main idea that I'm trying to share, IMHO the comments are useful always in the correct way.

I love React's dangerouslySetInnerHTML which replaces a lot of documentation and comments and forces the user to understand what's going on. If you don't know why it says "dangerous", you can look it up.

Much better than

//This is dangerous, read this post about XSS:
setInnerHTML

Because the comment would never get ported across all the use cases (obviously, given it's a library).

But most code doesn't live up to the scrutiny of library code and comments, used properly, are a perfectly reasonable part of the toolbelt.

Yes, yes and yes !

I have never used React but dangerouslySetInnerHTML is so clear !

Yeah, I've only ever used it once and it was to inject release notes into a component from an external HTML file. yolo.

 

If the code is abstract to the main idea, of course !

Sometimes you need comments but most of the time you need to think twice if is necessary.

From your shared post

Sometimes when I’m writing code, I think “I should comment this”

Right. The first and proper response to that feeling is to roll up your sleeves and refactor the code. After you’ve refactored, if you still feel a comment is necessary, then by all means add one. Never comment before you’ve attempted to refactor away the comment first.

 

Awesome posts, these rules are simple and yet they can make a huge difference in the code quality!

As you said, these are not written in stone but still, there is one rule that bothers me a lot:

Methods and functions can be no longer than 5 lines of code

I like the idea of reducing the size of classes, functions, methods, etc... but 5 lines (10 even) is just impossible most of the time and in my opinion over reducing functions/methods sizes makes the code harder to read in most cases. Splitting 15 lines over 3 functions makes it hard to keep up for someone unfamiliar with the code. Overusing syntaxic shortcuts is no good either if clarity is your main goal.

 

Ah interesting, I personally am very much in the 5 lines or less camp -- I think it is rare that your function is doing one thing only if it is longer than that! I rarely even write functions that are a full five lines of code to be honest!

 

I followed this practice for a few years.

Now I'm more into big functions when there is no/not much duplication involved.

I use blocks to encapsulate parts of the bigger functions and early returns, so you often don't need to scroll down the whole function.

Jumping around a file or multiple files to find 10 functions that are only used once or twice when they could have been a few extra lines in the main function doesn't cut it for me anymore.

 

While I generally hold as close to this rule as I can, there are times where I've had to break the rule to get the job done. Those have mostly been in financial applications, and numerical methods (ordinary differential equation solvers, spherical harmonics, etc.). Basic CRUD apps, I've hardly ever written any function that requires more than 5 lines.

 

Yeahh, 5 lines is too short IMO. Especially for the more verbose languages. To be fair, a function can be reasonably long and still do only one thing.

 

These tips are the gists of many of clean code practices 👍.

If you (as in developers like you and me) want to go deeper, you can read Uncle Bob's clean code book (as mentioned in other comments), or listen to this extensive podcast eps by Coding Blocks guys (epsidoes 47~55) where CB guys explain each coding practice mentioned in Clean Code book.

You can probably listen to these during your commute 🚂 to work 👷‍♀.

They might be 2 years old but these principles are evergreen skills that would last throughout your careers.

  1. 47. Clean Code – Writing Meaningful Names
  2. 48. Clean Code – How to Write Amazing Functions
  3. 49. Clean Code – Comments Are Lies
  4. 50. Clean Code – Formatting Matters
  5. 51. Clean Code – Objects vs Data Structures
  6. 52. Clean Code – Error Handling
  7. 53. Clean Code – Integrating with Third Party Libraries the Right Way
  8. 54. Clean Code – How to Write Amazing Unit Tests
  9. 55. Clean Code – How to Write Classes the Right Way
 

In regards to comments, check out the Commenting Showing Intent standard I helped author. I've been using it in production for a few years, with an excellent return on investment.

For anyone who says "clean code shouldn't have comments", please consider -- the cleanest, most obvious code in the world still fails to explain "why". The intent in your code is only obvious to you because you wrote it; to believe anyone else can or should figure it out is expecting nothing short of mind-reading. MANY problems in modern coding can be attributed to this mindset.

 

I'm personally in the "Clean comments shouldn't have code" camp.

 

Is not about to avoid the comments(this are useful of course), is about avoid the redundancy and obvious noise.

 

Sure, but that's the difference between "what" (redundant noise) and "why" (never ever redundant to anyone unfamiliar with the code).

Granted, it can be a fine line, but I've found it's better to air on the side of too many comments, leave them for a few weeks, and then come back later and pare back the unhelpful ones that have proven redundant (therefore showing them to be "what" comments).

 

All good stuff. Perhaps I’m spoiled in Ruby on Rails, but I feel like if your methods if you do 1, 2 and 4-7 well, you shouldn’t need comments. Comments, IMHO, are a last resort to explain something that is, by necessity, opaque.

 
 
 

Great article @Ali !

Just one correction, regarding meaningful names, this is actually misleading:

function averageArray (array) {
  let sum = array.reduce((number, currentSum) => number + currentSum)
  return sum / array.length
}

In a reduce, the first parameter is the accumulated value, and the second is the next item from the array. So it should be:

function averageArray (array) {
  let sum = array.reduce((currentSum, number) => currentSum + number)
  return sum / array.length
}

In your example, by chance it didn't hurt because A) both the array and the accumulated value are numbers, and B) addition is commutative, but if your operation was not, or if your accumulated value was of a different type, this would become more important.

I hope that is helpful! Thank you for writing interesting and useful articles!

 
 

Third one! Put PI to function call, you'll have a pure function then. :)

 

Ahh interesting! I normally make my constants global, but could see that being good too!

 

Both approaches are good. Putting const in function would align with functional programming approach. Making function not dependant on anything that's outside of it (being pure) 😊

 

Find a code style and stick to it

Prettier does it really nicely

 
 

Yeah prettier, aside from choosing a code style also helps eliminate a lot of noise in PRs so you can focus on the real problem the PR is trying to solve instead of "can you format this line like this? I find it reads better". It is opinionated, but I just love how it takes that off the table.

We use it at work and even dev.to uses it now.

 

Marvelous, and thanks so much Ali :) ... I will definitely sign up for your newsletters

 
 
 
 

Great Tips! I'm a teaching assistant at a coding bootcamp an we actually mention a lot of these to help teach best practices.

 
 

Great list of tips. In addition to these, I'm a really big fan of early returns and limiting else statements whenever possible.

 
code of conduct - report abuse