Code Style Guide
βAny fool can write code that a computer can understand. Good programmers write code that humans can understand.β
β Martin Fowler
Just as important as the functionality of your solution is the readability of your code. And generally, there are some ways of writing code that that makes your code more understandable and readable than others. Below are some of those practices.
This is a living document that I will be updating as we go along.
From when you begin programming it is essential that you follow the guidelines below - a good habit is much easier to get in to when you start!
β Naming Variables and Functionsβ
Making our code understandable by others is critical to being a programmer. One of the main tools in our toolbox is good naming for our variables and function names.
There are no strict rules to follow when thinking of variable names, but there are some general guidelines.
When thinking about whether a variable name is good, try to imagine that you are reading the code again in the future and you have forgotten exactly how it works.
Do the variable names help explain what the code is supposed to do?
Avoid ambigious abbreviationsβ
Avoid mental mappings, acronyms and abbreviations (unless it's univerasally understood by everyone). Don't come up with your own; it's better to use a long name than a confusing one.
# π Bad
fna = 'Bob'
cre_tmstp = 1621535852
evtnm = 'IT Expo'
# β
Good
first_name = 'Bob'
creation_timestamp = 1621535852
event_name = 'IT Expo'
Use descriptive/intention-revealing namesβ
A good variable name quickly explains what it represents to anyone reading the code. Try to describe what the variable is or what it does within in code, and
# π Bad
song = True;
# β
Good
song_is_playing = True;
Also, parameters of functions should also have names that properly represent what is going to be received into the function.
# π Bad
def is_old_enough(number):
return number > 18
# β
Good
def is_old_enough(year_of_birth):
return year_of_birth > 18
Use verbs for function namesβ
In this example, the function calculates a percentage and returns it. Therefore it is good to name it using the "get" verb to show that it returns something.
# π Bad
def percentage():
return 100
# β
Good
def getPercentage():
return 100
Don't use different words for the same conceptβ
# π Bad
def get_name(): pass
def fetch_age(): pass
# β
Good
def get_name(): pass
def get_age(): pass
β Avoid Long Functionsβ
Sometimes writing long functions are unavoidable, however most of the time is better to split a long function into a few shorter ones.
This will
- Make your code easier to read
- Make your code easier to maintain
- Make your code easier to review by out volunteers
When you writing code you should also try to keep in mind that you will only ever write the code once, but you will read the code many times. Always aim to write code that is readable.
For more details you can read these useful articles
- (The Art of Writing Small and Plain Functions)[https://dmitripavlutin.com/the-art-of-writing-small-and-plain-functions/]
β No Dead codeβ
If it doesn't run, it's dead code. When you are debugging a problem, you might comment out some sections of your code. When you're done debugging, take it out.
Bad
# π Don't do this!
def add_to_shopping_list(item):
# print('Shopping list before:', *shoppingList, sep='\n- ')
# print(f"Adding item", item)
shopping_list.add(item)
# print('hopping list after:', *shoppingList, sep='\n- ')
Good
def add_to_shopping_list(item):
shopping_list.add(item)
Saving old versions with Gitβ
You might be worried about "losing" some experimental code that you want to "save" by commenting it out. However, this can cause confusion about which bits of code still work.
If you want to save some code, remember that you can commit it using Git. It will then be saved it forever. If you decide to remove the code later you can delete it and make another commit. And if you want it back again, you can always look at the deleted code in the git history.
Don't leave unused variablesβ
As you write code, you may make changes to the variables that you are using. You may rename some variables, make some new variables or change how the variables are used. This may leave some variables that are unused.
def order_taxi(pick_up_time):
driver_name = get_driver_name();
customer_name = get_customer_name(); # π Don't do this!
print(f"{driverName} will pick you up at ${pickUpTime}`;
}
In this example, the customerName
variable isn't used anywhere.
You should remove any variables that are unused. This is because if you (or someone else) is reading your code, it can be confusing if you see a variable and then find out later that it isn't used. It could make you think that there's a bug, because the variable must have been put there for a reason!
β Don't store secrets in codeβ
Added to the guide on 16 Sept, 2022
When you are writing code, you should never store any secrets in your code. This includes passwords, API keys, and other sensitive information.
Per the 12 Factor App methodology, secrets should be stored in environment variables.
to achieve this, you can use the os
module to get the values of environment variables. For example, if you have an environment variable called API_KEY
, you can get the value of it using os.getenv['API_KEY']
.
import os
API_KEY = os.getenv("API_KEY")
Another way to do this is to use a .env
file. This is a file that contains environment variables. You can use the python-dotenv
module to load the environment variables from the .env
file.
import os
from dotenv import load_dotenv
load_dotenv(override=True)
API_KEY = os.getenv("API_KEY")
and remember to add the .env
file to your .gitignore
file so that it doesn't get committed to git.