True Laziness Requires a Little Effort
tl;dr
Make reusable code actually reusable by evicting it from your codebase.
I made a nifty npm package called future-state that allows you to subscribe to a Redux store for data that will eventually show up in the state. It’s not really complex, but that’s what is cool about it. It does one little tedious thing cleanly, removing a nuisance. Small, well-tested packages like this are the nuts and bolts of web development.
Let’s see some code.
I was waiting for several values to show up in a Redux state tree. Typically, react-redux handles all the state change notifications I care about, but this was outside Component Land. So I wrote something that returns a Promise that resolves once the values show up.
const getFutureStoreValues = (store, valuePaths) =>
new Promise((resolve) => {
// Subscribe for store changes.
const unsubscribe = store.subscribe(() => {
// When the store changes, we can get the new state.
const state = store.getState()
// Check to see if our values are in it.
const allValues = getAllValues(state, valuePaths)
if (allValues) {
// Clean up and hand off the values.
unsubscribe()
resolve(allValues)
}
})
})
You can see that there’s nothing really complex here. At first, this resided within other initialization code I was using. Once it grew a bit, waiting for multiple values and including safety checks for digging through an object of uncertain shape, it didn’t fit within that other code.
Make it a module.
Instead of just moving it to its own file, I decided to go a step further and make it its own module. The problem it solves is really tangential to the app. It’s generic enough and seems like it could be useful to others, so why not publish it to npm? Hell, even if no one else wants to use it, it’s still a good pattern for code resuse for my own projects.
Even if you don’t reuse code from people outside of your organization, using this kind of module-based approach can help your team work together better and make it possible to reuse code across projects. https://docs.npmjs.com/getting-started/what-is-npm
Making it a module and importing it into the main project really helps to seal it up, too. It’s a black box now, no need to look inside. The main project can continue to be focused on business logic and outsource lower level implementations.
Sometimes Invented Here Syndrome?
On the Not Invented Here/Never Invented Here spectrum, I fall closer to the “roll your own” end. That’s because I love creating and I tolerate configuring. By packaging code that’s grown into its own, I can save myself work in the future, keep my concerns narrow, and look a little less like a N(ot)IH nutbag.