| name | testability |
| description | Refactoring patterns for hard-to-test code |
Testability
Philosophy
Code that's hard to test is telling you something about its design. Coverage gaps are opportunities to improve architecture, not problems to silence.
Fix the design, don't silence the messenger.
Refactoring Patterns
1. Extract Pure Logic from I/O
res_t process_config(const char *path) {
char *content = read_file(path);
}
res_t parse_config(const char *content, config_t *out);
res_t load_config(const char *path, config_t *out) {
char *content = read_file(path);
return parse_config(content, out);
}
2. Infallible Functions → void
If a function cannot fail, don't pretend it can:
res_t init_defaults(config_t *c) {
c->timeout = 30;
return OK_RES;
}
void init_defaults(config_t *c) {
c->timeout = 30;
}
3. OOM Checks → Single-Line PANIC
When allocations PANIC on failure, downstream checks become unreachable:
result_t res = allocate_something();
if (is_err(&res)) {
return res;
}
result_t res = allocate_something();
if (is_err(&res)) PANIC("allocation failed");
4. Unreachable Else → PANIC
if (condition_always_true) {
handle();
} else {
return ERR(...);
}
if (condition_always_true) {
handle();
} else {
PANIC("Invariant violated");
}
5. Reduce Conditional Complexity
if (a) {
if (b) {
if (c) { }
}
}
if (!a) return;
if (!b) return;
if (!c) return;
6. Parameterize Behavior
void wait_for_response(void) {
sleep(30);
}
void wait_for_response(int timeout_sec) {
sleep(timeout_sec);
}
7. Wrap Vendor Functions
When vendor functions have inline branches we can't cover:
yyjson_val *root = yyjson_doc_get_root(doc);
if (!root) return ERR(...);
yyjson_val *root = yyjson_doc_get_root_(doc);
if (!root) return ERR(...);
When to Refactor vs Mock
| Situation | Action |
|---|
| Our code is complex | Refactor |
| External library call | Mock via wrapper |
| System call | Mock via wrapper |
Rule: Refactor our code, mock external dependencies.
Related Skills
coverage - Policy (90% requirement)
lcov - Finding specific gaps
mocking - Testing external dependencies