I have a few custom classes that require other dependency classes to work. Is there a way when you construct an object (in the constructor method) to check on these dependencies and exit the construct prematurely as nil as opposed to constructing it upon this validation… or, is once an object is constructed, there’s no way to make it nil within itself? This is probably a common-sense question, but I’m asking anyway. I’ve been trying to get this to work; however, it’s not.
This not possible. When the constructor is called, the object already exists.
A possible work around would be to use some kind of factory pattern that returns nil if the required conditions are not met.
Thanks guys, I thought so. Going to check if references of required dependencies are nil BEFORE constructing the new object then.
@Eric, you could make a Private Constructor (so it can’t be called) and then use a Shared Method on that class to create them. That method could return Nil if certain conditions couldn’t be met.
Shared Function Create() As MyClass
If ticks > 20000 then
Return New MyClass
You’d call it like this:
Dim MyClass1 as MyClass = MyClass.Create()
myClass1 will be Nil if the conditions are not met.
Constructors are not “object creators” rather they are “initializers”
You can actually call one at any time like any other method to reinitialize the object
Greg and Norman,
Thanks for the feedback. I’ll see what I can come up with… Greg’s idea looks like it could suit what I’m looking for.
whenever you need “return nil if creating one fails” a factory is a decent option because it can call new, catch an exception (if you raise one in the constructor), and return nil as a result