From Peter.Ruckdeschel at uni-bayreuth.de  Wed Nov 19 18:50:36 2003
From: Peter.Ruckdeschel at uni-bayreuth.de (Peter Ruckdeschel)
Date: Wed Nov 19 18:51:29 2003
Subject: [Rd] Was: setValidity and "initialize" method conflict ? [in R-help]
Message-ID: <3FBBAD6C.2000803@uni-bayreuth.de>

Hello,

Thomas Stabla (statho3@web.de) has already sent this
question to R-help,  Wed, 12 Nov 2003 21:21:31 +0100,
but we are not sure whether we should better post this
mail to this audience than to R-help:

---------------------------------------------------------------------

We are using S4-classes and want to force a validity check
when an object is created.

How can this be done, when an "initalize" method has been
set?

-------------------------------------------------------------------------
We got problems when using our own "initalize" method:

platform i686-pc-linux-gnu
arch     i686
os       linux-gnu
system   i686, linux-gnu
status
major    1
minor    7.1
year     2003
month    06
day      16
language R

[But the same behaviour ouccured under R 1.8.0]

Following piece of code works fine, just like we expected it to

-------------------------------------------------------------------------
 >setClass("Foo", representation(woo = "numeric"))
[1] "Foo"
 >validFooObject <- function(object) {
+   if(object@woo > 0) return(TRUE)
+   else return("warning: negative value for woo")}

 >setValidity("Foo", validFooObject)
[1] "Foo"

 >new("Foo", woo = 1) # all is fine
An object of class "Foo"
Slot "woo":
[1] 1

 >new("Foo", woo = -1) # ok, negative value
Error in validObject(.Object) : Invalid "Foo" object: warning: negative
value for woo

-------------------------------------------------------------------------

Now, if i define a initialize method for Foo, things change (R had
been restarted)

-------------------------------------------------------------------------
 >setClass("Foo", representation(woo = "numeric"))
[1] "Foo"

 >validFooObject <- function(object) {
+   if(object@woo > 0) return(TRUE)
+   else return("warning: negative value for woo")}

 >setValidity("Foo", validFooObject)
[1] "Foo"

 >setMethod("initialize", "Foo", function(.Object, woo){
+   .Object@woo = woo
+   .Object})
[1] "initialize"

 >new("Foo", woo = 1) # all is fine
An object of class "Foo"
Slot "woo":
[1] 1

 >new("Foo", woo = -1) # ! no warning, object created!
An object of class "Foo"
Slot "woo":
[1] -1
-------------------------------------------------------------------------

Thank you for your attention.
-- 

Peter Ruckdeschel


[Rd] Was: setValidity and "initialize" method conflict ? [in R-help]
Peter Ruckdeschel