This one is almost a philosophical question: is it bad to access and/or set slots of S4 objects directly using @
?
I have always been told it was bad practic
As developer of a S4 class, my opinion is:
If you read slots with @, you do that at your own risk (like pretty much everything you do in R - see below for some famous examples). That being said, the slots of an S4 class are actually part of the documented interface.
The main advantages of access via @
I see is speed:
> microbenchmark (accessor = wl (chondro), direct = chondro@wavelength)
Unit: nanoseconds
expr min lq median uq max
1 accessor 333431 341289.5 346784.5 366737.5 654219
2 direct 165 212.5 395.0 520.0 1440
(the accessor function does valitidy checking in addition to returning the @wavelength
slot which causes the difference. I'd expect every decent public accessor function to ensure validity)
I even recommend using read access to the slots of my class in time-critical situations (e.g. if lots of subsets of the same object are accessed, it may be worth while to skip checking the validity of an unchanged object every time), and in the code of my package I predominantly read the slots directly, ensuring validity at the beginning of functions and at the end of functions where the object could have become invalid. One may argue that the (R) design decision that @<-
does not check validity does cause an enormous overhead in practice because methods working on S4 objects can not rely on the object being valid and thus even methods with purely read access have to do validity checking.
If you think about write access to a slot, you should really know what you are doing. @<-
does not do any validity checking, the official write accessor should do that. And, the write accessor possibly does much more than just update one slot in order to keep the object's state consistent.
So, if you write into a slot, expect to find yourself in hell and do not complain. ;-)
Thinking a bit further along the philosophical line of this: my package is public under GPL. I not only allow you to adapt the code to your need, but I want to encourage you to develop/adapt the code for your needs. Actually it's really easy in R - everything is already there in a normal interactive R session, including access to the slots. Which is quite in a line with design decisions that make R very powerful but allow things like
> T <- FALSE
> `+` <- `-`
> pi <- 3
> pi + 2
[1] 1