Coding Principles

Gradient Coders

1. Keep it simple & stupid

Over-complicating code is the bane of all coding issues. In the words of Antoine de Saint-Exupery, “Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.”

2. Keep it DRY (Don’t Repeat Yourself)

Whenever you copy and paste a piece of code - there is almost always an easier solution (e.g. write a function). If you write the same piece of code three times, refactor it into a function. This makes our code much easier to handle and read.

3. Keep it tidy

Since most of our work is done in R we have adopted the style guide created by Hadley Wickham. This makes it easier for all of us to read each other’s code and complete it if necessary. Use naming conventions. Additionally, the styler library will help you keep the code clean and organized.

4. Write comments! Lots of them

How much do you care about your future self? Think about you, reading your code in 6 months. How clear should this code would be? What comments would you like to see? What places might be hard to understand after a certain amount of time? Do your best to comment the code. Write down your thought process first and then the code! Make sure that someone else can follow along with what you’re doing.

5. Review, Refactor & Repurpose

Code is never optimal when written for a single project. Therefore Gradient Coders will always have somebody review written code. Consequently, the code is refactored to optimize it for different scenarios, which allows us to re-purpose the code. Your code is never done on the first try. It needs multiple re-writes once written. Keep going until it’s perfect.

6. Separate Domains: Data, Analysis, Synthesis

Data processing and analysis should be kept as separate as possible. Have one file to process the data to get it into the format you want, and other files corresponding to specific statistical models. If the output from a model is the input into another analysis, keep that distinction clear; don’t just jump in from one model to the next.

7. Test our code for correctness

Functions should be tested. Data pipelines should be tested. Statistical models should be tested. Everything should be tested. The assertr and testthat libraries are good. Use them and provide tests.

8. Keep it reproducible (libraries and partial results)

Pay attention to both the re-usability and reproducibility of the code. Instead of “daisy chaining” scripts, use tools like Drake or Make to orchestrate the dependency structure. Set seeds. Do not use intermediate results unless absolutely necessary. Take into consideration that the code will be run on different machines, probably with different R version or even other version of libraries. Try using renv, Docker or AWS AMI to have the code be distributed with the set of libraries that were used during the code’s preparation.