πŸ’» Lab 05 – The art of refactoring code

Week 02 – Day 01 - Lab Roadmap (90 min)

Author
Published

17 July 2023

πŸ₯… Objectives

  • Apply the concepts learned in the morning lecture on code refactoring to real-world R scripts.
  • Gain hands-on experience improving code structure and readability.
  • Learn techniques for modularising your R code.
  • Enhance the skills acquired in Lab 04 by refactoring the web scraping code using the concepts from the morning lecture.

βš™οΈ Setup

  1. Open RStudio and create a new R script. Save the script as lab05.R.

πŸ“‹ Lab Tasks

Part 1: Reading someone else’s code

πŸ‘₯ IN PAIRS

  1. Sit in pairs and share your code from Lab 04 (Wikipedia).

    • Ideally, you would sit with someone you haven’t worked with before.
  2. Now, silently read your partner’s script and try to understand what it does. Do you understand what each line of code does? Do you understand the overall purpose of the script?

  3. Now list structural code refactorings that you would suggest and the reasons why you would suggest them. For example, you might suggest that a piece of code be moved into a function so it can be reused later, or you might suggest that a variable be renamed to make it more clear what it represents.

    • Give your colleague a list of suggestions for improving their code. You can write these down on a piece of paper or in a text file.
  4. πŸ—£οΈ CLASSROOM DISCUSSION: Your instructor will summarise the most common issues that were identified in everyone’s code and will discuss the suggested solutions.

Part 2: Refactoring your code

  1. Read the feedback from your colleague and apply it to your code, save the new code on the lab05.R script. If you have any questions, ask your instructor.
Tip

You can test your refactored code by running lab04.R and lab05.R in the same R session. This would let you compare the output of the two scripts and make sure that the refactored code produces the same results as the original code.

  1. Now, apply lintr to your refactored code. Are there any new issues that you didn’t notice before? If so, fix them.