Welcome | 10 min |
Introduction to Code Readability | 15 min |
Linters & Formatters in R & Python | 15 min |
Exercises or Work on your own code | 60 min |
Wrap-up | 10 min |
Drinks! |
A programming style guide consists of rules or guidelines on writing code. These can be seen as conventions or best practices for the community.
Following a style guide will make your code more consistent and readable, both for you and anyone who will interact with your code. It also reduces the chances of errors.
Guidance of strategic use of whitespace and new lines:
Compare:
this <- function(arg1,arg2) res<-arg1*arg2;return(res)
hurts <- mean(c(this(3,4),this(3,1),this(9,9))); print(hurts)
this <- function(arg1,arg2){
res <- arg1 * arg2
return(res)
}
hurts <- mean(
c(
this(3,4),
this(3,1),
this(9,9)
)
)
print(hurts)
The second chunk is longer, but more modular and readable.
Guidance on descriptive naming of functions and variables
Compare:
In the second chunk, we start functions with a verb and make variable names just long enough to be meaningful
Most programming languages have style guides and these are followed by the community or enforced within organizations.
Python: PEP-8
There are tools available to help you with this! You can use a linter and (auto)formatter while coding!
A linter is a static code analysis tool.
It will browse your code and flag/report issues (style, errors, bugs) as output. Then it’s up to the programmer to go through the list and fix the issues.
The lintr package in R:
The lintr package in R:
While linters provide a report of issues, (auto)formatters will browse the code and correct issues automatically/directly.
The corrections will depend on the rules encoded within the package/library.
The styler package in R:
Try linting and formatting your own code!
Don’t have your own code? You can use our exercise files:
Replace bad.R
with the relevant script name.
Make sure you’re in the same working directory as the script!
Replace ‘pep8.py’ with the relevant script name if needed.
Make sure you’re in the same working directory as the script!