Enhanced Factory (factoryX?)

Reginaldo Junior
3 min readMay 27, 2020

--

Hello folks, I hope you guys are going well. Today I wanna show y’all something I’ve been thinking lately and that may or may not be useful to someone somewhere.

It’s called factoryX, a higher-order function that adds to any factory the ability to recreate itself with different dependencies, let's dive into some examples so you may better understand what I mean.

In the following example factory we have a function that stores a record on the database, emits an event to a queue and log its data using some third-party monitoring tool like datadog.

factory example for storing, logging and event-producing records

That’s a very basic and abstract factory that does a lot of things and even though you wouldn’t use it on a real-world code, we can reason about it a little bit.

The Problem

This implementation has a limitation, if we needed to get a new version of the storeRecord function with different dependencies we would have to provide all its dependencies again, even if we only want to use a different monitoring tool, but keep the same database and queue service.

That may not look like a big deal because here we have only 3 dependencies but what if we had more? maybe 5, 6,7…

Obviously, if your function has that many dependencies it means it’s doing too much so you may wanna take some time to refactor it and break it down into smaller pieces.

But what if we could recreate the storeRecord function passing only the dependencies that have changed, something like:

storeRecord using sentry client instead of datadog

Wouldn’t that be awesome? Well, factoryX does exactly that.

But how? well, take a look at the basic implementation.

factoryX basic implementation

That’s it, simple as that, now we can wrap any factory with our factoryX and use the having method to recreate the initial factory with new dependencies.

The storeRecordFactory needs to be updated to something like:

Despite the fact that we are now storing our factory into a constant, we barely touched the factory implementation.

Conclusion

I hope this may be useful to someone, I didn’t found anything like that anywhere, if you guys know something like this please put it in the comments for me to take a look at.

Something to keep in mind:

As factoryX uses recursivity to recreate the factory, we should avoid creating factories inside loops to prevent stack overflow errors.

Thank y’all, see you soon.

--

--

Reginaldo Junior

I can lose everything, but I'll never lose what I've learned on the path till here