Readable:
A human being can easily understand the purpose of the code and can maintain the code.
Reusable:
Code is written in such a way that it can be reused across multiple contexts with little or no modification required.
Robust:
A computer system is able to cope with errors during execution.
Code is read more often than it is written. — Guido van Rossum (creator of Python)
At some point someone else or our future us will need to understand the code we write today.
Readable: The code clearly communicates its purpose and is descriptive.
You should be able to understand without heavily relying on comments.
Focused: Each function does one thing.
DRY: Don’t Repeat Yourself. Create small snippets that can be used over and over, avoid large functions.
Well-structured: Consistent formatting, avoid spaghetti code
Self-documenting: Structure and naming should be understandable without comments.
Use comments to explain why not what.
Python at its best:
R at its best:
Style Guides can help to stay consistent
| Language | Linters | Formatters |
|---|---|---|
| R | lintr | formatR, styler |
| Python | ruff, pylint | ruff, black |
Function: lintr::lint(filename)
The lintr package in R:
The ruff library in Python:
Function: ruff check --fix path/to/code/to/check.py
Run a linter through your code and identify style issues:
lintrruff checkEdit your code to improve the style compatibility, based on the feedback from your linter.
Run an autoformatter through your code to automatically fix issues instead of simply flagging them:
stylerruff formatIf you find code that is hard to read, or variable names that need adjusting, make a note to work on it. Use #TODO or another consistent label so you can extract these notes later.
Workshop Computational Reproducibility