A place to cache linked articles (think custom and personal wayback machine)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.md 8.7KB

5 yıl önce
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. title: Real-World JavaScript Anti-Patterns (Part Two)
  2. url: http://blog.javascripting.com/2015/01/12/real-world-javascript-anti-patterns-part-two/
  3. hash_url: fe3d245589980bff826bd38b03c12d34
  4. <p>My <a href="http://blog.javascripting.com/2014/11/06/real-world-javascript-anti-patterns/">previous post</a> was mainly about pure JavaScript syntax, callbacks and iterating collections. In this post I would like to focus on usage of a couple of popular third-party libraries: <a href="http://jquery.com/">jQuery</a> and <a href="https://lodash.com/">Lodash</a>. As in part one, I will use present JavaScript snippets encountered during real code reviews and suggest how they could be improved. I'm bending the rules a bit and will also present some of my favorite lesser known features of these libraries, even if it isn't strictly an anti-pattern not to use them.</p>
  5. <h4 id="jquery">jQuery</h4>
  6. <p>Let’s start with good old jQuery. Although most web developers are well-acquainted with this library, you can still find code like the following:</p>
  7. <pre><code class="language-javascript">if (limited) {
  8. $('body').addClass('height-limited');
  9. } else {
  10. $('body').removeClass('height-limited');
  11. }
  12. </code></pre>
  13. <p>The authors of jQuery knew about this common case and they <a href="https://github.com/jquery/jquery/blob/a3779bc3254159f5a99e8204e69a0f0b9e191f6f/src/attributes/classes.js#L101">wrote the <code>if</code> statement for us</a>. So we can change this to a one-liner: </p>
  14. <pre><code class="language-javascript">$('body').toggleClass('height-limited', limited);
  15. </code></pre>
  16. <p>Now consider a similar pattern with unnecessary condition check (not related exclusively to jQuery). Imagine that we need to handle focus changes of a specific element:</p>
  17. <pre><code class="language-javascript">function handler(e) {
  18. if (e.type == 'blur') { … }
  19. if (e.type == 'focus') { … }
  20. }
  21. $(el).blur(handler);
  22. $(el).focus(handler);
  23. </code></pre>
  24. <p>Clearly it would be better to have separate handlers for <code>blur</code> and <code>focus</code> and get rid of the conditional checks in the handler. You might protest that no one would write something so obviously inelegant, but in reality code along these lines shows up all the time, camouflaged into various more sophisticated forms (e.g. code flow is already branched by some condition, but later all the branches leads to single “bottle-neck” function). <strong>Keep your handlers small and specific</strong> and you won't have to use redundant conditional checks.</p>
  25. <p>Nowadays, with high-level frameworks like React/Ember/Angular, direct class and event manipulation is on its way out. But jQuery is still used this way, whether on standalone sites or in conjunction with another framework (e.g. inside an Angular directive).</p>
  26. <p>For example, we might have a component that needs to run some code on window resize:</p>
  27. <pre><code class="language-javascript">$(window).on('resize', resizeHandler);
  28. </code></pre>
  29. <p>In a single page application, the component is mounted and unmounted many times over the application lifecycle. If each component initialization attaches the resize handler then we must be sure to detact it when the component is destroyed. It is easy to forget this though, resulting in an ever growing number of obsolete handlers. This in turn leads to memory leaks and performance issues. These mistakes can go unnoticed for a long time since they might be invisible on your mighty 16GB RAM developer machine but cause serious trouble on a normal user’s five year old laptop. (And this is not just speculation as this section was motivated by mainly painful hours tracking down exactly this type of problem.)</p>
  30. <p>We could deal with this by keeping track of every handler we attach in every component, but this is tedious and error-prone. Instead we can use <strong>a handy but often neglected JQuery feature: event namespaces</strong>.</p>
  31. <pre><code class="language-javascript">$(window).on('resize.mycomponent', resizeHandler);
  32. </code></pre>
  33. <p>You can specify a namespace for an event by appending it with a period to the event type when adding it, as in the above example. All namespaced events can then be detached at once:</p>
  34. <pre><code class="language-javascript">$(window).off('.mycomponent');
  35. </code></pre>
  36. <p>You still need to remember to call <code>off</code>, but you don’t need to keep track of all the events you have attached. This also makes refactoring safer since we no longer risk changing the attaching code but forgetting to add or update the corresponding detaching code. In fact, if you have a lot of similar components, you can derive a namespace from its name and have the base implementation deal with cleaning up, so the actual components don't have to worry about this at all.</p>
  37. <h4 id="lodash">Lodash</h4>
  38. <p>Personally I find Lodash to be an essential part of almost every JavaScript project. I see its main purpose as fixing annoying JavaScript quirks (insert your favorite JavaScript bashing joke here) and adding missing collection functions that should really have been present in the language itself (and no doubt, one day, will be).</p>
  39. <p>I am guessing that many developers familiar with Lodash use it solely in this way. This is a pity. Lodash does a great job of making up for JavaScript's lacks, but <strong>it also contains many less well-known but equally handy functions</strong>.</p>
  40. <p>Everybody knows <a href="https://lodash.com/docs#forEach"><code>_.forEach()</code></a>, and most developers are familiar with <a href="https://lodash.com/docs#values"><code>_.values()</code></a>, <a href="https://lodash.com/docs#groupBy"><code>_.groupBy()</code></a> or <a href="https://lodash.com/docs#pluck"><code>_pluck()</code></a>. But do you know about <a href="https://lodash.com/docs#debounce"><code>_.debounce()</code></a>? I must admit I implemented it myself several times on several projects before noticing it. The same goes for <a href="https://lodash.com/docs#memoize"><code>_.memoize()</code></a>.</p>
  41. <p>Another functions are utilities that just makes your code a bit nicer to read. <br/>
  42. <a href="https://lodash.com/docs#isUndefined"><code>_.isUndefined(x)</code></a> is definitely better than <code>typeof(x) !== "undefined"</code>.
  43. <a href="https://lodash.com/docs#isNaN"><code>_.isNaN(x)</code></a> is clear to everyone, but <code>x != x</code> (which is the accepted pure JavaScript way to check for <code>NaN</code>) will blow your mind if you are not familiar with it.
  44. I would rather write <a href="https://lodash.com/docs#clone"><code>_.clone(arr)</code></a> then <code>arr.slice()</code>, even though the latter is idiomatic and experienced JavaScript developers will have no trouble understanding it.</p>
  45. <p>The last function I want to mention is <a href="https://lodash.com/docs#template"><code>_.template()</code></a> Of course, there are zillions of templating libraries, but this one can be used with no additional overhead if you already have Lodash in your project. And for many purposes <code>_.template()</code> is good enough. You probably won't use it for creating page markup, but in many cases you can write more elegant code by taking advantage of it. For example, you might want to support placeholders in your email sending function:</p>
  46. <pre><code class="language-javascript">var order = { id: 5774, title: 'Sweet lemonade' };
  47. var email = new sendgrid.Email();
  48. email.setSubject("Order #{id} - {title}", order);
  49. </code></pre>
  50. <p>Simple and straightforward with <code>_.template()</code> under the hood. And as you see, you can choose your favourite placeholder syntax.</p>
  51. <h4 id="conclusion">Conclusion</h4>
  52. <p>In general, I would encourage you to <strong>make the effort to be more familiar with your third-party libraries</strong>. especially those with the breadth of a jQuery or Lodash. You don't have to know every function intimately, but you should have at least a shallow knowledge of all they have to offer. Spare some time to read through the documentation, not just look stuff up when you need it. General-purpose libraries like Lodash, with many loosely related functions, may contain something cool you never suspected was there and will save you the effort of writing and testing your own implementation. The best code, after all, is the code you never have to write.</p>
  53. <p>Even if you are familiar with your libraries, it’s not a bad idea to go back and check for new features from time to time. Do you know about <a href="http://api.jquery.com/category/callbacks-object/"><code>$.Callbacks()</code></a> in jQuery, for instance? I was surprised when I spotted it recently. Because I learned jQuery many years ago and consider myself an expert, I am prone to disregard new features. I haven’t used <code>$.Callbacks()</code> yet, but at least I know now that it exists and what it is about.</p>