Menu
CoddyTech

Validated Constructors

Lesson 33 of 48 in Coddy's R for C Developers course.

C factory functions can validate inputs before returning initialized records or a failure status. R S3 constructors can call stop before attaching a class or returning a value. An S3 tag alone has no S4-style formal validity check. Every public constructor should establish its invariant instead of relying on later methods to repair malformed data.

C

#include <stdio.h>
struct Score{int points;};
static int score_new(int points,struct Score *out){if(points<0)return 0;out->points=points;return 1;}

int main(void) {
struct Score score; if(score_new(3,&score))printf("%d\n",score.points);
return 0;
}

R

new_window <- function(side) { if(side<=0)stop("side");structure(list(side=side),class="window") }
area <- function(x) x$side*x$side
cat(area(new_window(4)),"\n",sep="")

Validate the representation before returning the constructed S3 object.

challenge icon

Challenge

Easy

Implement new_stock(count) for one finite number. Reject negative values with stop; otherwise return class stock with numeric member count. The adapter returns count or invalid for an error.

Keep the declared public API. The visible locked driver checks it directly as well as printing solve(lines). Inputs satisfy the stated contract; all arithmetic is small and finite.

Your code goes in Stock.R and Exercise.R. main.R sources dependencies in order and holds the supplied input/output code; it cannot be edited.

Try it yourself

source("Stock.R")
source("Exercise.R")
stopifnot(inherits(new_stock(8),"stock"),identical(new_stock(8)$count,8),inherits(tryCatch(new_stock(-1),error=identity),"error"))
lines <- suppressWarnings(readLines(file("stdin"), warn=FALSE))
cat(solve(lines), "\n", sep="")
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in R for C Developers

Practice on your own: Online R compiler