Menu
CoddyTech

S4 Validity Contracts

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

C declarations establish storage types but do not enforce arbitrary business invariants; validation must be programmed. R S4 combines formal classes, slots and method signatures with validity functions returning TRUE or diagnostic strings. Construction consults validity. Wrap setValidity in invisible to avoid printing its returned object.

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

setClass("LabelDemo",slots=c(text="character"))
invisible(setValidity("LabelDemo",function(object)if(length(object@text)==1&&nzchar(object@text))TRUE else "text required"))
cat(validObject(new("LabelDemo",text="tea")),"\n",sep="")

S4 validity rules do not automatically validate arbitrary ordinary lists.

challenge icon

Challenge

Easy

Define S4 class Capacity with numeric slot value. Its validity function accepts exactly one finite nonnegative value and otherwise returns the message invalid capacity. Implement make_capacity(n) using new. Adapter returns the slot or invalid when construction raises 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 Capacity.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("Capacity.R")
source("Exercise.R")
stopifnot(is(make_capacity(8),"Capacity"),identical(make_capacity(8)@value,8),inherits(tryCatch(make_capacity(-2),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