Can a constructor return Nil?


In a plugin, I declare a class. This class has a constructor that creates and initializes a certain number of data structures. Is there a method for returning Nil to Xojo if one of these creations/initializations fails ? Today I’m using a boolean that can be tested in Xojo to find out if the data structures are valid.

If Not myClass.InitOK Then
myClass = Nil

No. You can raise an exception to prevent the constructor to return the object.


And raising different exceptions with messages and codes to know what failed.

Or you could have a factory, a shared method that returns a newly created instance or Nil otherwise.


But a class needs a constructor and the initial problem does not go away. So it would need to implement the constructor with the proper exceptions AND THEN create a factory wrapping it and handling the exceptions to return Nil.

Actually you can make private constructor and a shared method on the class that is the factory.

The way it works with plugins is that Private constructor does not get called. Only Initializer gets called. So basically the Factory shared method on the class can do all the work and return nil.

I use both patterns in my plugins, raising exception or a shared method as factory. Both are valid. Just depends on the case which is more suitable.

Private constructor on the class ensure the Xojo user cannot construct the class with the new operator.

1 Like

Thank you all for your advice. A mix of exceptions and shared methods seems to be the best solution.