Writing Clean Code and The Practice of Programming: Actionable advice for beginners
Tags: beginners, career, productivity
Published: 2019-11-27 20:52:16

> "**_The purpose of style is to make the code easy to read for yourself and others, and good style is crucial to good programming._**"

> -Brian W. Kerninghan in his book - [The Practice of Programming](https://www.goodreads.com/book/show/1032758.The_Practice_of_Programming)

When you are teaching yourself, it's easy to pick up bad habits or style because you don’t have someone checking your work. You don’t have many reference points for clean code because not many books/courses directly address these.

In this article, I want to give you some actionable advice on writing clean, beautiful code. 

## **5 simple, actionable, good programming practices:**

### **1. Put some thought into choosing your variables' names**

*"Should I be descriptive or can I be lazy?"*

That's the conundrum we all face when creating a new variable.

I find Brian W. Kerninghan's advice (in the above mentioned book) really helpful here:

> * Global functions, classes, and structures should have descriptive names that suggest their role in a program. 
> * By contrast, shorter names suffice for local variables; within a function, `n` may be sufficient, `npoints` is fine, and `numberofPoints` is overkill. 
> * Local variables used in conventional ways can have very short names. The use of `i` and `j` for loop indices, `p` and `q` for pointers, and `s` and `t` for strings is so frequent that there is little profit and perhaps some loss in longer names. 

Anyway, we have it a lot better than Brian did in the 90's when he wrote this book - *IDEs that can autocomplete our variable names*! 

So, can you really justify being lazy, now?

### **2. Create new functions wherever necessary**

It is easy to understand the syntax of writing functions in your favorite language. But it takes practice and some sense of design to learn when to break the code into functions. One goal is to design functions such that they can be reused when extending your program to new cases.

What more? Making such design choices are what make programming fun! 

Here are 3 heuristics from [Bob Martin's book Clean Code](https://www.goodreads.com/book/show/3735293-clean-code) that will guide you while making such choices:

* __Functions should be small__; how small? No more than a screenful or 20 lines
* __Functions should have descriptive names__. The smaller and more focused a function is, the easier it is to choose a descriptive name. Don’t be afraid to make a name long. A long descriptive name is better than a short enigmatic name. A long descriptive name is better than a long descriptive comment.
* __Functions should do only one thing__ and have no "side effects" - its intent should be clear from its name

When you first write a function it will probably come out long and complicated and not follow any of the above rules. And that's ok. You can refine and reformat your code later. I don't think anyone could start with writing functions that follow all the rules mentioned above. 

Remember they are function-building goals that you need to strive towards. Don't let them paralyse you. 

### **3. Document your code and write helpful comments**

{% twitter 849295255912534018 %}

You code should always include comments that serve as documentation for the functions and modules. Every function definition should be preceeded by a comment that includes - 

1. A short, one/two sentence description of what the function does.
2. Followed by a one line description of every argument that the function accepts (if they exist)
3. Which is followed by a one line description of the return variable of the function (if it exists)

Apart from that, you should include comments to describe less-comprehensible parts of your code. Just remember that - 

* Comments are meant to **help the reader** of a program. They do not help by saying things the code already plainly says, or by contradicting the code, or by distracting the reader with elaborate typographical displays.
* As much as possible, **write code that is easy to understand**; the better you do this, the fewer comments you need. Good code needs fewer comments than bad code. Comments are, at best, a necessary evil.
* **Don't contradict the code**. Most comments agree with the code when they are written, but as bugs are fixed and the program evolves, the comments are often left in their original form, resulting in disagreement with the code. 

### **4. Be consistent**

* Follow standard practices whenever you can. Search for **"< insert programming language> style guide"** and follow a credible source throughout your code. Here's the [Python PEP8 Style guide](https://www.python.org/dev/peps/pep-0008/) recommended by Python itself. 

* If you aren't sure of what the standard is or need to break away from it, make sure that you have a reason and that you do it consistently throughout your code.

* Be consistent in the way you name your variables, the way you indent your code, the way you document your functions and all the way to whether you use `++i` or `i++`. 

#### Why:

Because consistent coding style is good coding style. It makes it easy for someone (including you, yourself) to dive into your code and read it in the future.

### **5. If it breaks, assume that it's (_probably_) __your__ fault**

And, learn to own it.

{% twitter 1022532191342002182 %}

You are likely to spend a majority of your coding time banging your head over broken code. In those moments, you will inevitably try to shift the blame to your IDE, compiler, environment or your machine.  But you should remember - *It's not the computer, it's you.*

Only when you do that, will you be able to diagnose and get to the heart of the problem (even if it is some problem with the machine).

**How to debug your code:**

* **Explain the code to a friend or use the "Rubber duck technique"**

> 1. Pick a friend (or a rubber duck)
> 2. Open the problematic code and explain it to him (/her/it), line by line, slowly and patiently
> 3. Find the problem staring at you, in your face, without any help of your friend (or the duck), as if by magic! 

* **Add print statements**

<figure>
  <img src="https://thepracticaldev.s3.amazonaws.com/i/oirsdho3nnmne3dwr7ik.png" alt="Print statement debugging meme"/>
  <figcaption>You know.. these print statements! :joy:</figcaption>
</figure>

Although adding such print statements isn't the correct way to debug, I find them incredibly effective at times. Especially, when I'm working with a text editor like VIM and not on a full-fledged IDE that has a debugger (or when you are too lazy to learn how to use a debugger :p).

But I have to say, once you learn how to use an IDE debugger, there is no going back..

* **Use an IDE debugger** 

{% twitter 951514484979519490 %}

A debugger can be so useful that I will recommend you to learn how to use the debugger in it. Trust me, it is totally worth the pain!

*Personal advice: I using "IDE debugger" because Python provides a debugger in the standard library module - **`pdb`** - and I won't recommend using it.

---

In the end, remember that *the principles of programming style are based on common sense guided by experience, not on arbitrary rules and prescriptions.* 

### **Guiding principles:** 

1. **Don’t settle for “it runs”.**
1. **Write for readability - code is read more often than it is written.**
1. **Explicit is better than implicit.**
1. **Duplication may be the root of all evil in software.**

These should help you when you forget any rules or run into new situations in the real-world that are not covered by these concise rules.

---

## So, how can you adopt these and improve your own coding style?

Mind you - only reading about such practices is not enough. 

{% twitter 1018544870112165888 %}

These are difficult-to-grab intuitions and the best way to develop your own intuitions is through practice. 

I have [written before](https://medium.com/free-code-camp/learn-how-to-be-a-better-programmer-by-automating-the-boring-stuff-74a67a568c50) that the problem with the teaching-through-small-programs approach is that it doesn’t

* develop your intuition - like how to go about modularizing your code
* address how to write functions so that can be reused when extending your program to new use cases
* talk about the trade-off between writing readable code and compact code
provide focus on the need for a good and consistent programming style

In summary, small programs fail to teach the core design choices that one learns to make when creating larger programs working on your side-projects.

So, the way you develop these intuitions is by working on projects.

If you are stuck at the stage of finding ideas for an interesting project, I have written an article to help you out:

{% link https://dev.to/nityeshaga/fantastic-programming-project-ideas-and-where-to-find-them-the-beginner-friendly-version-9d5 %}

And if the idea of building your own project still seems too daunting, I wrote a guide to walk you through one of the projects in the above article:

{% link https://dev.to/nityeshaga/advance-your-python-skills-by-building-a-whatsapp-chat-analyser-a-guided-project-6p9 %}

If you are interested in building it, you can find peers in our Slack group - [Build To Learn Slack group](https://join.slack.com/t/build-to-learn/shared_invite/enQtMzg3MzYyNTA5MjAzLTkwMGYyYTljOTdkNTIzODJhNTlkZWQxMTZkODJmY2YxMTQ4OTVkODM1MTVlM2FmYTE0MzkwODhhYTc5MDc4YmI) (please feel free to join us). You can ask me or your fellow learners your doubts over here.

---

What other good programming practices do you follow religiously? Do you have some guiding principles of your own that you use to write more beautiful code? Let the community know in the comments below.

Subscribe to the [Build To Learn newsletter](https://buildtolearn.substack.com/) to get an email when I do new guides and articles. 

You can reach out me on both [Twitter](https://twitter.com/nityeshaga) and [LinkedIn](https://www.linkedin.com/in/nityeshaga).