S4 Validity Contracts
Lesson 40 of 48 in Coddy's R for Python Developers course.
Python protocols can describe structural interfaces to a type checker. R S4 uses declared class definitions, slots and generic method signatures rather than Kotlin-style interfaces or Python duck-typing annotations. A validity function returns TRUE or diagnostic strings and is consulted during construction. Wrap setValidity in invisible to avoid printing its return value.
Python
class Positive:
def __init__(self, n):
if n <= 0:
raise ValueError("positive required")
self.n = n
print(Positive(3).n > 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="")Do not describe S4 validity as automatic validation of arbitrary ordinary lists.
Challenge
EasyDefine 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="")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in R for Python Developers
1Files and Atomic Values
Run the R FilesText and OutputAtomic VectorsDivision and ModuloNULL and Missing ValuesRecap: Parcel Charge2Logic and Iteration
Comparisons and RecyclingScalar ConditionsNamed AlternativesSafe Index SequencesBreak and NextRecap: Fare Bands5Functions and Closures
Functions and ReturnsDefaults and PromisesDots ArgumentsClosures and StateRecap: Discount Total8Collaboration and Contracts
Function CollaborationS3 Inheritance OrderS4 Validity ContractsIdentity and AttributesRecap: Grouped Counts3Collections and Ownership
Vector SubsettingHeterogeneous ListsNamed LookupValues and EnvironmentsRecap: Unique StockPractice on your own: Online R compiler