DEV Community

Cover image for Clean up your code by applying these 7 rules ⚡️

Clean up your code by applying these 7 rules ⚡️

Joachim Zeelmaekers on November 14, 2020

Readable code is maintainable code In this short post, I will go over some of the rules that you can apply to improve your code. All cod...
Collapse
 
imjoshellis profile image
Josh Ellis • Edited

Great post!

Consider specifing the language in your markdown code blocks because Dev.to has syntax highlighting!

You can do this by adding the language after the first three backticks at the start of your code block:

// code block starts with '''js (but with backticks instead of ')
const fn = () => {
  const x = "hello"
  return 3 + x
}
Enter fullscreen mode Exit fullscreen mode

vs

// code block starts with just ''' (but with backticks instead of ')
const fn = () => {
  const x = "hello"
  return 3 + x
}
Enter fullscreen mode Exit fullscreen mode

Not sure that makes sense. The parser makes it difficult to explain. Here's a quick GitHub gist that will let you check out the raw text of this comment: Gist

Collapse
 
dvddpl profile image
Davide de Paolis

Wow. Cool suggestion. I do this all the time in Readme files, but never tried on DEV. To

Collapse
 
joachimzeelmaekers profile image
Joachim Zeelmaekers

Oh okay, thanks! Did not know that! 👏

Collapse
 
babakks profile image
Babak K. Shandiz

"Guard clause" is the commonly used title for early exit.

Collapse
 
joachimzeelmaekers profile image
Joachim Zeelmaekers

Oh thanks! Learned something new today!

Collapse
 
baenencalin profile image
Calin Baenen

Honestly, I get stuck with how to clean my code, but this is my rule of thumb. What do you think?:


# Imports
import modulestobeimported;
import modulestobeimported2;


# Do <thing>.
x = thing1(); # Make "x" a thing.
completething(x);

# Related things.
y.dothingwith(x, null); # Make Y do a thing to X.


# Semi-related.
a = str(y.getdata()); # Get graphing data.



# Unrelated things.
z = extrathings(); # Comment to clarify, if it seems confusing.



# Main method.
def Main():
    pass;

Enter fullscreen mode Exit fullscreen mode

The main (class and/or) method is considered unrelated to anything else, while, unrelated sections are 3 lines down, semi-related, 2, and related 1.

They don't always have to be labeled with comments, but, I think it looks neater.

One example is the CPane class from my most recent post (here).

Another is:


// Get graphing data for the money made from the server.
Tuple[] d = server.getGraphPoints("money-made");

// Graph some data.
Graph g = new Graph(
    new Tuple<int>(0, 0),
    new Tuple<int>(1000, 1000),
    d
); // Make a 1000 by 1000 graph to show the sales.


// Make a display to show the graph.
JFrame window = new JFrame("Data Graph");
window.add( g.getJPanelRepresentation() ); // Get the repr of the graph.

Enter fullscreen mode Exit fullscreen mode

Again, tell me what you think of my writing style, I'd love to hear feedback.

Collapse
 
emilesteen profile image
Emile Steenkamp • Edited

You don't need comments to explain what your code is doing. Better practice is to use code to explain what the code is doing.

for your last example you could rather do this:

Graph graph = getGraph("money-made");
displayGraph(graph);

function getGraph(String source) {
    Tuple[] graphPoints = server.getGraphPoints(source);
    Graph graph = new Graph(
        new Tuple<int>(0, 0),
        new Tuple<int>(1000, 1000),
        graphPoints
    );
    return graph
}

function displayGraph(Graph graph) {
    JFrame window = new JFrame("Data Graph");
    window.add( graph.getJPanelRepresentation() );
}
Enter fullscreen mode Exit fullscreen mode

In this example out functions are telling the developer exactly what is happening and splitting the code up into sections instead of comments. A common issue is that comments can lie. If you update the code and forget to update your comments your comments will be lying and can confuse you. If your code is readable you shouldn't need comments to explain what is happening.

Uncle Bob explains the use of comments much better in this talk:
youtu.be/2a_ytyt9sf8
and I would recommend watching the entire clean code series if you have time.

Collapse
 
baenencalin profile image
Calin Baenen

Is it bad, or to a disadvantage to use comments, then?

Thread Thread
 
darlantc profile image
Darlan Tódero ten Caten

Yes, experience teaches us that comments must be the last resource to be used only when the logic is very hard to explain. Even so in most times is better to break that complicated logic into multiple small functions to be easy to read that code later.

Always try to name all variables, functions, and classes with meaningful names that self explain itself, avoiding the usage of comments.

Also, another problem with comments is that when the code changes very often the developers don't update the comments (the linter don't tell us that they are wrong now) and they don't reflect anymore the current logic of the code.

Collapse
 
evanyoung1996 profile image
EvanYoung

Great post!

I'm from HelloGitHub, a nonprofit organization in China. I am reaching out to you to ask if it's OK for us to translate your posts, "Clean up your code by applying these 7 rules", into Chinese and publish it on our WeChat official account. You own the copyright of course.

How does that sound to you?

Collapse
 
joachimzeelmaekers profile image
Joachim Zeelmaekers

You can translate it and publish it, thanks for asking! I appreciate the interests!

Collapse
 
bebetos92 profile image
Alberto Talone

Nice article!
I really love to boyscout rule but I'm always afraid to destroy something 😂
About the team code style, every team should think about that, and a lot of them don't know or don't want to "waste" time about that..what a pity!

Collapse
 
joachimzeelmaekers profile image
Joachim Zeelmaekers

For the boy scout rule, the tests should help you to not break something. And most of the time people forget about very important parts before they start a project. Like the code style.

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Why so verbose? Why not just:

const mergeArrays = (...arrays) => arrays.reduce((merged, arr) => [...merged, ...arr])
Enter fullscreen mode Exit fullscreen mode

It's equally readable

Collapse
 
joachimzeelmaekers profile image
Joachim Zeelmaekers

Well it’s just to make the code snippet clear. As I said in the article, it could be replaced by a nice oneliner, but that’s not really the point of this article.

Collapse
 
felipemartins81 profile image
Felipe Martins

Good solution for 'If statements' issue!
What about this way?..

switch (value) {
    case 'duck':
    case 'dog':
    case 'cat':
        // ...
        break;
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
joachimzeelmaekers profile image
Joachim Zeelmaekers

In this case this would be a good solution, but it gets really big when you have to check 10 options for example! The switch statement is also not available in Python for example.

Collapse
 
kretaceous profile image
Abhijit Hota

The reason I use JSDoc in VS Code is for its autocomplete feature! But I do agree a function should be as self explanatory as possible.

Great write-up! 😄

Collapse
 
redheadcoder profile image
Esther

you should probably point out that destructuring is ES6 syntax, which may not be compatible with every codebase

Collapse
 
7ovo7 profile image
Marco Colonna • Edited

I'm not in the sector of informatics, and I know very little about informatics (something about HTML PHP CSS and very little about C), but I've always wondered why editors and IDEs for writing and compiling code don't separate automatically comments into a second file, in order to keep the final code clean, and to preserve the useful organization through the comments thus preserved; or maybe similar programs already exist and I don't know them.

Collapse
 
yuvrajkhavad profile image
Yuvraj Khavad

Hey, Thanks for good solutions, thank you for sharing with us.

Collapse
 
designeranna1 profile image
Designer Anna

Great tips to improve our coding skills. :)
Thanks for sharing this.

Collapse
 
phongduong profile image
Phong Duong

Thank you for sharing. I don't use the comment for my code. If I read my code after 1 month, I sometimes don't understand what it does and have to spend times rereading the whole function or file