10 Tips for Writing Cleaner & Better Code

10 Tips for Writing Cleaner & Better Code

For sure, programming is hard. It is one factor to be taught languages and research algorithms, nevertheless it’s an entire different beast attempting to code a posh working software that does not make you wish to claw your eyes out.

In a approach, writing clear code is rather a lot like drawing, cooking, or images—it seems to be simpler than it really is. So why hassle? Effectively, as a result of the advantages are price it.

Why You Ought to Write Clear Code

There are a number of advantages to writing clear code. A few of them embody the next:

  • Issues grow to be simpler to resolve. When you begin excited about clear code, your strategy to problem-solving modifications. As a substitute of brute-forcing options, your algorithms and software program design turns into extra elegant and intentional.
  • Much less time is wasted on upkeep. Clear code is simpler to learn and perceive, so that you spend much less time attempting to determine what sure segments really do and extra time on fixing, revising, extending, and many others.
  • Concepts are extra clearly communicated. In the event you’re working with different programmers, clear code reduces the chance of misunderstandings between all of you, which additionally means fewer bugs in the long term.

This is how one can begin writing clear code. Now that you simply acknowledge the significance of writing clear code, listed here are our prime 10 ideas for writing good code.

1. Use Descriptive Names

A programming is working on app development

What are variables, courses, and features? There are a lot of methods to reply that, however whenever you actually give it some thought, these issues are nothing greater than the interface between a programmer and the underlying logic of an software.

So whenever you use unclear and non-descriptive names for variables, courses, and features, you are basically obfuscating the appliance logic from any programmer who reads the code, together with your self.

“I am not a terrific programmer; I am only a good programmer with nice habits.”

— Kent Beck

What does a variable named dxy really imply? Who is aware of. You’d in all probability need to learn your entire chunk of code to reverse engineer its that means. However, the that means of a variable like distanceBetweenXY is immediately recognizable.


The identical is true for courses and features. Do not accept CalcTan() when you may go for CalculateTangent() or CalcTangentAngle() as a substitute. One of many elementary ideas for making code look neat is through the use of descriptive names.

2. Give Every Class/Perform One Function

Computer code on a screen

Have you ever ever peeked inside a perform that was tons of and even 1000’s of strains lengthy? You probably have, then you know the way a lot of a ache it may be to browse, perceive, and edit. Feedback may help however solely to a restricted diploma.

“Programming is breaking one huge inconceivable process into a number of small attainable duties.”

— Jazzwant

Clear code is damaged down into atomic chunks. Each perform ought to purpose to do one single factor, and each class ought to purpose to signify one explicit idea. This can be a simplification, in fact, however when unsure, less complicated is cleaner.

In observe, a posh calculation like GetCreditScore() could must be damaged into a number of helper features like GetCreditReports(), ApplyCreditHistoryAge(), and FilterOutstandingMarks(). Holding it easy is simply one of many primary programming rules each programmer ought to know.

3. Delete Pointless Code

This unhealthy behavior is one which programmers wrestle with occasionally. It often occurs like this: You wish to repair or optimize a bit of code, so that you remark it out and do a rewrite slightly below it—and despite the fact that it really works, you retain the previous code there simply in case.

“Is it attainable that software program will not be like the rest, that it’s meant to be discarded: that the entire level is to at all times see it as a cleaning soap bubble?”

— Alan J. Perlis

Over time, you accumulate a number of commented-out blocks of code which can be now not wanted but litter up your supply recordsdata. And the humorous factor is that in a number of instances, the encircling code has developed, so the commented-out code would not work even when restored.

Data structures in programming

The factor is that this observe of commenting out “backup code” was made out of date by supply management. In the event you aren’t utilizing one thing like Git or Mercurial, it’s worthwhile to begin utilizing supply management instantly. Cleaner code awaits you.

Keep in mind, it is also necessary to keep away from writing repetitive code, which you’ll accomplish simply with an online framework. Listed below are a number of net frameworks price studying as a developer.

4. Readability > Cleverness

Too many programmers conflate “clear code” with “intelligent code” as if compacting ten strains into one is by some means cleaner. Certain, it takes up much less house on the display screen, however is it really simpler to know? Generally, perhaps. However more often than not? No.

“Everybody is aware of that debugging is twice as arduous as writing a program within the first place. So in case you’re as intelligent as you will be whenever you write it, how will you ever debug it?”

—Brian W. Kernighan

I feel programmers love intelligent code as a result of it seems like a solved puzzle or riddle. They discovered a particular and distinctive strategy to implement one thing—a “shortcut,” if you’ll—and it virtually acts as a validation of the programmer’s abilities.

However to jot down clear code, it’s worthwhile to depart your ego on the door. At all times optimize code for the following one that’s going to learn it as a result of, in all chance, that subsequent particular person is definitely going to be you, and there is nothing extra shameful than being unable to learn or perceive your cleverness.

5. Hold a Constant Coding Type


We now have nothing in opposition to good programming tutorials, however one of many downsides is that newbies find yourself selecting all kinds of conflicting habits, particularly as they pertain to coding type.

We’re not right here to declare that one type is any higher than one other. If you’d like braces on their strains, go for it; if you wish to precede methodology calls with areas, effective. In the event you choose tabs to areas, do not allow us to persuade you in any other case.

However no matter you do, keep constant.

Stunning is healthier than ugly.

Express is healthier than implicit.

Easy is healthier than complicated.

Complicated is healthier than sophisticated.

Flat is healthier than nested.

Sparse is healthier than dense.

Readability counts.

— Tim Peters, The Zen of Python

