Organizing Related Functions

A few times at work lately I’ve found myself doing “the same thing but another way, and in another place too”, i.e. displaying the same icon/text combo in a few places but horizontally here and here, and vertically there.

I had originally added an optional boolean argument as I’ve done in the past in order to return the different but related jsx, I had a realization that that technically does mix business logic with presentation logic.

So after a little noodling around, I came to this idea of name-spacing two or more related functions in an object:

// previously

const displayIconAndText = (data: unknown, isVertical: boolean) => {
    return isVertical ? (
        // vertical version of jsx component that displays icon and text data
    ) : (
        // implied horizontal version of jsx component that displays icon and text data
      )
}
// and now!

const forHorizontalDisplay = () => {
  // horizontal version of jsx component that displays icon and text data 
}

const forVerticalDisplay = () => {
    // vertical version of jsx component that displays icon and text data 
}

const displayIconAndText = {
    forHorizontalDisplay, 
    forVerticalDisplay,
}

So now if the deep midst of some heavy business logic bug, you won’t see this mystery boolean flag:

displayIconAndText(datObject, true)

Instead, you’ll be reading business logic and then see this:

displayIconAndText.forHorizontalDisplay(dataObject)

and if you’re reviewing for other reasons apart from the styling, it’s now much clearer what that function is doing completely apart from that buggy dataObject.

Happy Coding 😎