Good practices for coding
A collection of tips and tricks to write better code
Why should you care?
What will happen when you show your work to someone else if you don’t follow a guide style. (From Xkcd: code quality)
Clear naming of variables and functions
- Be explicit in your naming. If you name a variable
my_variable
, don’t name another onemy_var
ormy_var_
. If you name a functionmy_function
, don’t name another onemy_func
ormy_func_
. - Names should be self-explanatory. If you need to add a comment to explain what a variable or a function does, it means that you should change its name. For example,
my_variable
is a bad name, butnumber_of_samples
is a good name.df
,df2
, … are bad names, butraw_data
,ìmputed_data
, … are good names.
Do not repeat yourself
- Write functions to avoid copying and pasting slight variations of the same piece of code in many places
- Use map functions for applying a piece of code iteratively to all the elements of an object
Consistency
- Be consistent in your style. If you start a project, try to follow the style of the project. If you join a project, try to follow the style of the project.
- Be consistent in your naming. If you name a variable
my_variable
, don’t name another onemyVariable
ormyVariable_
. If you name a functionmy_function
, don’t name another onemyFunction
ormyFunction_
. - Be consistent in your formatting. If you use 2 spaces for indentation, don’t use 4 spaces for indentation. If you use 2 spaces for indentation, don’t use tabs for indentation.
All of this will make your code easier to read and understand.
Code Style Guidelines
Consistency in coding style is essential for making the code more readable and understandable by others. Adopting a standard coding style across your team helps avoid confusion and reduces the time spent on code reviews. For each language (Julia, R, and Python), there are widely accepted coding style guidelines:
Tip
There exists tools to help you check your code style and correct the basic mistakes. They are called linters. For example, in Julia, you can use JuliaFormatter.jl, in Python black and in R styler.