Chapter 16 Style guide
16.1 What is a coding style?
“Good coding style is like using correct punctuation. You can manage without it, but it sure makes things easier to read.” Headley Wickham.
“thus try to make use of it try to follow the style guides you may thin it is kind of useless in the beginning however you will see that it is especially when your functions get more complex very useful to do so i often spent hours to find my own bugs just because my coding style was horrible keep that in mind” Reto, 2019.
16.2 Special characters
- do not use special characters (Umlaute, apostrophes, …)
- neither for object names, nor comments!
- you may have noticed it: object names have to start with a letter, blanks are not allowed
Preferably in English. Especially if you hand over your code to someone else.
16.4 Script file names
Should be meaningful and use the
16.5 Object names
Should be lowercase and meaningful! Use underscores to separate words within a name. If possible use nouns for variables and verbs for functions.
16.6 Spaces: infix operators
Put spaces around all infix operators (
|), around the get operator (
Well written code:
16.7 Spaces: colons
One exception: There is no space around colons (
16.8 Spaces: multiple spaces
Ok to use multiple spaces if it increases readability. E.g.:
More well-structured …
… than this:
16.9 Spaces: brackets
A space before opening round brackets (
() and after closing round brackets
)) except for function calls.
16.10 Spaces: commas
Always use spaces after the comma.
16.11 Opening/closing brackets
Opening curly brackets should never go in a new line, but should always be followed by a new line. Final closing curly brackets should be in a separate line.
Use block-wise indention (RStudio supports you). Suggested by Headley: use two spaces as indent.
For very short statements:
16.13 Explicit return
My personal suggestion: explicitly use the command when returning results from a function!
For short functions or temporary functions:
16.14 Line breaks
Line breaks: lines should not be longer than 80 characters. Use line breaks for long statements.
16.15 Nested indention
Use block-wise indention (RStudio supports you). Use two spaces as indent.
16.16 Object assignment
<- and not
- Start to write comments!
- Again: code is more often read then written,
- comments help to understand code (also your own!).
# ========to separate code blocks.
16.18 All together
Both code chunks do the very same. And both will work. I think there’s nothing to say here!
Very, very bad: