loading...

How to write a clean code.

ishanbagchi profile image Ishan Bagchi ・2 min read

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

-Martin Fowler

There are two things- Programming and Good Programming. Programming is what we have all been doing, writing codes for the machines to understand. Now is the time to do good programming, the codes people can understand. We all know that even bad code works. But it takes time and resources to make a program good. Moreover, other developers mock you when they are trying to find what all is happening in your code. But it’s never too late to care for your programs.

Here are some of the methods to write clean codes.

Write DRY codes.

DRY is an acronym that stands for Don’t Repeat Yourself. If you are doing the same thing in multiple places, consolidate the duplicate code. If you see patterns in your code, that is an indication it is prime for DRYing. Sometimes this means standing back from the screen until you can’t read the text and literally looking for patterns.

clean code

const MyOtherComponent = ({ type }) => (
  <OtherComponent type={type} className="colorful" foo={123} bar={456} />
);
const MyComponent = () => (
  <div>
    <MyOtherComponent type="a" />
    <MyOtherComponent type="b" />
  </div>
);

bad code

const MyComponent = () => (
  <div>
    <OtherComponent type="a" className="colorful" foo={123} bar={456} />
    <OtherComponent type="b" className="colorful" foo={123} bar={456} />    
  </div>
);

Sometime DRYing code may increase your code size, but it increases maintainability. For eg, you can just change one line of the function which will be implemented all over the program.

Use Intention-Revealing name

The names of the variable should be revealed so that others can understand the purpose of the variable.

bad code

var $d; //elapsed time in days

clean code

var $elapsedTimeInDays;
var $daysSinceCreation;

Make code speak

The code should have the ability to make people understand what is its purpose.

clean code

if ($employee -> isEligibleForFullBenifits())

bad code

// check to see if the employee is elegible for full benifits
if ($employee -> flags && self :: HOURLY_FLAG && $employee -> age > 65)

Commented out code

We've all seen entire blocks of code containing multiple functions being commented out. Just delete that piece of commented-out code.

Messy formatting of code

One of the most common ways to solve messy formatting is by using a linter.

Here are some Do's and Dont's for clean code

+ Do's
  • Use verbs for function names
  • Use nouns for classes and attributes
  • The smaller the better
  • A function should only do one thing
  • Don't comment bad code, rewrite it
  • Explain your intention in comments
- Dont's
  • Dead code
  • Large classes
  • Framework core modifications
  • Overuse of static
  • Magic numbers - replace with const or var
  • Hard-coding

Conclusion

I hope that I’ve helped you see the benefits of writing clean code and that you can even use some of the practical examples presented here. Once you embrace writing clean code, it will become second nature. You (and your future self) will soon appreciate the “write it and forget it” way of life.

Acknowledgement

Posted on by:

ishanbagchi profile

Ishan Bagchi

@ishanbagchi

Hi, welcome to my account. I am a rising programmer, doing my B.tech from Siliguri Institute of Technology, Salbari, Darjeeling.

Discussion

pic
Editor guide
 

I fully agree, if code would just be for executing on the machine, it would be absolutely sufficient writing assembly language. The reason why we have all these high-level languages and frameworks these days, is to make it easier implementing complex systems. If we sabotage this by writing messy code, we loose a big advantages of these technologies.

Thx for sharing the thought "other developers will mock you" - to be honest, I wasn't fully aware of this until you pointed it out. But that's the case. When implementing a feature, I try to write the code like a store - it's not just a bunch of instructions for a machine, it's a story on how this business case is meant to be. The audience of this story is either my future self or another developer who has to modify something in this story a few years from now.

 

Everything is art. Even coding is an art in itself. Clean and attractive codes are just so satisfying to see and understand.

 

The other reason is that there is no "the machine".

There are many machines that the code should be able to target.

 

It should probably be noted that the majority of this article is a direct copy/paste/summarise from Uncle Bob's book Clean Code, while it also misses the point that Bob himself regularly makes - that writing clean code is hard.

I seriously doubt Bob would pursue anyone legally for trying to get the message across, but maybe consider giving the man a little credit for it (especially since the code samples are definitely direct copy/pastes from the book).

 

After almost 15 years of development , the one thing that get me angry is when people try to write the more concise code possible. Fewer line almost never mean better performance.
Write an intelligible code ,easy to read fluently instead of being a smart ass writing one-liners that everybody else need time to decrypt

 

I'd like to add a few thoughts about that DRY thing. It's a tricky one.

Over the years I've come to the realization that sometimes it's actually more readable to duplicate code on purpose. Like in your example I would totally go for the "bad" code because it's still way shorter than the "good" code. Even though it's duplicated, the reader will immediately see what's going on in MyComponent without having to mentally go forth and back between MyComponent and MyOtherComponent.

OK, I understand, this is really just a minimal example of the DRY principle so perhaps I shouldn't pick on it. But I often see similar situations in real life too, where good-intentioned colleagues have created one-liner methods (or even classes!) that are called in one or two places only, yet they require me to jump all around the place before I finally get the full picture of what MyComponent is actually doing.

Another case for violating the DRY principle is when you have two pieces of requirements that are almost - but not quite - the same. That's really a tough choice. There are three ways you can tackle that - duplicate code and make minor modifications in each place; put common code in a base class and specific code in child classes; or just pepper the code with a spiderweb of IF statements. All three are ugly, but I tend to find that code duplication is actually the lesser evil of the three a lot of the time. Whenever you're reading this code, most likely you'll just be interested in one of the versions, so having the other two out of the way is actually easier. And the thing about the different versions is that they tend to get even more different over time, so keeping up with the other two approaches you end up adding more and more abstract methods or IF statements. And that in turn makes it even less legible.

 

I understand you. Here in my example in OtherComponent it is ok to change just 2 lines if there is a mistake. Now just imagine if I had a few more lines of OtherComponent, and I had to change the class name, it would be so much pain to remove all of them and replace it with the new class name. Whereas in MyOtherComponent I just have to change the class name in just one line.

 

The DRY principle is not about code duplication, but knowledge duplication. It's not the same thing at all. From the Pragmatic Programmer, the book which coined the term, DRY is defined as:

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

This makes a big difference I explain here.

Other than that, all these principles are nice and we should definitely know them, but always keep in mind that it depends on the context you're in. Don't apply them blindly, think before if it's wise to apply them.

 

For a long time I have wanted to write a book somewhat along the lines of this one: on the one hand I knew that programs could have a compelling and deep logical beauty, but on the other hand I was forced to admit that most programs are presented in a way fit for mechanical execution but, even if of any beauty at all, totally unfit for human appreciation.

Edsger W. Dijkstra. A discipline of programming (1976).

 

How is var $d; //elapsed time in days clear code and var $elapsedTimeInDays; bad code?

 

Thank you for pointing, you are correct its other way round. 😅