RConsortium / S7

S7: a new OO system for R
https://rconsortium.github.io/S7
Other
386 stars 32 forks source link

Print method occurs before validation #377

Closed JosiahParry closed 9 months ago

JosiahParry commented 9 months ago

I'm playing around with S7 and abstract classes. I've encountered a scenario where a custom print method is being dispatched before the validation occurs. I think this might be because the validation is lazy? My expectation is that validation would happen before a print method is dispatched.

library(S7)
#> Warning: package 'S7' was built under R version 4.3.1

Enum <- new_class(
  "Enum",
  properties = list(
    Value = class_character,
    Variants = class_character
  ),
  validator = function(self) {
    if (length(self@Value) != 1L) {
      "enum value's are length 1"
    } else if (!(self@Value %in% self@Variants)) {
      print(self)
      "enum value must be one of possible variants"
    }
  }, 
  abstract = TRUE
)

enum_class <- "GridShape"
variants = c("Square", "Hexagon")

GridShape <- new_class(
  enum_class,
  parent = Enum,
  properties = list(
    Value = class_character,
    Variants = new_property(class_character, default = variants)
  )
)

# print method for enums
# since this is an abstract class we get the first class (super)
# to print
print.Enum <- function(x, ...) {
  cat(class(x)[1], "::", x@Value, sep = "")
  invisible(x)
}

GridShape("Square")
#> GridShape::Square
GridShape("sdfs")
#> GridShape::sdfs
#> Error: <GridShape> object is invalid:
#> - enum value must be one of possible variants

Created on 2023-11-10 with reprex v2.0.2

hadley commented 9 months ago

You're calling print in the validator?

JosiahParry commented 9 months ago

Welp! There it is! Lol. Sorry about.. 🤦🏼