9 Software development concepts

9.1 Good coding practices

9.1.1 Script structure

  • Use comments to create sections.
  • Load all required packages at the very beginning.
  • Write all function definitions after package loading section or create a standalone file for your functions and call it in the main code.

9.1.2 Functions

Identify functions capitalizing the first letter of each word

# Good
DoNothing <- function() {
  return(invisible(NULL))
}

# Bad
donothing <- function() {
  return(invisible(NULL))
}

Use explicit returns

# Good
AddValues <- function(x, y) {
  return(x + y)
}

# Bad
AddValues <- function(x, y) {
  x + y
}

Define what the functions does, the input parameters, and output using comments inside the function

AddValues <- function(x, y) {
  
  # Description: Function to add to numeric variables
  # Input
  # x = numeric
  # y = numeric 
  # Output: numeric
  
  return(x + y)
}

Testing and documenting

  • Use formal documentation for functions whenever you are writing more complicated projects. This documentation is written in separate .Rd files,and it turns into the documentation printed in the help files.
  • The roxygen2 package allows R coders to write documentation alongside the function code and then process it into the appropriate .Rd files.
  • Formal automated tests can be written using the testthat package.

9.1.3 External packages

  • Packages are essentially bundles of functions with formal documentation. Loading your own functions through source("functions.R") is similar to loading someone else’s using library("package")

  • As a general rule, only load a package using library() if you are going to use more than two functions from if.

  • Use the name space when calling an external function. Not doing it can cause clashes when two packages have a function with the same name.

# Good
purrr::map()

# Bad
map()

9.2 Debugging and troubleshooting

General advice:

  • Create a minimal reproducible example of your error.
  • Whenever you see an error copy the full message and paste it in the search bar on your web browser. There is a lot of support out there, and most likely someone came across that same error before.