10 Tips for Writing Cleaner & Better Code

Joel Lee 12-07-2016

Without a doubt, programming is tough. It’s one thing to learn languages and study algorithms, but it’s a whole other beast trying to code a complex working application that doesn’t make you want to claw your eyes out.


In a way, writing clean code is a lot like drawing, cooking, or photography—it looks easier than it actually is. So why bother? Well, because the benefits are worth it:

  • 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.

Here’s how YOU can start writing clean code.

1. Use Descriptive Names

What are variables, classes, and functions? There are many ways to answer that, but when you really think about it, those things are nothing more than the interface between a programmer and the underlying logic of an application.

So when you use unclear and non-descript names for variables, classes, and functions, you’re essentially obfuscating the application logic from any programmer who reads the code, including yourself.

“I’m not a great programmer; I’m just a good programmer with great habits.”
— Kent Beck

What does a variable named dxy actually mean? Who knows. You’d probably have to read the entire chunk of code to reverse engineer its meaning. On the other hand, the meaning of a variable like distanceBetweenXY is instantly recognizable.


The same is true for classes and functions. Don’t settle for CalcTan() when you can go for CalculateTangent() or CalcTangentAngle() instead.

2. Give Each Class/Function One Purpose

Have you ever peeked inside a function that was hundreds or even thousands of lines long? If you have, then you know how much of a pain it can be to browse, understand, and edit. Comments can help but only to a limited degree.

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

Clean code is broken down into atomic chunks. Every function should aim to do one single thing and every class should aim to represent one particular concept. This is a simplification of course, but when in doubt, simpler is cleaner.

In practice, a complex calculation like GetCreditScore() may need to be broken into several helper functions like GetCreditReports(), ApplyCreditHistoryAge(), and FilterOutstandingMarks().


3. Delete Unnecessary Code

This bad habit is one that I still struggle with from time to time. It usually happens like this: I want to fix or optimize a chunk of code so I comment it out and do a rewrite just below it — and even though it works, I keep the old code there just in case.

“Is it possible that software is not like anything else, that it is meant to be discarded: that the whole point is to always see it as a soap bubble?”
— Alan J. Perlis

Over time, I accumulate a whole lot of commented-out blocks of code that are no longer needed yet clutter up my source files. And the funny thing is that in a lot of cases, the surrounding code has evolved so the commented-out code wouldn’t work even if restored.

The thing is, this practice of commenting out “backup code” was made obsolete by source control. If you aren’t using something like Git or Mercurial, you need to start using source control right away. Cleaner code awaits you.

Remember, it’s also important to avoid writing repetitive code, which you can accomplish easily with a web framework. Here are a few web frameworks worth learning as a developer 5 Web Frameworks Worth Learning for Developers Interested in learning advanced web development? Avoid writing repetitive code---use these web development frameworks instead. Read More .


4. Readability > Cleverness

Too many programmers conflate “clean code” with “clever code”, as if compacting ten lines into one is somehow cleaner. Sure, it takes up less space on the screen, but is it actually easier to understand? Sometimes, maybe. But most of the time? No.

“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

I think programmers love clever code because it feels like a solved puzzle or riddle. They found a special and unique way to implement something — a “shortcut” if you will — and it almost acts as a validation of the programmer’s skills.

But to write clean code, you need to leave your ego at the door.

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

I have nothing against good programming tutorials What Makes a Good Programming Tutorial? Not all programming tutorials are made equal. Some benefit you and others end up wasting your time. Here's what to look for in a quality programming tutorial. Read More , but one of the downsides is that newbies end up picking up a wide variety of conflicting habits, especially as they pertain to coding style.

I’m not here to declare that one style is any better than another. If you want braces on their own lines, go for it. If you want to precede method calls with spaces, fine. If you prefer tabs to spaces, don’t let me convince you otherwise.

But whatever you do, stay consistent!

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

If you’re going to use camelCaseNaming for variables, don’t adulterate it with underscore_naming. If you use GetThisObject() in one place, don’t go with FetchThatObject() somewhere else. And if you mix tabs and spaces, you deserve to have your keyboard taken away.

Decide what you’re going to do from the outset and stick with it through and through. Some languages, like Python and C#, have language-wide style guides that you may want to follow.

6. Choose the Right Architecture

There are many different paradigms and architectures that you can use to create your projects. Note how this tip is about selecting the right one for your needs, not about selecting the best one out there. There is no “best” here.

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

