10 Tips for Writing Cleaner & Better Code

Without a doubt, programming is tough.In a way,
writing clean code is a lot like drawing, cooking,
or photography — it looks easier than it actually is. But actually it’s difficult.

I. Benefits

  • Problems become easier to solve.
    Once you start thinking in clean code, your approach to problem-solving changes. Instead of brute forcing solutions, your algorithms and software design become more elegant and intentional.
  • Less time is wasted on maintenance.
    Clean code is easier to read and understand, so you spend less time trying to figure out what certain segments actually do and more time on fixing, revising, extending, etc.
  • Ideas are more clearly communicated.
    If you’re working with other programmers, clean code reduces the likelihood of misunderstandings between all of you, which also means fewer bugs in the long run.

II. 10 Tips

1. Use Descriptive Names

“I’m not a great programmer;
I’m just a good programmer with great habits.”
— Kent Beck
Don’t settle for CalcTan() when you can go for CalculateTangent() or CalcTangentAngle() instead.

2. Give Each Class/Function One Purpose

“Programming is breaking one big impossible task into several small possible tasks.”
— Jazzwant

3. Delete Unnecessary Code

4. Readability > Cleverness

“Everyone knows that debugging is twice as hard as writing a program in the first place. So if you’re as clever as you can be when you write it, how will you ever debug it?”
— Brian W. Kernighan
Always optimize code for the next person who’s going to read it, because in all likelihood that next person is actually going to be YOU and there’s nothing more shameful than being unable to read or understand your own cleverness.

5. Keep a Consistent Coding Style

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
— Tim Peters, The Zen of Python

6. Choose the Right Architecture

“Without requirements and design, programming
is the art of adding bugs to an empty text file.”
— Louis Srygley

7. Master the Language’s Idioms

“A language that doesn’t affect the way
you think about programming is not worth knowing.”
— Alan J. Perlis

8. Study the Code of Masters

If you want to write clean code, the best thing you can do is to see what clean code looks like and try to understand why it is the way it is — and there’s no better way to do this than by studying the source files of industry masters.

9. Write Good Comments

Here’s a good rule of thumb: comments exist to explain WHY a piece of code exists rather than WHAT the code actually does.

10. Refactor, Refactor, Refactor

  • For everyone else, clean code is something that’s absolutely worth striving towards, even if it takes the rest of your life to get there.