Question: How to handle CFCs and initialization?

So, this is my problem. I have a CFC where you need to call an init on it to set certain values up. So, the logic is:

Make an instance in X.
X.init(“foo”,”goo”)

The problem is - how can I ensure people always call init? The simple yet yucky solution is to let init set a variable called loaded. If you call any other method, a check is made to checkLoaded(), which throws an error if init was never called. This works, but requires me adding hooks to all my methods.

The other possible solution - make the init() method actually return an instance of the CFC itself, so you could do something like this instead:

x = createObject(“component”,”foo”).init(“moo”)

However, if the user doesn’t create the CFC in this manner, all the methods will fail when run.

So, what do you think is best? On one hand, we have a solution that is somewhat idiot-proof. On the otherhand we have a solution that is less “hacky” but more prone to user error.

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Comments