Saturday, May 30, 2015

Common Pitfalls with Immediately Invoked Function Expressions (IIFE)

I am a big fan of John Papa's Pluralsight Courses and his Angular Style Guide. If you have not checked those out definitely worth the Pluralsight subscription by themselves. But today I am going to recommend a change to John's Angular Style Guide particularly the IIFE section and how it works with Visual Studio. I have seen this behavior in Visual Studio 2010, Visual Studio 2013, Visual Studio 2015 RC. So its not particularly new. The examples are with Resharper 9 and Visual Studio 2015 RC.

Figure 1 is a straight copy and paste from John Papa's Angular Style Guide starting at line 2.  Line 1 I added to help out with Visual Studio's intellisense.

Figure 1: Recommendation from John Papa's Style Guide


First the most important change is to the IIFEs definitions. Lines 2 and 13 should pass in angular and Lines 10 and 21 should pass angular in the last pair of parentheses. Doing this remove the squiggles on lines 6 and 17. See Figure 2.

Figure 2: Defining External Dependencies in an IFFE


Second is more of Resharper Default Style Guide definition thing. For .NET Developers I think basing a Style Guide off of what Resharper complains about is a good baseline. Resharper prefers double quotes. Lines 3, 6, 7, 14, 17, 18 lose their green warning squiggles once you change out single quotes for double quotes. See Figure 3,

Figure 3: Switching to Double Quotes
Final class of issues with the recommendation are the blue squiggles on line 7 and 18. I can see the merit John's logic on putting interface before definition. But both Resharper and Visual Studio take issue with defining the functions after their usages. This is perfectly legal as JavaScript does hoisting to the top of a given functional scope. So the logger function and storage function would be hoisted to line 4 and 15 respectively. Is there a way to make Visual Studio and Resharper aware of the hoisting? For me I rather avoid the squiggly and use a file per component convention instead. If you are DRY with your code a component shouldn't grow to such a size your worried the next dev will get lost in the weeds. I think I would recommend Figure 4 unless hoisting is accepted by tooling. Basically you just look at the bottom of the file for your interface right next to where the external dependencies are listed in the IFFE.

Figure 4: Hoisting functions

I am curious to hear anyone's feedback on this. Maybe I am just missing a setting with the hoisting thing. I am aware Resharper allows you to decide between single and double quotes for string literals under Resharper -> Option from the top menu of Visual Studio see Figure 5.

Figure 5: Where you could switch to Apostrophes in Resharper