Micro-pattern: IIFE and Return-Early
What are those and how can we utilize them?
Immediately Invoked Function Expression (IIFE)
I remember back then I used think of this as a “wrapper” of my JQuery code and go on with my life without trying to find out what it’s actually doing. So let’s deconstruct this code together.
As its name, this wrapper is actually just a function that is immediately executed. You can see the function is declared anonymously (without a name) inside the first bracket, then immediately executed with
jQuery as its parameter (converted to
$ inside the function body). As a side note, the function is also a closure, meaning that it can have access to all the variables of its parent (the one that declare it).
Really, it’s just a bunch of shortcut to achieve this same code:
So why do we want to use it then?
I myself also don’t quite understand why I want to use this pattern instead of the more readable counterpart, but then I realize I can do things like this:
And perhaps my most used use case for this pattern is to quickly create an async task inside any scope:
As you can see, it’s kind of useful as a one-shot logical block. I find it useful where I need to do some logic that is quite short and specific. If I instead write a utility function for this, I found it might distract the reader by forcing them to context switch (to a distant function or maybe even another “utils” file). I also need to pass in the parameters and add more things to remember while context switching. With IIFE, the reader can just read the code naturally from top to bottom.
See? It’s quite useful for a short, concise, specific logic, right? Later if turns out it needs to be used anywhere else we can always just take it out and refactor it as separate function (and if needed, pass any parent variables as parameters).
a fail-fast system is one which immediately reports at its interface any condition that is likely to indicate a failure. (Wikipedia)
While this is a pretty common pattern used in system design context as mentioned by Martin Fowler in Fail Fast, I found this can also be derived to a good micro-pattern to use anytime. My explanation for this is simply: return/throw immediately when something may go wrong so we can always follow the happy path.
Imagine we have something like this (exaggerated example):
Wouldn’t it be easier to digest if instead we return early on any possible error? As a bonus, we also get lesser nesting, it’s easier to see the edge cases, and the code flows in one direction, making it easier to review.
So that’s it, these two are the micro-patterns that I find are used pretty often, not only by me but also by others. Oh and these two are not mutually exclusive, they can also be used together. Personally I think this pattern can help to make our codes to be easier to reason so it benefits our future selves and also the ones reviewing our codes.
Let me know if you have other micro-patterns you usually use!