🎓 A1Learner
🔍
0 of 27 lessons completed

R S4 Validity

A validity method is a function that checks an S4 object against extra rules. setValidity attaches the method to a class and new runs it when an object is built.

A valid object passes

The rule says the balance must not be negative. A balance of 20 passes, so new builds the wallet and print shows its slots.

setClass("Wallet", slots = c(balance = "numeric", owner = "character"), prototype = list(balance = 0, owner = "Ana"))
v <- setValidity("Wallet", function(object) {
  if (object@balance < 0) {
    return("balance must not be negative")
  }
  return(TRUE)
})
w <- new("Wallet", balance = 20, owner = "Ana")
print(w)
print(w@balance)

Zero passes the rule

The rule only fails values below zero. A balance of 0 passes and the slot reads print on their own.

setClass("Wallet", slots = c(balance = "numeric", owner = "character"), prototype = list(balance = 0, owner = "Ana"))
v <- setValidity("Wallet", function(object) {
  if (object@balance < 0) {
    return("balance must not be negative")
  }
  return(TRUE)
})
w <- new("Wallet", balance = 0, owner = "Bo")
print(w@balance)
print(w@owner)

A negative balance fails

A balance of -5 breaks the rule. new stops and the error carries the message text from the checking function.

setClass("Wallet", slots = c(balance = "numeric", owner = "character"), prototype = list(balance = 0, owner = "Ana"))
v <- setValidity("Wallet", function(object) {
  if (object@balance < 0) {
    return("balance must not be negative")
  }
  return(TRUE)
})
w <- new("Wallet", balance = -5)

Example

setClass("Wallet", slots = c(balance = "numeric", owner = "character"), prototype = list(balance = 0, owner = "Ana"))
v <- setValidity("Wallet", function(object) {
  if (object@balance < 0) {
    return("balance must not be negative")
  }
  return(TRUE)
})
w <- new("Wallet", balance = 55, owner = "Cy")
print(w@balance)
print(w)
w2 <- new("Wallet", balance = 5, owner = "Dee")
print(w2@balance)

Key points

  • setValidity takes a class name and a checking function.
  • The checking function receives the object being built.
  • The function returns TRUE when the object passes the rules.
  • The function returns a message text when the object fails a rule.
  • new runs the validity check as part of building the object.
  • A failed check stops new and the error carries the message text.
  • setValidity returns a class summary, so the call is assigned to a variable to keep the output clean.

In this example, both balances pass the rule because neither is negative. The prints show the balance of 55, the full slot dump for the first wallet and the balance of 5 for the second wallet.

Try it Yourself

Edit the code, then press Run.

Running is simulated · rdrr.io R Snippets

Exercise

What does a validity checking function return when an object fails its rule?