Coding best practices

Revision as of 23:22, 28 July 2021 by P.petrelli (talk | contribs)

There are code standards and conventions available depending on the language you are using and sometimes also conventions adopted for specific collaborative projects. These can be quite complex and out of scope if you are writing a code for your analysis, however there are a few things you can do to make your code much more readable and safer from bugs which are quite simple. In the video linked below, kindly provided by DataTAS, the presenter gives some useful tips which can be applied to any language:

"Reproducible research how to write code that is built to last

It is worth watching the video (the actual presentation is about half of the video ~35 minutes) to understand fully how valuable these tips are and also to get a perspective from someone who went from a science background to a commercial software engineering position.

Below is a list of best practices discussed in the video.

Naming

  • Use descriptive names for variables and functions
  • Use consistent naming across the code
  • Avoid hard-coding values
  • Initialising variables

Code structure

  • Indents
  • ​​​​​​​Comments
  • Use functions to organise your code 
  • ​​​​​​​Don't Repeat Yourself (DRY) code
  • One statement per line
  • Write explicit code
  • Keep your files a reasonable length
  • Clear flow: try to have only one exit point in a function
  • Test important parts of your code  

Style guides