For example, the Model-View-Controller (MVC) pattern is very popular right now in web development because it helps to keep your code organized and designed in a way that minimizes maintenance efforts.

Similarly, the Entity-Component-System (ECS) pattern is very popular right now in game development because it helps modularize game data and logic in a way that makes upkeep easier, all while producing code that’s easier to read.

7. Master the Language’s Idioms

One of the difficulties in mastering a new programming language 7 Useful Tricks for Mastering a New Programming Language It's okay to be overwhelmed when you are learning to code. You'll probably forget things as quickly as you learn them. These tips can help you to better retain all that new information. Read More is learning the nuances that separate it from all other languages. These nuances can be the difference between ugly, convoluted code and beautiful, easy-to-maintain code.

Consider Python, Java, and JavaScript. They’re all extremely different from each other, to a degree that requires a different way of thinking depending on which language you choose to use.

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

Whereas Python is all about compact code and duck typing, Java is more towards the side of verbosity and explicitness. Every language has idioms (such as list comprehensions in Python) that encourage a certain way of coding. You’d do well to learn them.

There are also “anti-patterns” to worry about, which are essentially sub-optimal design patterns that result in inefficient, unreliable, or otherwise bad code. Study and unlearn all of the common anti-patterns related to your language of choice.

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.

Obviously, you can’t just pop into Microsoft’s headquarters and peek at their projects, but you can always browse well-known open-source projects How To View & Edit The Source Code Of An Open-Source App While going open source might be a good choice, you'll also need to invest in the right community. GitHub is one of the best places to do this, not only because of the sheer amount... Read More . Don’t know where to start? Try the showcased projects on Github.

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”
— Martin Fowler, Refactoring: Improving the Design of Existing Code

After all, that’s one of the reasons why open-source projects exist Why Do People Contribute to Open Source Projects? Open source development is the future of software. It's great for users because open source software is usually available gratis and often safer to use. But what compels developers to contribute code for free? Read More : so others can learn from them. And if you decide to contribute to such a project, it can accelerate the learning process 5 Project Ideas To Help You Learn Programming Faster There are a few ways to ease the learning curve for programming. Get your hands dirty and learn faster with side projects you can start anytime. Play around with these five. Read More .

Personally, the very first time I saw truly clean code is when I stumbled across a certain hobbyist’s open-source Python project. The code was so overwhelming elegant that I nearly quit programming, but it ended up teaching me a lot.

9. Write Good Comments

“Write good comments” is the oldest piece of advice in the world of programming. In fact, as soon as newbies are introduced to comments, they’re pretty much encouraged to comment as often as they can.

But it almost feels like we’ve swung too far in the opposite direction. Newbies, in particular, tend to over-comment – describing things that don’t need to be described and missing the point of what a “good comment” actually is.

“Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.”
— John Woods

Here’s a good rule of thumb: comments exist to explain WHY a piece of code exists rather than WHAT the code actually does. If the code is written cleanly enough, it should be self-explanatory as to what it does — the comment should shed light on the intention behind why it was written.

Comments can be good for warnings (i.e. “removing this will break A, B, and C”) but for the most part should uncover things that can’t be immediately gleaned from the code (i.e. “use this parameter because X, Y, and Z”).

10. Refactor, Refactor, Refactor

Just as editing is part of the writing process, refactoring is part of the coding process. An aversion to refactoring is the quickest way to end up with unmaintainable code, so in many ways this is actually the most important tip to consider.

In short, refactoring is just a fancy term for cleaning up the code without impacting its actual behavior.

“Whenever I have to think to understand what the code is doing, I ask myself if I can refactor the code to make that understanding more immediately apparent.”
— Martin Fowler, Refactoring: Improving the Design of Existing Code

One bit of wisdom that has stuck with me is the saying, “Don’t comment bad code. Rewrite it.” As Fowler explains in the quote above, if code ever feels confusing enough that you need to comment it, maybe you actually need to refactor it.

Furthermore, as you edit bits of code here and there throughout your project, always leave the code in a better state than when you first found it. It may seem like a nuisance in the moment, but it will pay off in the long run (and can even stave off mental burnout Programming Burnout: How to Regain Your Lost Motivation Feeling tired of programming? Suffering burnout and can't see a way out? Here's how to begin regaining your motivation to code. Read More ).

There’s Always Something New to Learn

A programmer who’s learning how to write clean code is akin to a novelist learning how to write clean prose: there isn’t a right way to do it per se, but there are plenty of wrong ways to do it, and it’ll take years to master.

