How to not instantiate a class if the arguments passed to the constructor are wrong

  1. 9 weeks ago

    Hello,

    I hope this is not a duplicate. I searched here and there but I couldn't find an answer. I have a custom class and the constructor demands a certain type of object to be passed to it. I can easily check within the constructor if the object is valid (eg != Nil, etc...) and at the end of these checks I would like to have an option to throw an exception and avoid the object creation. Is throwing an exception the answer? Is there any other better way?

    Thank you in advance for your support
    Fabio

    if the arguments are invalid.... then have the class return itself as nil (or some detectable value), and have the code that requested the class deal with it.. not the class itself... since the class can't do anything if it doesn't exist....

  2. Dave S

    Oct 10 Answer San Diego, California USA

    if the arguments are invalid.... then have the class return itself as nil (or some detectable value), and have the code that requested the class deal with it.. not the class itself... since the class can't do anything if it doesn't exist....

  3. Good point. Thank you Dave. That should do. As soon as I fix enough to be able to compile I try it

  4. Tim H

    Oct 10 Pre-Release Testers Portland, OR USA

    I think you're talking about a factory method, not a constructor. By the time you get to the constructor, the object is already created. Think of Constructor as more of an Initializer.

  5. Javier M

    Oct 11 Pre-Release Testers, Xojo Pro AprendeXojo - Europe, Spain

    May be a solution setting the constructor as private and providing, thus, a Method of convenience for instantiation that checks if arguments are valid?

  6. jim m

    Oct 11 Pre-Release Testers Phoenix, Arizona

    For a factory method, add a shared method to the class.
    Something like NewMyClass( args ) as MyClass. If args are invalid, return nil.
    (Just wanted to help clarify the above comments)

or Sign Up to reply!