tdd-bdd: add R-flavored deep-modules, interface-design, mocking, refactoring refs

This commit is contained in:
Łukasz Boryń 2026-05-28 22:35:34 +02:00
parent cabfcc019f
commit 5526eb203c
5 changed files with 362 additions and 4 deletions

View File

@ -12,10 +12,16 @@ description: Drive implementation with a strict red-green-refactor loop where ev
- Behavior is observable from outside the unit (input → output, state - Behavior is observable from outside the unit (input → output, state
change, side effect) — pure refactors are out of scope. change, side effect) — pure refactors are out of scope.
## Language references ## Language references — R
- **R** (testthat ed. 3+, `box::use`, `describe`/`it`): see
[tests-r.md](tests-r.md) for paired good/bad examples covering fixtures, Testthat ed. 3+, `box::use`, `describe`/`it`.
typed errors, render-vs-data, and precondition encoding.
- [tests-r.md](tests-r.md) — paired good/bad examples + characteristics.
- [interface-design-r.md](interface-design-r.md) — DI, pure functions,
minimal surface. *Consult before step 1.*
- [deep-modules-r.md](deep-modules-r.md) — small interface, large impl.
- [mocking-r.md](mocking-r.md) — boundaries only. *Consult before `mockery::stub` / `local_mocked_bindings`.*
- [refactoring-r.md](refactoring-r.md) — what to look for in step 3.
## Process ## Process

View File

