The Paper Trail (Comments)
The Rule: Every time you use AI to write code, write a # comment in plain English above it explaining what you told the AI to do.
Code snippet
# I asked AI to filter for patients with BMI over 30 and count them # [AI CODE BELOW]
Below is an example of non readable code
# What is x? What is 1.05? Why are we subsetting?
f <- function(x, y) {
z <- x[x$a > y, ]
r <- sum(z$b) * 1.05
return(r)
}
res <- f(df, 100)
And here is an example of readable code
library(dplyr)
# Calculate the total revenue for high-value orders including a 5% tax
calculate_total_revenue <- function(order_data, minimum_price_threshold) {
sales_tax_rate <- 1.05
total_revenue <- order_data |>
filter(price > minimum_price_threshold) |>
summarize(total = sum(price)) |>
pull(total)
return(total_revenue * sales_tax_rate)
}
# Usage:
final_report_value <- calculate_total_revenue(current_orders, minimum_price_threshold = 100)
Just by reading through each line a reader should understand what is going on. One does not need to comment every single line, but rather comment whenever something complex is happening on the code line below it. And as always source work which is not yours.