Menu
CoddyTech

Validated Constructors

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

Python __init__ can reject invalid starting state. R S3 constructor functions can call stop before attaching a class or returning an object. Unlike S4 formal validity, an S3 class tag does not enforce a schema by itself. Make every public constructor preserve the invariant rather than expecting later methods to repair malformed objects.

Python

class Window:
    def __init__(self, side):
        if side <= 0:
            raise ValueError("side")
        self.side = side
    def area(self):
        return self.side * self.side

print(Window(4).area())

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="")

Attach a class only after validating the intended representation.

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 Python Developers

Practice on your own: Online R compiler