π» Lab 05 β The art of refactoring code
Week 02 β Day 01 - Lab Roadmap (90 min)
π₯ 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
- 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
Sit in pairs and share your code from Lab 04 (Wikipedia).
- Ideally, you would sit with someone you havenβt worked with before.
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?
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.
π£οΈ 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
- 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.
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.
- Now, apply
lintr
to your refactored code. Are there any new issues that you didnβt notice before? If so, fix them.