If you are going to use camelCaseNaming for variables, do not adulterate it with underscore_naming. In the event you use GetThisObject() in a single place, do not go together with FetchThatObject() someplace else. And in case you combine tabs and areas, you should have your keyboard taken away.

Determine what you are going to do from the outset and keep it up by means of and thru. Some languages, like Python and C#, have language-wide type guides that you could be wish to comply with.

Associated: The Finest Free On-line Coding Programs for Pc Programming

6. Select the Proper Structure

There are a lot of paradigms and architectures that you need to use to create your tasks. Be aware how this tip is about choosing the fitting one on your wants, not about selecting the right one on the market. There isn’t any “greatest” right here.

“With out necessities and design, programming is the artwork of including bugs to an empty textual content file.”

— Louis Srygley

For instance, the Mannequin-View-Controller (MVC) sample is standard in net growth as a result of it helps to maintain your code organized and designed in a approach that minimizes upkeep efforts.

Equally, the Entity-Element-System (ECS) sample is standard in sport growth as a result of it helps modularize sport knowledge and logic in a approach that makes maintenance simpler, all whereas producing code that is simpler to learn.

7. Grasp the Language’s Idioms

Woman programming on a notebook with a Python book placed next to her

One of many difficulties in mastering a brand new programming language is studying the nuances that separate it from all different languages. These nuances will be the distinction between ugly, convoluted code and exquisite, easy-to-maintain code.

Think about Python, Java, and JavaScript. They’re all extraordinarily completely different from one another to the diploma that requires a distinct mind-set relying on which language you select to make use of.

“A language that does not have an effect on the best way you consider programming will not be price figuring out.”

— Alan J. Perlis

Whereas Python is all about compact code and duck typing, Java is extra in the direction of the aspect of verbosity and explicitness. Each language has idioms (equivalent to listing comprehensions in Python) that encourage a sure approach of coding. You’d do nicely to be taught them.

There are additionally “anti-patterns” to fret about, that are basically suboptimal design patterns that end in inefficient, unreliable, or in any other case unhealthy code. Examine and unlearn all of the widespread anti-patterns associated to your language of alternative.

8. Examine the Code of Masters

^ signs you aren't meant to be a programmer

If you wish to write clear code, the most effective factor you are able to do is to see what clear code seems to be like and attempt to perceive why it’s the approach it’s—and there isn’t any higher approach to do that than by finding out the supply recordsdata of business masters.

Clearly, you may’t simply pop into Microsoft’s headquarters and peek at their tasks, however you may at all times browse well-known open-source tasks. Do not know the place to start out? Attempt the showcased projects on Github.

“Any idiot can write code that a pc can perceive. Good programmers write code that people can perceive.”

— Martin Fowler, Refactoring: Enhancing the Design of Present Code

In any case, that is one of many explanation why open-source tasks exist: so others can be taught from them. And in case you resolve to contribute to such a venture, it will probably speed up the training course of.

rust command-line tools for linux

“Write good feedback” is the oldest piece of recommendation on the planet of programming. In reality, as quickly as newbies are launched to feedback, they’re just about inspired to remark as typically as they’ll.

However it virtually seems like we have swung too far in the wrong way. Newbies, specifically, are inclined to over-comment—describing issues that do not must be described and lacking the purpose of what a “good remark” really is.

“At all times code as if the man who finally ends up sustaining your code will probably be a violent psychopath who is aware of the place you reside.”

— John Woods

This is a very good rule of thumb: feedback exist to clarify WHY a chunk of code exists moderately than WHAT the code really does. If the code is written cleanly sufficient, it ought to be self-explanatory as to what it does—the remark ought to make clear the intention behind why it was written.

Feedback will be good for warnings (i.e., “eradicating this can break A, B, and C”) however, for essentially the most half, ought to uncover issues that may’t be instantly gleaned from the code (i.e., “use this parameter as a result of X, Y, and Z”).

Associated: Indicators You Aren’t Meant to Be a Programmer

10. Refactor, Refactor, Refactor

Simply as modifying is a part of the writing course of, refactoring is a part of the coding course of. An aversion to refactoring is the quickest strategy to find yourself with unmaintainable code, so in some ways, that is really crucial tip to think about.

In brief, refactoring is only a fancy time period for cleansing up the code with out impacting its precise habits.

“Every time I’ve to assume to know what the code is doing, I ask myself if I can refactor the code to make that understanding extra instantly obvious.”

— Martin Fowler, Refactoring: Enhancing the Design of Present Code

One little bit of knowledge that has caught with us is the saying: “Do not remark unhealthy code. Rewrite it”. As Fowler explains within the quote above, if code ever feels complicated sufficient that it’s worthwhile to remark it out, perhaps you really have to refactor it.

Man Doing Programming on Computer

Moreover, as you edit bits of code right here and there all through your venture, at all times depart the code in a greater state than whenever you first discovered it. It might seem to be a nuisance in the mean time, however it should repay in the long term (and may even stave off psychological burnout).

There’s At all times One thing New to Study

A programmer who’s studying learn how to write clear code is akin to a novelist studying learn how to write clear prose: there is not a proper strategy to do it per se, however there are many flawed methods to do it, and it will take years to grasp.

Some individuals haven’t got what it takes and finally find yourself quitting programming for good—and that is effective as a result of there are many different techy jobs that do not contain coding. However for everybody else, clear code is one thing that is completely price striving in the direction of, even when it takes the remainder of your life to get there.

The 9 Finest Coding Video games to Construct Your Programming Abilities

Coding video games make it easier to be taught sooner with hands-on observe and expertise. Plus, they are a enjoyable strategy to take a look at your programming abilities!

Learn Subsequent

About The Writer

Leave a Comment

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