<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Acatl on Medium]]></title>
        <description><![CDATA[Stories by Acatl on Medium]]></description>
        <link>https://medium.com/@acatl?source=rss-2c586ce429fb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Lx1TwjI4KmwDxwd4.jpg</url>
            <title>Stories by Acatl on Medium</title>
            <link>https://medium.com/@acatl?source=rss-2c586ce429fb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 00:50:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@acatl/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[re-exploring the factory pattern in javascript]]></title>
            <link>https://medium.com/@acatl/re-exploring-the-factory-pattern-in-javascript-6246b123e2fb?source=rss-2c586ce429fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/6246b123e2fb</guid>
            <dc:creator><![CDATA[Acatl]]></dc:creator>
            <pubDate>Wed, 17 Dec 2014 18:51:21 GMT</pubDate>
            <atom:updated>2014-12-19T17:43:36.174Z</atom:updated>
            <content:encoded><![CDATA[<p>whats the best approach to creating a new object?</p><p><em>Seems there isn’t such thing as a best approach and each author proposes different (but some what similar) solutions.</em></p><p>There are many good reads out there telling us we should get rid of the “<strong>new” </strong>and specially of the <strong>“this” </strong>keywords. Douglas Crockford himself explains it pretty well on his <a href="https://www.youtube.com/watch?v=PSGEjv3Tqo0">The Better Parts</a> presentation. <a href="http://ericleads.com/2012/09/stop-using-constructor-functions-in-javascript/">Stop Using Constructor Functions In JavaScript</a> by Eric Elliott from his book <a href="http://shop.oreilly.com/product/0636920033141.do?cmp=af-prog-books-videos-product_cj_9781491950296_%25zp">Programming JavaScript Applications</a>.<strong> </strong>A long but totally worth it read <a href="https://medium.com/javascript-scene/the-two-pillars-of-javascript-pt-2-functional-programming-a63aa53a41a4">How to Stop Micromanaging Everything</a> also from Eric Elliott from his series of <em>The two Pillars of Javascript.</em></p><p>Anyways, so these all very smart people tell us stop using these patterns, ok, swell, and so how exactly should we create new objects? whats the best approach?</p><blockquote>I had this specific issue, I have a JSON object, which acts as a definition object. once I read the JSON source I want to pass it through a factory method to get an actual JS Object, and because I can’t totally trust the JSON values, I want to be able to set some defaults, which is the main the reason for using a factory in this case.</blockquote><p><strong><em>note</em></strong><em>: just to be clear I do not need any methods attached to this object.</em></p><p>the classic way of doing this, or at least to my understanding would be</p><pre>function MyObject(spec){<br> this.prop1 = spec.prop1 || &#39;test&#39;;<br> this.prop2 = spec.prop2 || 0;<br>}</pre><p>to be used as:</p><pre>var myObject = new MyObject({prop1: ‘hi’});</pre><p>this is pretty straight forward, but its supposed to be discouraged, blah!</p><p>the proposed way of doing this is around:</p><pre>var def = {<br>  prop1: ‘test’,<br>  prop2: 0<br>}</pre><pre>function create(spec){<br>  var instance = {};<br>  instance.prop1 = spec.prop1 || ‘test’;<br>  instance.prop2 = spec.prop2 || 0;<br>  return instance;<br>}</pre><p>which at this point you might as well do:</p><pre>function create(spec){<br>  var instance = {};<br>  instance.prop1 = spec.prop1 || def.prop1;<br>  instance.prop2 = spec.prop2 || def.prop2;<br>  return instance;<br>}</pre><p>this is all well, but wait, according to Douglas he recommends to stop using <strong>“null”</strong> and “<em>falsy</em>” ouukay, so?</p><p>next round:</p><pre>function create(spec){<br> var i = {};<br> i.a = typeof spec.a == &#39;undefined&#39; ? def.a : spec.a;<br> i.b = typeof spec.b == &#39;undefined&#39; ? def.b : spec.b;<br> return i;<br>}</pre><p>lets stop here, this works, looks ok, and its definitely better than just checking against a “falsy” value, which can actually give you unexpected values. Say `spec.prop2 === false` and its a valid value, because of checking against falsy value you just set it to `0`, oh noes! not what you wanted ☹.</p><p>any ways, here is where my journey actually started.</p><h3>Round 1</h3><p>you see a pattern here?</p><pre>i.a = typeof spec.a == &#39;undefined&#39; ? def.a : spec.a;</pre><p>and to show my exploration path, I went through a couple of steps, to end back here again (sort of). and would like to share them.</p><p>my first thought was, oh this is a perfect place to use <strong>lodash</strong>’s <a href="https://lodash.com/docs#defaults">_.defaults</a> and it will actually make for a <strong>DRY</strong> approach.</p><pre>function create(spec){<br> var i = {};<br> return _.defaults(i, def);<br>}</pre><p>this works marvelous! but.. wait! because its a factory we actually care <strong>a lot </strong>about <strong>performance,</strong> so lets <em>jsperf </em>it.</p><p>and as expected <a href="http://jsperf.com/factory-vanilla-vs-lodash-defaults">http://jsperf.com/factory-vanilla-vs-lodash-defaults</a> vanilla is many many times faster, so, sadly lets drop lodash for this ☹</p><h3>Round 2</h3><p>using _.defaults significantly hits performance, lets do a for..in loop then? might not be that bad?</p><pre>function create(spec) {<br> var i = {};<br> for (key in def) {<br>  i[key] = typeof spec[key] === &#39;undefined&#39; ? def[key] : spec[key];<br> }<br> return i;<br>}</pre><p>sadly, as also expected, its pretty bad, <a href="http://jsperf.com/factory-set-manual-vs-for-in">http://jsperf.com/factory-set-manual-vs-for-in</a> not as bad as using lodash, but still not what we want for performance. It’s definitely not as bad as using lodash so could be a solution you might want to use if performance is not so so important to your use case.</p><h3>Round 3</h3><p>this all means we have to do it manually right? ok, if so at least lets do it via a function, to be as DRY as possible while not sacrificing performance at all.</p><pre>function getDefault(val, def) {<br> return typeof val === ‘undefined’ ? def : val; <br>}</pre><p>that should do it right?</p><pre>function create(spec){<br> var i = {};<br> i.a = getDefault(spec.a, def.a);<br> i.b = getDefault(spec.b, def.b);<br> return i;<br>}</pre><p>done! this works! its fast and its DRY! … is it?</p><h3>Round 4</h3><p>well we can always improve that getDefault method to:</p><pre>function getDefault(key, val, def) {<br> return typeof val[key] === ‘undefined’ ? def[key] : val[key]; <br>}</pre><p>ok, this will help me take it a step further into my obsessed DRY approach, but humm will it make it slower? lets <em>jsperf</em> it!</p><p><a href="http://jsperf.com/default-explicit-vs-dianmic-access">http://jsperf.com/default-explicit-vs-dianmic-access</a> not so bad! actually they end up being pretty even! actually if you run it a couple of times access via key can sometimes even come up faster O_o, well that is surprising!</p><p>well that wasn’t expected… usually making something be more dynamic you sacrifice performance, not the case here!</p><pre>function create(spec){<br> var i = {};<br> i.a = getDefault(&#39;a&#39;, i, def);<br> i.b = getDefault(&#39;b&#39;, i, def);<br> return i;<br>}</pre><p>call me a dork but I think this is all very interesting.</p><h3>Round 5</h3><p>this temped me to why not move in the setting of the property inside the getDefault method, as:</p><pre>function setDefault(key, src, def) {<br>  return src[key]=typeof src[key]===&#39;undefined&#39;? def[key]:src[key];<br>};</pre><p>and yet life had me another surprise, this is actually faster! wtff?! <a href="http://jsperf.com/set-default-explicit-vs-dinamic">http://jsperf.com/set-default-explicit-vs-dinamic</a></p><p>so either im loosing it or im missing something? you tell me. prob the second but for now seems we have a winner!</p><p>or do we?</p><h4>Round 5.1</h4><p>Well just to add more confusion to all of this I decided to test my original</p><pre>function getDefault(key, val, def) {<br> return typeof val[key] === ‘undefined’ ? def[key] : val[key]; <br>}</pre><p>vs</p><pre>function setDefault(key, src, def) {<br> return src[key]=typeof src[key]===&#39;undefined&#39;? def[key]:src[key];<br>};</pre><p>and well, seems like what <em>I expected to be </em><strong><em>even</em></strong> but guess what? now there is a BIG difference between them!!!</p><p>‘getDefault’ is many many times faster! <a href="http://jsperf.com/get-vs-set-through-keys">http://jsperf.com/get-vs-set-through-keys</a>.</p><p>I have no conclusion here (round 5.1), just plain confusion and leaving it to you to take it from here .</p><h3>Conclusion</h3><p><strong>1st</strong>: javascript is nuts!</p><p><strong>2nd</strong>: from my findings i’m sticking to:</p><pre>var def = {<br>  a: ‘test’,<br>  b: 0<br>};</pre><pre>function create(spec){<br>  var i = {};<br>  setDefault(‘a’, i, def);<br>  setDefault(‘b’, i, def);<br>  return i;<br>}</pre><p>what about you ? have any better ideas pls share!</p><p><em>side note</em>:</p><p>wanted to know if there was a big difference here, there is, but in this case I rather have the benefits from checking against undefined than blindly trusting a falsy value.</p><p><a href="http://jsperf.com/factory-falsy-vs-undefined-check">http://jsperf.com/factory-falsy-vs-undefined-check</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6246b123e2fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>