Validated Constructors
Lesson 33 of 48 in Coddy's R for Java Developers course.
Java constructors may throw to reject invalid starting state. R S3 constructor functions can call stop before returning a tagged value. An S3 class attribute does not enforce S4 formal validity automatically. Validate inputs at every public constructor boundary rather than expecting methods to repair malformed objects.
Java
import java.util.*;
public class Main {
static class Score{final int value;Score(int value){if(value<0)throw new IllegalArgumentException("negative");this.value=value;}}
public static void main(String[] args){
Score score=new Score(3);System.out.println(score.value);
}
}
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
EasyImplement 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="")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in R for Java Developers
1Files and Atomic Values
Run the R FilesText and OutputAtomic VectorsDivision and ModuloNULL and Missing ValuesRecap: Parcel Charge7Objects and Invariants
S3 Object ConstructionValidated ConstructorsS4 Classes and MethodsEnvironment IdentityClosure EncapsulationRecap: Running Peak2Logic 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