Some people don’t have what it takes and eventually end up quitting programming for good 6 Signs You Aren't Meant to Be a Programmer Not everyone is cut out to be a programmer. Is coding right for you? Here are some signs to point you in the right direction. Read More — and that’s fine because there are plenty of other techy jobs that don’t involve coding Coding Isn't for Everyone: 9 Tech Jobs You Can Get Without It Don't be discouraged if you want to be a part of the tech field. There are plenty of jobs for people without coding skills! Read More . But 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.

Affiliate Disclosure: By buying the products we recommend, you help keep the site alive. Read more.

Whatsapp Pinterest

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. Outsourcemyjob
    January 28, 2019 at 5:01 am

    writing better depend on research and maintain the quality of writing is not ease. we do need to keep learning and follow some tips. Thanks

  2. mike
    November 10, 2017 at 10:23 pm

    I would add "do no harm."
    Most coding is maintenance and as a maintainer the programmer should read through the code to get a sense of what the original programmer was doing and if possible why he chose to do it the way it was done.
    This general understanding will give the maintenance coder a jumping off place to maintain the original code and do any necessary alterations in the spirit of the original program. I always wonder why writers position the "imaginary" programmer in their articles as some intrepid loner. Few programmers strike out to build a product like Microsoft Office on their own and companies usually select their most experienced programmers to break new ground. Most projects and code writing is as a team effort with particular modules being done by one or another coder after the team has laid out a plan on executing the work with new programmers following the lead of the experienced coder to "learn the trade." Or more cynically, the way we do it here.

  3. A
    September 7, 2017 at 6:12 pm

    The underlying idea that drives my coding style is empathy.

    Will this suck for someone else to understand later? When I eventually forget how I wrote this, would I wish it had more comments or fewer? Yeah this test might be annoying to write, but if someone tries to refactor would they prefer it had a test?

  4. Andy
    April 25, 2017 at 4:29 pm

    I agree on everything, but I have mixed feelings about your views on commenting.
    Many times, I comment what a bunch of lines are doing because those lines are just one of many chunks that are step-by-step operations for an end result of a complex or long instruction. By the end of the day, I have a bunch of chunks that lead to an end product, and I don't have to read each chunk to know what they're doing - I skim over the comments. that tell me what they are doing. I then know why they are there in the first place since I know what they're leading up to.

  5. Joseph Pollock
    December 21, 2016 at 11:23 pm

    Nice, clear article. And great quotes!

    One thing I learned working on maintaining some larger programs (similar to what Fcd76218 said): If it ain't broke, don't fix it.

    This may sound like it goes against the whole article, but if you clean something up or make it "better" without understanding the entire system it's a part of, there's a good chance that you may introduce bugs that are hard to find by doing things like eliminating side effects that some other part of the system relies on.

  6. Anonymous
    July 14, 2016 at 4:39 am

    Your write, it's tough and hard, and sometimes I sit for hours just thinking "How am I gonna make this work? What should I do? Where do I start?". But that's what makes it so fricken fun. The problem solving.

    • Joel Lee
      July 26, 2016 at 4:14 pm

      The harder the problem, the more satisfying it is to finally solve it! Unless it's so hard that it makes you give up. That's no bueno. :P Thanks for sharing, Jaden.

      • Anonymous
        July 26, 2016 at 4:16 pm

        Yeah, unless it makes you give up lol

  7. Matthew Hughes
    July 12, 2016 at 11:23 pm

    Great work Joel. Allow me to add an 11th point - "Always Follow The Conventions Of The Codebase You're Working On"

    I learned this one the hard way. If you're collaboratively working on something, try to match the style used by the rest of your team. Even if you know a better way, adding inconsistencies helps literally nobody.


    • Anonymous
      July 13, 2016 at 2:29 pm

      "Even if you know a better way, adding inconsistencies helps literally nobody. "
      Of course you could teach your better way to the rest of the team, making everybody more efficient.

    • Joel Lee
      July 13, 2016 at 8:52 pm

      Absolutely, Matt! I haven't worked on a team project in a while but that was one of the most frustrating things to deal with. An internal style guide is essential part of maintaining sanity!

  8. Anonymous
    July 12, 2016 at 12:09 pm

    "Real programmers don't document. If it was hard to write, it should be hard to understand." - Some guy whose mess I need to work on now.

    • Joel Lee
      July 13, 2016 at 8:51 pm

      Haha, I would hate working with someone who believed that. :(