@ -0,0 +1,77 @@
# Deep modules in R
Adapted from John Ousterhout, *A Philosophy of Software Design*. A **deep
module** has a small interface and a large implementation. A **shallow
module** has a large interface and almost no implementation — every helper
becomes part of the public contract, which makes the code hard to reason
about *and* hard to test.
In R you control the interface with `box::use` (or NAMESPACE/`@export` in a
package). The interface is whatever a caller writes after `box::use(...)`.
## Shallow — bad
```r
# R/modb/client.R — exports eight thin helpers
box::export(
build_url, build_headers, parse_token, refresh_token,
page_request, paged_collect, validate_dataset_id, query_dataset
)
```
A caller writes:
```r
box::use(R/modb/client[
build_url, build_headers, parse_token, refresh_token,
page_request, paged_collect, validate_dataset_id, query_dataset
])
tok <- refresh_token(parse_token(Sys.getenv("MODB_TOKEN")))
url <- build_url("DS001")
hdr <- build_headers(tok)
rows <- paged_collect(page_request(url, hdr))
```
Every refactor that splits, renames, or merges a helper breaks every caller
and every test. The tests reach into internals because the internals *are*
the interface.
## Deep — good
```r
# R/modb/client.R — one exported entry point, everything else internal
box::export(query_dataset)
```
A caller writes:
```r
box::use(R/modb/client[query_dataset])
rows <- query_dataset("DS001")
```
`query_dataset()` handles tokens, paging, retries, and validation
internally. Tests target the contract ("returns a tibble of expected rows
for DS001"; "raises `modb_auth_error` on bad token"). Internal helpers can
be renamed or replaced freely.
## Design questions before exporting
For every name you are about to `box::export()` or `@export`:
1. **Does a caller need this?** If only other internals call it, keep it
unexported.
2. **Could two of these collapse?** `build_url` + `build_headers` may want
to become an internal `prepare_request()`.
3. **Could a parameter swallow a helper?** A `paginate = TRUE` argument on
`query_dataset()` can remove `page_request` + `paged_collect` from the
surface.
4. **Is this a leaky abstraction?** Returning a `httr2::request` object
forces every caller (and test) to know `httr2`. Return a tibble or a
typed result instead.
## Heuristic
If the count of exports from a module changes every PR, the module is
shallow. Deep modules export one or two names and stay stable for months.

View File

@ -0,0 +1,75 @@
# Interface design for testability (R)
Three rules. Apply them before writing the test, not after.
## 1. Dependency injection — pass clients, don't construct them
Functions that build their own dependencies are hard to test because the
test has to monkey-patch the constructor.
```r
# BAD — constructs the client internally
process_order <- function(order) {
client <- get_modb_client(Sys.getenv("MODB_CRED")) # hidden global!
client$charge(order$total)
}
```
```r
# GOOD — client is a parameter
process_order <- function(order, client) {
client$charge(order$total)
}
```
The test passes a stub list `list(charge = function(x) list(status = "ok"))`
instead of mocking `get_modb_client` and `Sys.getenv`.
R-specific: default arguments are the idiomatic seam.
```r
process_order <- function(order, client = get_modb_client()) { ... }
```
Production code uses the default; tests pass an explicit stub.
## 2. Pure functions — return, don't mutate
A function that returns its result is testable with one `expect_equal`.
A function that writes to disk, modifies `options()`, or assigns into the
global env needs setup, teardown, and a side-channel assertion.
```r
# BAD — mutates state
reduce_expr <- function(expr_df) {
expr_df$total <<- expr_df$total * 0.9 # global mutation
invisible(NULL)
}
```
```r
# GOOD — returns the new expr data frame
reduce_expr <- function(expr_df) {
expr_df$total <- expr_df$total * 0.9
expr_df
}
```
For pipelines, return a tibble (or `data.table`) and let the caller decide
where it goes. `targets` factors this naturally: each target is a pure
function of its upstream targets.
## 3. Minimal interface complexity
Each parameter is a multiplier on the number of test cases. Each method on
an S3 object is something a test must consider. Shrink the surface:
- Fold orthogonal arguments into one structured input
(`opts = list(retries = 3, timeout = 10)` beats six positional args).
- Use S3 generics with one dispatch path instead of `if (is.character(x))
... else if (is.numeric(x)) ...` inside the function.
- Default everything that has an obvious default; require only what varies.
The single test: *can a new caller use this function correctly without
reading its body?* If no, the interface is too complex regardless of how
clever the implementation is.

View File

@ -0,0 +1,88 @@
# Mocking in R
**Mock at system boundaries. Never mock your own code.**
## Boundaries you may mock
- HTTP / REST APIs — `httptest2`, `webmockr`, or `httr2::with_mocked_responses()`.
- Databases — prefer a real test DB (`RSQLite::SQLite()` in-memory) over a
mock. Mock only when the schema is irrelevant to the test.
- Time — `withr::local_envvar(TZ = "UTC")`, `lubridate::with_tz()`, or
inject a `now = Sys.time` parameter.
- Randomness — `withr::local_seed(42)`, or inject `rng = runif`.
- File system — `withr::local_tempdir()`, `fs::path_temp()`. Real temp
files are usually cheaper than mocks.
## Things you must NOT mock
- Your own `box` modules or package exports.
- Internal collaborators (functions called by the function under test).
- S3 / S4 methods you defined.
- Anything you control and could refactor.
If a test feels like it needs to stub an internal helper, that is a signal
your function under test is doing two things. Split it.
## Design for mockability at the boundary
### Dependency injection over hardcoded constructors
```r
# Easy to mock — pass the client in
process_payment <- function(order, payment_client) {
payment_client$charge(order$total)
}
# Hard to mock — constructs the client internally
process_payment <- function(order) {
client <- StripeClient$new(Sys.getenv("STRIPE_KEY"))
client$charge(order$total)
}
```
In tests:
```r
fake_client <- list(charge = function(amount) list(status = "ok", id = "tx_1"))
expect_equal(process_payment(order, fake_client)$status, "ok")
```
### SDK-style wrappers over a generic `do_request()`
```r
# GOOD — each function has one job and one mock shape
modb <- list(
get_dataset = function(id) httr2::request(...) |> httr2::req_perform(),
list_datasets = function() ...,
query_expression = function(dataset_id, gene_ids) ...
)
```
```r
# BAD — every test mock needs conditional logic
modb <- list(
call = function(endpoint, params) httr2::request(endpoint) |> ...
)
# tests now have to encode "if endpoint == '/datasets' return ..."
```
The SDK-style approach lets each test replace exactly one function with a
constant return value. No `switch()` inside the mock, no risk of one test's
expectations bleeding into another.
## R-specific tools, briefly
- `testthat::local_mocked_bindings(fn = function(...) ...)` — replaces a
binding inside the package under test for the scope of one `test_that`.
Use only at the *boundary*: stub `httr2::req_perform`, not your own
`parse_response`.
- `mockery::stub(target, "boundary_fn", value)` — same idea, finer-grained.
Same rule: only stub at the boundary.
- `httptest2::with_mock_dir("fixtures/")` — replay recorded HTTP fixtures.
Best option for integration-style tests against an HTTP service.
## The single-sentence test
*If I refactor the body of the function under test without changing its
public contract, do the mocks in this test still make sense?* If the mocks
target internal helpers, the answer is no, and the test is mis-scoped.

View File

@ -0,0 +1,112 @@
# Refactor candidates (R)
After every tdd-bdd cycle goes green, scan for these. Refactor only with a
green test bar.
## Duplication → extract a function
Three lines that recur in two places: probably noise. Three *similar* lines
in three places, with a shared shape: extract.
```r
# Before — same column rename pattern in three pipelines
df1 |> rename(gene = gene_symbol, expr = expression)
df2 |> rename(gene = gene_symbol, expr = expression)
df3 |> rename(gene = gene_symbol, expr = expression)
```
```r
# After
normalize_cols <- function(df) rename(df, gene = gene_symbol, expr = expression)
```
Resist extracting on first sight — premature abstractions are worse than
duplication.
## Long functions → private helpers, public interface unchanged
A 200-line `query_modb()` can be split into `prepare_request()`,
`fetch_pages()`, `parse_response()` — *kept inside the same `box` module
without `box::export()`*. Tests still target `query_modb()`. The helpers
are an internal convenience, not part of the contract.
```r
# R/modb/client.R
box::export(query_modb) # only this is public
query_modb <- function(id) prepare_request(id) |> fetch_pages() |> parse_response()
prepare_request <- function(id) { ... }
fetch_pages <- function(req) { ... }
parse_response <- function(raw) { ... }
```
## Shallow modules → combine or deepen
Two modules that always travel together, each exporting one thin function?
Merge them. A module that exports eight helpers users always call in the
same order? Deepen — collapse them behind one entry point. (See
`deep-modules-r.md`.)
## Feature envy → move logic to where the data lives
A function in `R/plot/plot_bxp.R` that does heavy reshaping of a
`modb_result` tibble probably belongs in `R/modb/client.R` (or wherever
`modb_result` is constructed). The test of `plot_bxp` then becomes about
plotting, not about reshape.
```r
# Before — plot module reaches into modb internals
build_bxp_plot <- function(modb_raw) {
df <- modb_raw$data |> filter(...) |> pivot_longer(...) |> rename(...)
ggplot(df, aes(...)) + geom_point()
}
```
```r
# After — modb module owns its shape
# R/modb/client.R
as_long_expr <- function(modb_raw) modb_raw$data |> filter(...) |> pivot_longer(...)
# R/plot/plot_bxp.R
build_bxp_plot <- function(modb_raw) {
ggplot(as_long_expr(modb_raw), aes(...)) + geom_point()
}
```
## Primitive obsession → S3 value objects
Passing `dataset_id = "DS001"`, `genes = c("ENSG1","ENSG2")`, `cohort =
"PRODUCTION"` everywhere? Wrap them in a constructor + validator:
```r
new_query <- function(dataset_id, genes, cohort = "PRODUCTION") {
stopifnot(is.character(dataset_id), length(dataset_id) == 1L)
structure(
list(dataset_id = dataset_id, genes = genes, cohort = cohort),
class = "modb_query"
)
}
validate_query <- function(q) { ... ; q }
```
Now `query_modb()` takes one `modb_query`, every test builds one with
`new_query(...)`, and validation lives in one place.
## Existing code the new code reveals as problematic
The most valuable refactor after a TDD cycle is sometimes *not* in the code
you just wrote. New tests often expose nearby code that is untested,
implicit, or duplicated. Flag it; don't necessarily fix it in the same
commit, but capture the finding so it isn't forgotten.
## `targets` pipelines
Refactor target definitions to keep transforms pure: each `tar_target` is
a function of upstream targets, no side effects. If a target writes a file
out-of-band, that file is invisible to `targets`' invalidation and your
tests can't reason about it. Return the data; let `targets` cache it.
## Never refactor while red
If the suite is red, fix the test or fix the code — do not "tidy while
fixing". Two changes mixed together are two regressions waiting to happen.