Build To Learn (4 Part Series)
"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
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.
"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,
nmay be sufficient,
npointsis fine, and
- Local variables used in conventional ways can have very short names. The use of
jfor loop indices,
qfor pointers, and
tfor 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?
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 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.
Programming Wisdom"Documentation is a love letter that you write to your future self." - Damian Conway 💌16:19 PM - 04 Apr 2017
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 -
- A short, one/two sentence description of what the function does.
- Followed by a one line description of every argument that the function accepts (if they exist)
- 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.
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 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
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.
And, learn to own it.
Jen Simmons@jensimmonsDon’t take it personally. You don’t know what code to write? Yeah, we all don’t know what code to write. We figure it out. Line by line. Bit by bit. It’s broken most of the time. Until it’s not. Then we go write new broken code. Until it’s not broken.
Welcome. That’s the job.17:20 PM - 26 Jul 2018
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"
- Pick a friend (or a rubber duck)
- Open the problematic code and explain it to him (/her/it), line by line, slowly and patiently
- 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
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
Programming Wisdom"Debuggers don't remove bugs. They only show them in slow motion." - unknown18:01 PM - 11 Jan 2018
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.
- Don’t settle for “it runs”.
- Write for readability - code is read more often than it is written.
- Explicit is better than implicit.
- 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.
Mind you - only reading about such practices is not enough.
These are difficult-to-grab intuitions and the best way to develop your own intuitions is through practice.
I have written before 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:
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:
If you are interested in building it, you can find peers in our Slack group - Build To Learn Slack group (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 to get an email when I do new guides and articles.