Plan your coding
When starting up a big project or an advanced function, having a pre-made plan will often save you a lot of time. Even though everything seems clear at first, you may have forgotten or will forget something crucial while writing.
A good plan should contain information about your coding approach, when the different variables are known and unknown, and what the output of each code block is supposed to be. Knowing all this information in advance will help you locate difficult sections of your code, as well as prevent unnecessary code and rewriting.
Write useful comments
Commenting while writing will always help you out in the long run. Your code may seem very simple and self explanatory at the time of writing, but to someone else, or yourself in three months, it is not necessarily that simple. Write meaningful, single line comments for vague lines, and more detailed descriptions for more difficult sections. Also, remember to keep updating your comments when updating your code.
Use meaningful names
The name of a variable, class or function should in itself explain what it does and why it's there. If a name requires a comment, it does not reveal it's content. Take a look at the example below, which variable is easiest to interpret.
Code Block | ||
---|---|---|
| ||
int d = 3600 # Seconds in one hour # vs int secInHour = 3600 |
Beware of names with very few differences, making them difficult to seperate.
Code Block | ||
---|---|---|
| ||
int likesAtMDGFacebookPage # vs int likesAtMGPFacebookPage |
Use pronounceable names.
Code Block | ||
---|---|---|
| ||
str famousBlvd # vs str famousBoulevard |
Naming conventions
When writing code, there are many different naming conventions in use. When seperating words within a single name, the two types most used are the underscore-method and camelCase-method.
Code Block | ||
---|---|---|
| ||
int this_is_the_underscore_method # vs int thisIsTheCamelCaseMethod |
Unless you are told to use one specific method, choose the one you prefer the most and stick with it. Mixing the two methods is a recipe for disaster, and should always be avoided.
Use some extra space when necessary
Writing readable code is essential when coding, and using spaces within your code is an easy way to improve the readability a lot. Take a look at the short code example below, and see what a couple of extra spaces does to the code.
Code Block | ||
---|---|---|
| ||
>>> from sympy import * >>> x = Symbol('x') >>> solve([x + 5*y - 2, -3*x + 6*y - 15], [x, y]) {x: -3, y: 1} # vs >>> x=Symbol('x') >>> solve([x+5*y-2,-3*x+6*y-15],[x,y]) {x: -3, y: 1} |
Info |
---|
The use of whitespaces in your code does not affect the performance of your code. Some editors will help autoformat your code while writing. This is a great feature, so check if your preffered editor has this possiblity. |
Some coding quotes
“Clean code always looks like it was written by someone who cares.”
Robert C. Martin