Writing Human Readable Code¶
Writing clear, well commented, readable and re-usable code benefits not only you but the community (or audience) that you are developing it for. This may be your lab, external collaborators, stakeholders, or you might be writing open source software for global distribution! Whatever scale you work at, readability counts!
Here are a few aspects to consider when making your code easy to read by others.
There is some agreement on the length of the coding lines.
PEP8 suggests a maximum of 79 characters per line and 80 by the R style guide.
This means that the lines can easily fit on a screen, and multiple coding windows can be opened.
It is argued that if your line is any longer than this then your function is too complex and should be separated!
This is the crux of the Tidy method of R programming, which even has a special operator
%>% which passes the previous object to the next function, so fewer characters are required:
recoded_melt_dat <- read_csv('~/files/2019-05-17_dat.csv') %>% recode() %>% melt() #We now have a recoded, melted dataframe called recoded_melt_dat
The R style guide suggests that lines should be separated:
by two spaces
a mixture of tabs and spaces.
Obviously, sometimes the arguments of a function can far expand 80 characters. In this case, it is recommended that the second line be indented to the start of the arguments:
my_variable <- a_really_long_function(data = "2019-05-17_Long_File_Name_2", header = TRUE, verbose = TRUE)
These are of course just guidelines, and you should choose elements that suit your coding style. However, and again, it is important to ensure that you are consistent when collaborating, and can agree on a common style. It could be useful to create a readme file describing your coding style so collaborators or contributors can follow your lead.
…end. …end. …or end.\n¶
If you are sharing text files or working collaboratively on manuals or documents, then there is a lot of controversy surrounding whether to use one or two spaces after a period. When using Markdown, it can be clearer to include a new line after every sentence. This chapter (and most, if not all, of this book) has a new line after every sentence that makes the raw text easier to read, review and solve the spacing issue.