<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Running with Code</title>
	<atom:link href="http://robpaveza.net/feed" rel="self" type="application/rss+xml" />
	<link>http://robpaveza.net</link>
	<description>Like with scissors, only more dangerous</description>
	<lastBuildDate>Mon, 20 Feb 2012 06:27:56 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>A brief detour: Dry rub for ribs</title>
		<link>http://robpaveza.net/a-brief-detour-dry-rub-for-ribs</link>
		<comments>http://robpaveza.net/a-brief-detour-dry-rub-for-ribs#comments</comments>
		<pubDate>Mon, 20 Feb 2012 06:27:56 +0000</pubDate>
		<dc:creator>Rob Paveza</dc:creator>
				<category><![CDATA[Living Life]]></category>
		<category><![CDATA[cooking]]></category>

		<guid isPermaLink="false">http://robpaveza.net/?p=182</guid>
		<description><![CDATA[I have to admit: I'm excited. Tomorrow morning, I'll be putting my first ever dry rub on ribs. I've been looking forward to this because I've got a friend whose family is gluten-intolerant, and before he knew it, we always used to enjoy crock pot ribs with some store-bought K.C. Masterpiece honey barbecue sauce. Since [...]]]></description>
			<content:encoded><![CDATA[<p>I have to admit: I'm excited.  Tomorrow morning, I'll be putting my first ever dry rub on ribs.  I've been looking forward to this because I've got a friend whose family is <a href="http://en.wikipedia.org/wiki/Coeliac_disease" target="_blank">gluten-intolerant</a>, and before he knew it, we always used to enjoy crock pot ribs with some store-bought K.C. Masterpiece honey barbecue sauce.  Since they stopped eating gluten, we haven't really enjoyed ribs together.  Not only that issue, but there's also the issue of actually just finding ribs when they're drowned in the sauce within the crock pot.  So, for a while, I've been looking for a somewhat savory rub that I could make gluten-free that would be tasty.  I think I've found it.</p>
<p>Apparently, <a href="http://crockpot365.blogspot.com/2008/11/john-mccains-rib-recipe-in-crockpot.html" target="_blank">John McCain has a fantastic dry rub</a> that he uses.  I'm going to adapt the recipe on that site a little bit: I have more ribs, and I think I can get a little bit more variety (and I'd like to have a little kick).  So here are my ingredients:</p>
<ul>
<li>3 tablespoons kosher salt</li>
<li>3 tablespoons garlic powder</li>
<li>2 tablespoons black pepper</li>
<li>1 tablespoon chili powder (I would have preferred cayenne pepper I think, but we didn't have any) - I'd like it to have just a little more punch than just black pepper would have</li>
<li>1 orange, 2 lemons, and 1 lime, juiced</li>
</ul>
<p>Otherwise, I'll follow the recipe as indicated: apply the rub all over the ribs, and then add the juice.  Cook on low 8-10 hours.</p>
<p>I wanted to mix up the citrus a little.  Citrus is generally interchangeable, but lime is my favorite citrus, and I wasn't willing to completely give up the sweetness of typical barbecue, so I thought the orange might be able to help add that a bit.</p>
<p>I will post some pictures and thoughts once they are cooked.  </p>
]]></content:encoded>
			<wfw:commentRss>http://robpaveza.net/a-brief-detour-dry-rub-for-ribs/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Review of Balsamiq Mockups</title>
		<link>http://robpaveza.net/a-review-of-balsamiq-mockups</link>
		<comments>http://robpaveza.net/a-review-of-balsamiq-mockups#comments</comments>
		<pubDate>Sun, 19 Feb 2012 07:01:29 +0000</pubDate>
		<dc:creator>Rob Paveza</dc:creator>
				<category><![CDATA[Computing]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[mockups]]></category>
		<category><![CDATA[wireframing]]></category>

		<guid isPermaLink="false">http://robpaveza.net/?p=175</guid>
		<description><![CDATA[Balsamiq was kind enough to provide me with a free license for Mockups a while back on the condition that I reviewed it. I'm embarrassed to say it is WAY longer than I would have expected if I had been the one providing the license. That said, I definitely still owe them the review, so [...]]]></description>
			<content:encoded><![CDATA[<p>Balsamiq was kind enough to provide me with a free license for <a href="http://www.balsamiq.com/products/mockups" target="_blank">Mockups</a> a while back on the condition that I reviewed it.  I'm embarrassed to say it is WAY longer than I would have expected if I had been the one providing the license.  That said, I definitely still owe them the review, so I think I'd better get on it!  (I had originally intended to do a videocast of using Mockups but I'm not particularly good at that sort of thing).</p>
<p>My daily job responsibilities have never been 100% on wireframing or feature design.  Up until I was introduced to Mockups, I had tried out <a href="http://www.axure.com/" target="_blank">Axure RP Pro</a> (I think around version 5), and during my time at Terralever, we used <a href="http://www.omnigroup.com/products/omnigraffle/" target="_blank">Omnigraffle</a> extensively.  I first was introduced to Mockups when we were partnering with MySpace on <a href="http://www.hulu.com/if-i-can-dream" target="_blank">If I Can Dream</a>.  I was impressed initially by the extremely rapid prototyping that we were able to do as a collaborative team.  I had spent probably about 30 hours doing the initial Facebook-based proposal, which was, in fairness, <i>far</i> more extensive than the MySpace integration ended up being (sorry JT).  That said, we were able to put Mockups up on the projector and it was really easy to make some interesting UI components very quickly.</p>
<p>Since then, I've used Mockups at Terralever as well as with my own consulting business.  Generally, I've found that Mockups is ideal when I'm looking for:</p>
<ul>
<li>Very rapid prototyping, to help conceptualize something that I'm actively coding and just need to give myself a fixed visual.</li>
<li>Prototypes that I'm going to deliver in PDF format, because of the automatic internal linking it provides (more later).</li>
<li>Any kind of prototypes that are going to be "internal only."  If I need to perform a "real" usability consultation, I prefer Omnigraffle; I think that what I can find in Omnigraffle generally looks a little more polished.</li>
</ul>
<h2>The Prototyping Experience</h2>
<p>Absolutely exceptional.  To be honest, I think it's the best aspect of Mockups in terms of its speed advantage.  If the components are there in the library, it's incredibly fast to go from nothing to something good.  Let's take a simple example of a common navigation element: the tabs list.  Drag-and-drop from the library onto a fresh canvas, and this is what we're presented with:<br />
<a href="http://robpaveza.net/wp-content/uploads/2012/02/tabsbar-entertext.png"><img src="http://robpaveza.net/wp-content/uploads/2012/02/tabsbar-entertext.png" alt="" title="tabsbar-entertext" width="296" height="135" class="alignnone size-full wp-image-176" /></a><br />
You can see that there are four items in a comma-delimited list.  What could be more intuitive than that?  Well, I'll type some comma-separated items in and then hit enter:<br />
<a href="http://robpaveza.net/wp-content/uploads/2012/02/tabsbar-round2.png"><img src="http://robpaveza.net/wp-content/uploads/2012/02/tabsbar-round2.png" alt="" title="tabsbar-round2" width="392" height="118" class="alignnone size-full wp-image-177" /></a><br />
Okay, that's pretty good; but I think I should be able to have the Mockups tab selected.  Lo and behold, the very simple property editor window saves the day:<br />
<a href="http://robpaveza.net/wp-content/uploads/2012/02/tabsbar-round3.png"><img src="http://robpaveza.net/wp-content/uploads/2012/02/tabsbar-round3.png" alt="" title="tabsbar-round3" width="754" height="413" class="alignnone size-full wp-image-178" /></a><br />
You can see in this image that Mockups is selected (and it is highlighted in the "Selected" field of the property editor as well).  But what's also very neat about this control (and other similar ones) is the "Links" property set.  See how there's a field for each one of the tabs that I created?  Every one of them can link to another Mockup in the same folder.  When I choose to export them to PDF, those links will be live, and I'll be able to navigate between mockups by clicking on the linking element.  In my opinion, it's one of the coolest interactive features, and it's readily surfaced.  (I suspect that there may be similar features in Omnigraffle but I've never used them if they do exist).</p>
<p>Also very cool for preserving your "sketch" feel is the ability to "Sketchify" (okay, that term isn't in the UI, but it fits) any bitmapped image you drop into the app.  It's actually very good and accurate.  Take a look at this (original images courtesy of Amazon and Google Shopping).:<br />
<a href="http://robpaveza.net/wp-content/uploads/2012/02/sketched-images.png"><img src="http://robpaveza.net/wp-content/uploads/2012/02/sketched-images.png" alt="" title="sketched-images" width="457" height="304" class="alignnone size-full wp-image-179" /></a><br />
This is tremendous for those of us who want to use images to get the point across but are terrible at using Photoshop for anything other than taking someone else's image and using the "Slice" tool.</p>
<p>I've found the locking and ordering mechanism to be very intuitive.  Mockups is also very good about letting you select the element you want with the right-click menu, which lets you select down the visual hierarchy even if the element you're trying to get (for instance, a Web Browser surface) is occluded by something else.</p>
<h2>The Library</h2>
<p>The UI library is adequate.  There have been times where I've longed for the ability to add a control to it, which invariably leads me to creating a "Library" mockup that contains my custom "controls."  The drawback to this model is that you don't get the very nice programmed editing capabilities.  For example, suppose I wanted to wireframe the feature that Facebook uses when you've auto-completed a friend (you know, the highlighted background with an X to the right of the text).  I can make something that looks like it.  However, I don't get the great features of the intrinsic controls: I can't make only the text editable, and I can't make the X hotlink to another wireframe.  There may be a way to develop these kinds of extensions, but I haven't found it.  The lack of extensibility in this sense is a detractor compared to Omnigraffle (compare <a href="http://graffletopia.com/" target="_blank">Graffletopia</a>), but at the same time, it's a good challenge to be able to do more with less.  (I love Graffletopia's diversity in components, but it can also give you a library that is much, much too large).</p>
<p>Still, I think that, while there have been times that I've really wished for some specific controls, it's generally given me what I've needed.  And when it didn't have quite what I needed, I was able to fake it.</p>
<p>That said, there is one thing that stands above the others: the Text Paragraph control:<br />
<a href="http://robpaveza.net/wp-content/uploads/2012/02/paragraph.png"><img src="http://robpaveza.net/wp-content/uploads/2012/02/paragraph.png" alt="" title="paragraph" width="211" height="89" class="alignnone size-full wp-image-180" /></a><br />
You can see inline the italics, hyperlink, and bold format specifiers that can automatically be applied.  I've found this enormously useful and I think the inline links are particularly handy (it's not something you see everywhere).  But without a doubt, the best part is that you can get them while you're typing: no need to stop and use the mouse to select a text range just to get a special format like that.</p>
<h2>How it stacks up</h2>
<p>I realize that as someone who almost exclusively develops on the Microsoft stack, I should probably at least occasionally wireframe in Expression Blend's Sketchflow feature.  I'm mildly ashamed to admit that I've never tried it; I think I'm afraid that if I start working in Sketchflow I'll get the urge to do some real programming, or I'll spend too much time on an animation and not get the actual prototyping done.  So with that in mind, I'm going to compare it to Axure and Omnigraffle, because those are the other two tools I've used.</p>
<p><b>Axure</b>: Mockups, even the first time I saw it, was miles ahead of Axure in appearance.  Noted that it's probably 2 years ago that I tried Axure, but it sometimes felt like I was literally working with the .NET Windows Forms or Web Forms designer controls (the radio buttons stand out in my mind as looking like they were pure Windows-based controls).  I have seen the end-result of some Axure work recently and was a bit impressed (I think they've added some sketchlike appearance support in a recent version).  That said, I get the general impression that Axure's prototypes are meant to look a bit more like the real thing than wireframes that you might generate using Mockups or Omnigraffle.</p>
<p><b>Omnigraffle</b>: Like I noted above, I tend to like Omnigraffle when I'm consulting for a client.  Mockups produces visuals that are very sketch-like in their appearance, and while this is generally a Good Thing, sometimes that rounded edge or drop-shadow that you can include in Omnigraffle makes the product really pop.  Still, Omnigraffle is only available on Mac and iPad, and while I have an iMac, I tend to be developing in Windows.  The reboot required to go into OS X makes it cost-prohibitive to use when I'm going to be the consumer of the wireframes.  Mockups, being an Adobe AIR application, can run on either platform.  As a result, when I need to give myself some visual guidance, I tend to do my rapid prototyping in Mockups.</p>
<p>One note: Since installing Mockups on my new laptop, I was surprised to see that Comic Sans is no longer the default font.  In some ways this saddens me.  I realize that most customers were probably unhappy with that as the default because it made them hesitant to show their mockups to customers.  I thought that it was a bit charming in its own way - another not-so-subtle reminder to "not take this visual too seriously".  Oh well <img src='http://robpaveza.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Thanks, Balsamiq, for the Mockups license!  Keep the goodness coming!</p>
]]></content:encoded>
			<wfw:commentRss>http://robpaveza.net/a-review-of-balsamiq-mockups/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Bridging the gap between Jurassic and the DLR, Part Two</title>
		<link>http://robpaveza.net/bridging-the-gap-between-jurassic-and-the-dlr-part-two</link>
		<comments>http://robpaveza.net/bridging-the-gap-between-jurassic-and-the-dlr-part-two#comments</comments>
		<pubDate>Thu, 16 Feb 2012 07:31:28 +0000</pubDate>
		<dc:creator>Rob Paveza</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dynamic programming]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jurassic]]></category>

		<guid isPermaLink="false">http://robpaveza.net/?p=166</guid>
		<description><![CDATA[Part Two: A More Complete Object Model Part 1: ObjectInstance derives from DynamicObject Once I started implementing the rest of the object model, things started coming together very well. Let's take a look at the rest of the ObjectInstance implementation: For FunctionInstance: For ArrayInstance, things were a little more interesting. JavaScript doesn't support multidimensional arrays [...]]]></description>
			<content:encoded><![CDATA[<h2>Part Two: A More Complete Object Model</h2>
<ul>
<li><a href="http://robpaveza.net/bridging-the-gap-between-jurassic-and-the-dlr-part-one">Part 1: ObjectInstance derives from DynamicObject</a></li>
</ul>
<p>Once I started implementing the rest of the object model, things started coming together very well.  </p>
<p>Let's take a look at the rest of the ObjectInstance implementation:</p>
<pre class="brush: csharp; title: ; notranslate">
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            return TryCallMemberFunction(out result, binder.Name, args);
        }

        public override bool TryConvert(ConvertBinder binder, out object result)
        {
            if (binder.ReturnType == typeof(string))
            {
                result = this.ToString();
                return true;
            }
            else
            {
                try
                {
                    result = Jurassic.TypeConverter.ConvertTo(this.engine, this, binder.ReturnType);
                    return true;
                }
                catch
                {
                    result = null;
                    return false;
                }
            }
        }

        public override bool TryDeleteMember(DeleteMemberBinder binder)
        {
            return Delete(binder.Name, false);
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            this.FastSetProperty(binder.Name, value, PropertyAttributes.FullAccess, true);
            return true;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = GetNamedPropertyValue(binder.Name, this);
            if (object.ReferenceEquals(null, result))
                return false;

            return true;
        }
</pre>
<p>For FunctionInstance:</p>
<pre class="brush: csharp; title: ; notranslate">
        public override bool TryInvoke(System.Dynamic.InvokeBinder binder, object[] args, out object result)
        {
            try
            {
                result = CallLateBound(this, args);
                return true;
            }
            catch
            {
                result = null;
                return false;
            }
        }
</pre>
<p>For ArrayInstance, things were a little more interesting.  JavaScript doesn't support multidimensional arrays (as in C#, where you can access something via <tt>someArr[1,5]</tt>).  However, it's important to consider the type.  Fortunately, Jurassic provides that as well, fairly easily.</p>
<pre class="brush: csharp; title: ; notranslate">
        public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
        {
            Debug.Assert(indexes != null &amp;&amp; indexes.Length &gt; 0);

            result = null;

            if (indexes.Length &gt; 1)
                return false; // multi-dimensional arrays are not supported.

            if (object.ReferenceEquals(null, indexes[0]))
                return false;

            Type indexType = indexes[0].GetType();
            if (indexType.IsEnum)
            {
                indexType = Enum.GetUnderlyingType(indexType);
            }

            if (indexType == typeof(byte) || indexType == typeof(sbyte) || indexType == typeof(short) || indexType == typeof(ushort) || indexType == typeof(int) || indexType == typeof(uint))
            {
                uint index = unchecked((uint)indexes[0]);
                try
                {
                    result = this[index];
                    return true;
                }
                catch
                {
                    result = null;
                    return false;
                }
            }
            else
            {
                string index = indexes[0].ToString();
                try
                {
                    result = this[index];
                    return true;
                }
                catch
                {
                    result = null;
                    return false;
                }
            }
        }

        public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
        {
            Debug.Assert(indexes != null &amp;&amp; indexes.Length &gt; 0);

            if (indexes.Length &gt; 1)
                return false; // multi-dimensional arrays are not supported.

            if (object.ReferenceEquals(null, indexes[0]))
                return false;

            Type indexType = indexes[0].GetType();
            if (indexType.IsEnum)
            {
                indexType = Enum.GetUnderlyingType(indexType);
            }

            if (indexType == typeof(byte) || indexType == typeof(sbyte) || indexType == typeof(short) || indexType == typeof(ushort) || indexType == typeof(int) || indexType == typeof(uint))
            {
                uint index = unchecked((uint)indexes[0]);
                try
                {
                    this[index] = value;
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            else
            {
                string index = indexes[0].ToString();
                try
                {
                    this[index] = value;
                    return true;
                }
                catch
                {
                    return false;
                }
            }
        }

        public override bool TryDeleteIndex(DeleteIndexBinder binder, object[] indexes)
        {
            Debug.Assert(indexes != null &amp;&amp; indexes.Length &gt; 0);

            if (indexes.Length &gt; 1)
                return false; // multi-dimensional arrays are not supported.

            if (object.ReferenceEquals(null, indexes[0]))
                return false;

            Type indexType = indexes[0].GetType();
            if (indexType.IsEnum)
            {
                indexType = Enum.GetUnderlyingType(indexType);
            }

            if (indexType == typeof(byte) || indexType == typeof(sbyte) || indexType == typeof(short) || indexType == typeof(ushort) || indexType == typeof(int) || indexType == typeof(uint))
            {
                uint index = unchecked((uint)indexes[0]);
                return Delete(index, false);
            }
            else
            {
                string index = indexes[0].ToString();
                return Delete(index, false);
            }
        }
</pre>
<p>I did add one set of precompilation directives so that I could modify ScriptEngine with one little item:</p>
<pre class="brush: csharp; title: ; notranslate">
        public
#if SUPPORT_DYNAMIC
            dynamic
#else
            object
#endif
            GetGlobalValue(string variableName)
        {
            if (variableName == null)
                throw new ArgumentNullException(&quot;variableName&quot;);
            return TypeUtilities.NormalizeValue(this.Global.GetPropertyValue(variableName));
        }
</pre>
<p>With that gem, we're in good shape.  I'll update the test program; let's take a good look:</p>
<pre class="brush: csharp; title: ; notranslate">
    class Program
    {
        static void Main(string[] args)
        {
            ScriptEngine engine = new ScriptEngine();

            engine.SetGlobalFunction(&quot;write&quot;, (Action&lt;string&gt;) ((s) =&gt; { Console.WriteLine(s); }));

            engine.Execute(@&quot;
var a = {
    A: 'A',
    B: 20,
    C: function() { return 'Hello'; }
};

function double(val)
{
    return val * 2;
}

var array = [1, 5, 9, 13, 21];
&quot;);
            dynamic obj = engine.Evaluate&lt;ObjectInstance&gt;(&quot;a&quot;);
            Console.WriteLine(obj.A);
            Console.WriteLine(obj.B);
            Console.WriteLine(obj.C());
            obj.D = &quot;What's that?&quot;;

            Console.WriteLine(&quot;C#: &quot; + obj.D);

            engine.Execute(@&quot;
write('JavaScript: ' + a.D);
&quot;);

            dynamic dbl = engine.GetGlobalValue(&quot;double&quot;);
            Console.WriteLine(dbl(20));
            Console.WriteLine(dbl.call(null, 20));

            dynamic array = engine.GetGlobalValue(&quot;array&quot;);
            Console.WriteLine(array[2]);

            Console.ReadLine();

        }
    }
</pre>
<p>Output is happily correct:</p>
<pre>
A
20
Hello
C#: What's that?
JavaScript: What's that?
40
40
9
</pre>
<p>Particularly neat about this implementation is that the calls automatically recurse.  Note that I use the intrinsic JavaScript <tt>call</tt> method on the Function instance (of <tt>dbl</tt>).  This implementation covers a whole bunch of typical scenarios and use-cases, and I'm happy to see that it has worked out fairly well thus far.</p>
<p>One item I've found is that there's a TypeLoadException when targeting .NET 4.  This has something to do with a new CAS policy in .NET 4.  For now, applying this attribute to the test program as well as the library will resolve the issue, though I don't intend for it to be long-term:</p>
<pre>
[assembly: System.Security.SecurityRules(System.Security.SecurityRuleSet.Level1)]
</pre>
<p>Next time, we'll do some more fit and finish, with precompilation constants and a security review.</p>
]]></content:encoded>
			<wfw:commentRss>http://robpaveza.net/bridging-the-gap-between-jurassic-and-the-dlr-part-two/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Bridging the gap between Jurassic and the DLR, Part One</title>
		<link>http://robpaveza.net/bridging-the-gap-between-jurassic-and-the-dlr-part-one</link>
		<comments>http://robpaveza.net/bridging-the-gap-between-jurassic-and-the-dlr-part-one#comments</comments>
		<pubDate>Tue, 14 Feb 2012 07:50:04 +0000</pubDate>
		<dc:creator>Rob Paveza</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[dynamic programming]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jurassic]]></category>

		<guid isPermaLink="false">http://robpaveza.net/?p=164</guid>
		<description><![CDATA[Part One: ObjectInstance derives from DynamicObject A while back I posted that I was joining the Jurassic team; Jurassic is an open-source JavaScript engine for .NET. If you've ever gone through the long search for a JavaScript implementation on .NET (other than JScript.NET, of course), there are a bunch of incomplete implementations, and if you're [...]]]></description>
			<content:encoded><![CDATA[<h2>Part One: ObjectInstance derives from DynamicObject</h2>
<p>A while back I posted that I was <a href="http://robpaveza.net/joining-the-jurassic-team">joining the Jurassic team</a>; Jurassic is an <a href="http://jurassic.codeplex.com/" target="_blank">open-source JavaScript engine for .NET</a>.  If you've ever gone through the long search for a JavaScript implementation on .NET (other than JScript.NET, of course), there are a bunch of incomplete implementations, and if you're lucky enough to find the blog about the Microsoft project of JScript running on the DLR (once called Managed JScript), you'll find that it was an implementation that was specifically designed to give design feedback on the DLR itself, and was not planned to be carried forward into production.  Personally I think that's too bad, but I'm happy to see a couple of projects (notably, Jurassic and IronJS) that have stepped up to fill the gap.</p>
<p>I had considered implementing <a href="http://msdn.microsoft.com/en-us/library/system.dynamic.idynamicmetaobjectprovider.aspx" target="_blank">IDynamicMetaObjectProvider</a>, but inheriting from <a href="http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx" target="_blank">DynamicObject</a> seems to be a better design decision all-around.  Since all of the other JavaScript objects inherit from ObjectInstance, it's a simple matter of overriding its virtual methods instead of creating a new implementation of DynamicMetaObject for each class in the hierarchy.</p>
<p>I've created a new library project within the solution as well as a simple testing project to advise on the API as well as to step into my DynamicObject overrides.  Here are some simple components:</p>
<pre class="brush: csharp; title: ; notranslate">
// These are new:
using System.Dynamic;
using System.Diagnostics;

// This is updated
    public class ObjectInstance
        : DynamicObject
#if !SILVERLIGHT
        , System.Runtime.Serialization.IDeserializationCallback
#endif
    {

// The class exists as normal
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            result = GetNamedPropertyValue(binder.Name, this);
            if (result != null)
                return true;

            return false;
        }

        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            try
            {
                result = CallMemberFunction(binder.Name, args);
                return true;
            }
            catch
            {
                result = null;
                return false;
            }
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            this.AddProperty(binder.Name, value, PropertyAttributes.FullAccess, true);
            return true;
        }

    }
</pre>
<p>This is the source of the test application.  It's very straightforward:</p>
<pre class="brush: csharp; title: ; notranslate">
        static void Main(string[] args)
        {
            ScriptEngine engine = new ScriptEngine();

            engine.SetGlobalFunction(&quot;write&quot;, (Action&lt;string&gt;) ((s) =&gt; { Console.WriteLine(s); }));

            engine.Execute(@&quot;
var a = {
    A: 'A',
    B: 20,
    C: function() { return 'Hello'; }
};
&quot;);
            dynamic obj = engine.Evaluate&lt;ObjectInstance&gt;(&quot;a&quot;);
            Console.WriteLine(obj.A);
            Console.WriteLine(obj.B);
            Console.WriteLine(obj.C());
            obj.D = &quot;What's that?&quot;;

            Console.WriteLine(&quot;C#: &quot; + obj.D);

            engine.Execute(@&quot;
write('JavaScript: ' + a.D);
&quot;);

            Console.ReadLine();

        }
</pre>
<p>We create a global function 'write' which writes a string to the console.  Then we create a global object <tt>a</tt> with properties <tt>A</tt>, <tt>B</tt>, and <tt>C</tt>.  We then use C# to retrieve the value of this object as a <tt>dynamic</tt>.  This is what provides us access to the <tt>DynamicObject</tt>'s overrides intrinsic within C#'s support of the DLR.  We then access each property (which each return a <tt>dynamic</tt>) and, happily because of Jurassic's automatic conversion of primitives to their respective .NET types, when these values are returned as <tt>dynamic</tt>, they can be automatically converted to their appropriate types for their <tt>Console.WriteLine</tt> parameter.  You can see that we invoke <tt>TryGetMember</tt> on <tt>A</tt> and <tt>B</tt>, <tt>TryInvokeMember</tt> on <tt>C</tt>, and <tt>TrySetMember</tt> and then <tt>TryGetMember</tt> on <tt>D</tt>.</p>
<p>OK, it's late, so I'm not going to stick this out anymore right now.  I'm not even sure if the previous paragraph was particularly coherent.  <img src='http://robpaveza.net/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>There's a lot to update: it doesn't support case-insensitive languages (like Visual Basic), it's not particularly good at error checking, and I haven't dealt with any other components yet.  The good news is that it seems like we should be good to go for the rest of the components.  </p>
<p>Next time, we'll look at other classes, like ArrayInstance, FunctionInstance, and more.</p>
]]></content:encoded>
			<wfw:commentRss>http://robpaveza.net/bridging-the-gap-between-jurassic-and-the-dlr-part-one/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>In a disconnected world, robust code is crucial</title>
		<link>http://robpaveza.net/in-a-disconnected-world-robust-code-is-crucial</link>
		<comments>http://robpaveza.net/in-a-disconnected-world-robust-code-is-crucial#comments</comments>
		<pubDate>Tue, 07 Feb 2012 06:15:40 +0000</pubDate>
		<dc:creator>Rob Paveza</dc:creator>
				<category><![CDATA[Computing]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[asynchrony]]></category>
		<category><![CDATA[best practices]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[performance]]></category>

		<guid isPermaLink="false">http://robpaveza.net/?p=148</guid>
		<description><![CDATA[Probably 99.99% of HTML applications and websites are served over HTTP exclusively. (I'm referring here to HTTP as a transport protocol, not HTTP vs.HTTPS, for example, and I realize that HTTP is an application-layer protocol according to OSI; but developers generally treat it as an abstraction for "the network"). As anybody who has done web [...]]]></description>
			<content:encoded><![CDATA[<p>Probably 99.99% of HTML applications and websites are served over <a href="http://en.wikipedia.org/wiki/HTTP" target="_blank">HTTP</a> exclusively.  (I'm referring here to HTTP as a transport protocol, not HTTP vs.HTTPS, for example, and I realize that HTTP is an application-layer protocol according to <a href="http://en.wikipedia.org/wiki/OSI_model" target="_blank">OSI</a>; but developers generally treat it as an abstraction for "the network").  As anybody who has done web programming knows, HTTP is a <em>stateless</em> protocol; that is, it's based on a request-response model, and in general, one request has no knowledge of previous requests.  This has posed some challenges for web developers over the years, and some brilliant abstractions of state on top of the statelessness have been devised.</p>
<p>The hard part now, though, isn't to deal with statelessness.  It's dealing with the <a href="http://en.wikipedia.org/wiki/Request-response" target="_blank">request-and-response</a> model.</p>
<p>All network communication is inherently request-and-response.  There are some applications that utilize full-duplex communications to get around that (think of chat software), but for the most part, that isn't really available behind the firewall.  <a href="http://en.wikipedia.org/wiki/WebSocket" target="_blank">Web sockets</a> are still yet to be standardized (and there are some questions about long-term compatibility with WebSocket-ignorant proxies).  And typically, corporate firewalls say no to outbound connections except on ports 80 or 443.  Some applications (think <a href="http://www.meebo.com/" target="_blank">Meebo</a>) have been able to get around this limitation by cleverly using long-timeout delays on AJAX requests.  The client makes a request to the server, and the server either responds immediately (if an event is in queue) or holds the request for 30-90 seconds to see if an event comes in.  I even did this once myself with good success, although I never took that app into production.  (There was also some question about the total # of clients an ASP.NET server could sustain whilst holding threads in that way).</p>
<p>In many respects, Windows developers haven't had to deal with this.  We could issue <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.receive.aspx" target="_blank">synchronous requests</a>, and the UI would stand still for a second, and either it would work or it would fail.  But usability concerns over this process, as well as issues with high network latency (imagine pressing the "Submit" button and having to wait 20 seconds while your app freezes - by then, I've force-closed the app) have seen platform providers decree that asynchrony is the only way to go.</p>
<p>HTML isn't the only application provider dealing with this limitation.  Adobe Flash has long had an asynchronous-communication-only model, <a href="http://www.informit.com/articles/article.aspx?p=1759240" target="_blank">Microsoft Silverlight</a> has also carried on this principle; of course, these two applications have lived predominantly in browsers, where a hanging UI probably means interfering with other apps as well as the one making the request.  Interestingly, WinRT - the Windows 8 developer framework - is also going to <a href="http://revoseek.com/information-technology/asynchronous-api-based-element-of-metro-ui-windows-8-winrt/" target="_blank">mandate an asynchronous model</a>, following in the Silverlight-based foodsteps blazed by Windows Phone 7.</p>
<p>So as we trek out into the world of asynchrony, well, we have a whole mess of questions to deal with now:</p>
<ul>
<li>If there's an error, does it show up in the calling method or in the callback method?  Does it even show up?</li>
<li>Does a network (transport-level) error surface differently than an application error?  What if the server returned an HTTP 403 Forbidden response?</li>
<li>What are all of the different <em>kinds</em> of errors that can crop up?  Do I need to handle SocketException or is that going to be abstracted to something more meaningful to my application?</li>
<li>What do I do if a network error comes up?  Do I assume that I'm offline, panic, and quit?  What if my application only makes sense "online"?</li>
<li>Do I surface an error to the customer?  Silently fail?  I might generally fail silently if I'm a background process, but then again, what if it's an important one?  What if the customer thought he was saving his draft while all along it was offline, and then the customer closes the browser?</li>
<li>During the async operation, should I show the user a timeout spinner or something to that effect?</li>
<li>How should I design my async operations?  For example, consider a Save operation.  Should I capture all of my state at once and send it off, and let the user immediately keep working?  Should I make the user wait until saving completes?  Should I even use Save, or automatically save whenever something changes?</li>
<li>If I use auto-save, how do I handle undo?  What if I want to undo between sessions?  Is there a way to go back if the hosting application crashes?  (Worst case scenario: the user accidentally hit Select All, Delete and then the browser crashed after the auto-save).</li>
</ul>
<p>This merely scratches the surface of the kinds of questions we'll need to begin asking ourselves.  It doesn't even deal with the difficulties of programming asynchronously, which C# 5 is going to deal with extraordinarily, but many developers will be unable to take advantage of these updates.  For example, suppose I have a widget on my page that monitors the status of a long-running server-based process.  I need to have JavaScript on my page that monitors that process and updates my widget accordingly.  Should I:</p>
<ul>
<li>Write a <a href="http://en.wikipedia.org/wiki/Singleton_pattern" target="_blank">singleton object</a>?  This might be easier and afford strong member protection, but I can only have one widget, unless I somehow differentiate between them and multiplex, which can become hairy quickly.</li>
<li>Should the monitoring function accept a callback, or should it be event-based, so that multiple subscribers can listen?  (Maybe an event-based model offers some interesting ways to deal with the complexities of a singleton?)</li>
<li>Should the widget manipulate the view directly, or should I write separate code that handles the view based on the state of the object (or objects)?</li>
</ul>
<p>The list goes on.</p>
<p>We're moving faster and faster into an asychronous world.  It is already happening, and we as developers need to be prepared to handle these difficulties.  We also need to understand how to communicate these kinds of questions to our business analysts, our supervisors, and our customers.  We need to be able to equip ourselves to ask the right questions of our customers, so that when it's time to make a decision, we have the information we need.</p>
]]></content:encoded>
			<wfw:commentRss>http://robpaveza.net/in-a-disconnected-world-robust-code-is-crucial/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Usability Problem</title>
		<link>http://robpaveza.net/a-usability-problem</link>
		<comments>http://robpaveza.net/a-usability-problem#comments</comments>
		<pubDate>Sat, 28 Jan 2012 19:01:02 +0000</pubDate>
		<dc:creator>Rob Paveza</dc:creator>
				<category><![CDATA[Computing]]></category>
		<category><![CDATA[criticism]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[firefox]]></category>
		<category><![CDATA[ux]]></category>

		<guid isPermaLink="false">http://robpaveza.net/?p=143</guid>
		<description><![CDATA[I don't use Firefox very often. Generally I'm in Chrome or IE. But, I keep Firefox on my taskbar, because I do enough web development that it's prudent for browser compatibility testing. Every now and then I get this dialog: Note that when I'm not taking a screenshot, that first item has a blue highlight [...]]]></description>
			<content:encoded><![CDATA[<p>I don't use Firefox very often. Generally I'm in Chrome or IE. But, I keep Firefox on my taskbar, because I do enough web development that it's prudent for browser compatibility testing.</p>
<p>Every now and then I get this dialog:<br />
<img class="alignnone size-full wp-image-144" title="ffox-addons" src="http://robpaveza.net/wp-content/uploads/2012/01/ffox-addons.png" alt="Firefox Add-ons Dialog" width="524" height="506" /></p>
<p>Note that when I'm not taking a screenshot, that first item has a blue highlight instead of gray.</p>
<p>What's the problem?  </p>
<p>Well, first of all, it's a popup.  It has its own window, which in my mind, means that Firefox thinks I ought to do something about it.  The only action that appears to be there is the "Find Updates" button; but of course, that doesn't find updates to the plugin I just installed, which is the purpose of the dialog in the first place, isn't it?</p>
<p>No.  In the screenshot, the Java Console 6.0.27 is the newly-installed plugin because I just installed Java (with MonoTouch and MonoDevelop).</p>
<p>Mozilla, this dialog sucks, and has sucked since I saw it back in the early days of Firefox.  Take a lesson from IE, and if you want to show me a notification, put it in a bar.  Make it say, "The 'Java Console' add-on has been newly installed."  Or, "4 new add-ons have been installed; <span style="color: blue; text-decoration: underline;">click here </span> to see this list."  </p>
<p>At the heart of this problem, though, is a <a href="http://www.joelonsoftware.com/articles/Biculturalism.html" target="_blank">cultural difference</a>; I strongly believe that the *nix culture is reflected in this user experience.  It was as if someone said, "OK, well, we'll run <tt>firefox --check-plugin-updates | firefox-ui</tt> and the result was piped to a new window, because it had nowhere better to go.  </p>
<p>That's not to say that command-line piping to the UI is a bad thing (though I believe that it's better to make the programmatic interface between two subsystems, well, programmatic, not text), but if someone had actually spent some time designing the user interaction for the "New plugins installed" use-case, they would not have decided to simply reuse the "Show all installed plugins" UI.</p>
]]></content:encoded>
			<wfw:commentRss>http://robpaveza.net/a-usability-problem/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A very fast, random text string generator in C#, Part One</title>
		<link>http://robpaveza.net/a-very-fast-random-text-string-generator-in-c-part-one</link>
		<comments>http://robpaveza.net/a-very-fast-random-text-string-generator-in-c-part-one#comments</comments>
		<pubDate>Wed, 18 Jan 2012 06:36:11 +0000</pubDate>
		<dc:creator>Rob Paveza</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[challenges]]></category>
		<category><![CDATA[math]]></category>
		<category><![CDATA[tools]]></category>

		<guid isPermaLink="false">http://robpaveza.net/?p=137</guid>
		<description><![CDATA[This is about half of a type I designed a few years ago in response to my boss's assertion that I couldn't improve on the speed of random string generators. This is a pretty handy type to have around when you want to generate a character string of a fixed length. It so happens that [...]]]></description>
			<content:encoded><![CDATA[<p>This is about half of a type I designed a few years ago in response to my boss's assertion that I couldn't improve on the speed of random string generators.  This is a pretty handy type to have around when you want to generate a character string of a fixed length.  It so happens that 6 characters can fit a "base 36" number very well into just over 2<sup>31</sup> bits (it's just a little bit bigger than <tt>int.MaxValue</tt> and so it stores the value as a <tt>uint</tt>).  </p>
<p>What is included below is a first step.  I want to show how to refactor it for improved performance and where certain design scenarios might be better; for example, repeatedly calling the <tt>CreateNew</tt> method results in repeatedly creating new <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.rngcryptoserviceprovider.aspx" target="_blank">RNGCryptoServiceProviders</a>.  Although I believe this class is a bit better about seeds as it incorporates hardware-dependent data, it isn't necessarily cryptographically strong.  You can add some strength by passing in a single RNG to each subsequent call, for example.</p>
<p>This sample also only goes one way: from number to string.  Next time, we'll show the reverse operation.</p>
<p>Note: an important inclusion:</p>
<pre class="brush: csharp; title: ; notranslate">using System.Security.Cryptography;</pre>
<pre class="brush: csharp; title: ; notranslate">
    /// &lt;summary&gt;
    /// Represents a number that may be transitioned to a six-digit alphanumeric (base-36) representation.  This type is not CLS-compliant.
    /// &lt;/summary&gt;
    [CLSCompliant(false)]
    public struct AlphaNumericNumber
    {
        private const uint MAX_VALUE = 2176782336; // = RADIX ^ 6
        private const int RADIX = 36; // 10 digits + 26 alphabetics
        private uint m_val;

        /// &lt;summary&gt;
        /// Creates a new &lt;see&gt;AlphaNumericNumber&lt;/see&gt; with the specified value.
        /// &lt;/summary&gt;
        /// &lt;param name=&quot;value&quot;&gt;The value with which to assign the number.&lt;/param&gt;
        public AlphaNumericNumber(uint value)
        {
            if (value &gt; MAX_VALUE)
                value %= MAX_VALUE;
            m_val = value;
        }

        /// &lt;summary&gt;
        /// Creates a new, random &lt;see&gt;AlphaNumericNumber&lt;/see&gt;.
        /// &lt;/summary&gt;
        /// &lt;returns&gt;A randomly-chosen &lt;see&gt;AlphaNumericNumber&lt;/see&gt;.&lt;/returns&gt;
        public static AlphaNumericNumber CreateNew()
        {
            byte[] container = new byte[4];
            using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
            {
                rng.GetNonZeroBytes(container);
            }

            return new AlphaNumericNumber(BitConverter.ToUInt32(container, 0));
        }

        /// &lt;inheritdoc /&gt;
        public override string ToString()
        {
            char[] result = new char[6];
            uint msd = RADIX * RADIX * RADIX * RADIX * RADIX;

            uint currentDigit = msd;
            uint accumulator = m_val;
            unchecked
            {
                for (int charIndex = 0; charIndex &lt; result.Length; charIndex++)
                {
                    uint currentDigitValue = accumulator / currentDigit;
                    accumulator -= (currentDigitValue * currentDigit);
                    if (currentDigitValue &lt;= 9)
                    {
                        result[charIndex] = (char)('0' + currentDigitValue);
                    }
                    else
                    {
                        currentDigitValue -= 10; // adjust for 'A' equaling 10.
                        result[charIndex] = (char)('A' + currentDigitValue);
                    }

                    currentDigit /= RADIX;
                }
            }

            return new string(result);
        }

        /// &lt;summary&gt;
        /// Gets the value contained by this &lt;see&gt;AlphaNumericNumber&lt;/see&gt;.
        /// &lt;/summary&gt;
        public uint Value
        {
            get { return m_val; }
        }
    }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://robpaveza.net/a-very-fast-random-text-string-generator-in-c-part-one/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Please, don&#8217;t ever use the &#8220;Remove Unused Namespaces&#8221; feature</title>
		<link>http://robpaveza.net/please-dont-ever-use-the-remove-unused-namespaces-feature</link>
		<comments>http://robpaveza.net/please-dont-ever-use-the-remove-unused-namespaces-feature#comments</comments>
		<pubDate>Wed, 11 Jan 2012 02:52:21 +0000</pubDate>
		<dc:creator>Rob Paveza</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[bad plugins]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[complaints]]></category>
		<category><![CDATA[maintenance programmer]]></category>
		<category><![CDATA[plugins]]></category>

		<guid isPermaLink="false">http://robpaveza.net/?p=134</guid>
		<description><![CDATA[Seriously, I don't know why this feature exists or who thought it would be a good idea. The time it takes to compile even the most complicated C# file is trivial. On the other hand, when I try to access the .Take() method in System.Linq, or the Encoding class in System.Text, or suddenly I need [...]]]></description>
			<content:encoded><![CDATA[<p>Seriously, I don't know why this feature exists or who thought it would be a good idea.  The time it takes to compile even the most complicated C# file is trivial.  </p>
<p>On the other hand, when I try to access the .Take() method in System.Linq, or the Encoding class in System.Text, or suddenly I need a new List&lt;T&gt; from System.Collections.Generic - if you have used a tool to remove unused namespaces from your C# code file - you have made me wonder why my editor isn't detecting it.</p>
<p>There's a reason that many default namespaces are included with a default C# code file.  Leave them there!  Maintenance programmers will love you forever.</p>
]]></content:encoded>
			<wfw:commentRss>http://robpaveza.net/please-dont-ever-use-the-remove-unused-namespaces-feature/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Revealing Prototype Pattern: Pros and Cons</title>
		<link>http://robpaveza.net/revealing-prototype-pattern-pros-and-cons</link>
		<comments>http://robpaveza.net/revealing-prototype-pattern-pros-and-cons#comments</comments>
		<pubDate>Tue, 10 Jan 2012 04:45:08 +0000</pubDate>
		<dc:creator>Rob Paveza</dc:creator>
				<category><![CDATA[Computing]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[best practices]]></category>
		<category><![CDATA[Closures]]></category>
		<category><![CDATA[dynamic programming]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[Languages]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[samples]]></category>

		<guid isPermaLink="false">http://robpaveza.net/?p=129</guid>
		<description><![CDATA[A short while ago, I wrote a post generally saying good things about the Revealing Prototype Pattern but mostly focused tearing down the other part that was presented with it, namely the way that variables were declared in a chain separated by the comma operator. This post will discuss some of the pros and cons [...]]]></description>
			<content:encoded><![CDATA[<p>A short while ago, I wrote a post <a href="http://robpaveza.net/defining-variables-in-javascript">generally saying good things about the Revealing Prototype Pattern</a> but mostly focused tearing down the other part that was presented with it, namely the way that variables were declared in a chain separated by the comma operator.  This post will discuss some of the pros and cons of using this pattern, and give some examples about when you should or shouldn't use it.</p>
<h2>Advantages</h2>
<p>As Dan notes in his post, this features a significant improvement over straight prototype assignment (assignment of an object literal to a prototype), in that private visibility is supported.  And because you're still assigning an object to the prototype, you are able to take advantage of prototypal inheritance.  (Next time: How prototypal inheritance really works and how it can make your head explode).</p>
<p>Except for chaining his variable declarations, I have to admit Dan had me pretty well sold on the Revealing Prototype Pattern.  It's very elegant; it provides good protection to its inner variables, and it uses a syntax we've been seeing more and more of ever since jQuery became a popular platform.</p>
<p>Unfortunately, it has some nasty drawbacks.</p>
<h2>Disadvantages</h2>
<p>To be fair, Dan lists some of the disadvantages about this pattern; however, he doesn't quite list them as such, and I think he was possibly unaware of some of their implications:</p>
<blockquote><p>There's something interesting that happens with variables though, especially if you plan on creating more than one Calculator object in a page.  Looking at the public functions you'll see that the 'this' keyword is used to access the currNumberCtl and eqCtl variables defined in the constructor.  This works great since the caller of the public functions will be the Calculator object instance which of course has the two variables defined.  However, when one of the public functions calls a private function such as setVal(), the context of 'this' changes and you'll no longer have access to the two variables.</p></blockquote>
<p>The first time I read through that I glossed over the problems; I didn't quite understand the issue until I wrote some code.  So let's do that - we'll implement the Java <a href="http://docs.oracle.com/javase/1.4.2/docs/api/java/util/StringTokenizer.html" target="_blank">StringTokenizer class</a>:</p>
<pre class="brush: jscript; title: ; notranslate">function StringTokenizer(srcString, delim)
{
    if (typeof srcString === 'undefined')
        throw new ReferenceError(&quot;Parameter 0 'srcString' is required.&quot;);
    if (typeof srcString !== 'string')
        srcString = srcString.toString();
    if (typeof delim !== 'string')
        delim = ' ';

    if (!(this instanceof StringTokenizer))    // enforce constructor usage
        return new StringTokenizer(srcString, delim);

    this.sourceString = srcString;
    this.delimiter = delim;
}
StringTokenizer.prototype = (function()
{
    var that = this;

    var _tokens = that.sourceString.split(that.delimiter);
    var _index = 0;

    var _countTokens = function() { return _tokens.length; };
    var _hasMoreTokens = function() { return _index &lt; _tokens.length; };
    var _nextToken = function()
    {
        if (!_hasMoreTokens())
            return false;

        var next = _tokens[_index];
        _index += 1;
        return next;
    };
    var _reset = function() { _index = 0; };

    var resultPrototype =
    {
        countTokens: _countTokens,
        hasMoreTokens: _hasMoreTokens,
        nextToken: _nextToken,
        reset: _reset
    };
    return resultPrototype;
})();</pre>
<p>If you've ever written a jQuery plugin, you'll probably recognize what I did with the prototype assignment function; when writing jQuery plugins, it's common to close over the current instance of the jQuery object by assigning <tt>var that = $(this);</tt> so that you can write event-handler functions without losing access to the overall context.  Unfortunately, what I did in this case is wrong; you may already see why.</p>
<pre class="brush: jscript; title: ; notranslate">var that = this;</pre>
<p>In this context, <tt>this</tt> is a reference to the global object, not to the instance of the object - even though the prototype is being set.  This is a generalization of what Dan said.  Rewriting it to overcome it results in information leaking:</p>
<pre class="brush: jscript; title: ; notranslate">function StringTokenizer(srcString, delim)
{
    if (typeof srcString === 'undefined')
        throw new ReferenceError(&quot;Parameter 0 'srcString' is required.&quot;);
    if (typeof srcString !== 'string')
        srcString = srcString.toString();
    if (typeof delim !== 'string')
        delim = ' ';

    if (!(this instanceof StringTokenizer))    // enforce constructor usage
        return new StringTokenizer(srcString, delim);

    this.sourceString = srcString;
    this.delimiter = delim;
    this.tokens = srcString.split(delim);
    this.index = 0;
}
StringTokenizer.prototype = (function()
{
    var _countTokens = function() { return this.tokens.length; };
    var _hasMoreTokens = function() { return this.index &lt; this.tokens.length; };
    var _nextToken = function()
    {
        if (!this.hasMoreTokens())
            return false;

        var next = this.tokens[this.index];
        this.index += 1;
        return next;
    };
    var _reset = function() { this.index = 0; };

    var resultPrototype =
    {
        countTokens: _countTokens,
        hasMoreTokens: _hasMoreTokens,
        nextToken: _nextToken,
        reset: _reset
    };
    return resultPrototype;
})();</pre>
<p>The code works correctly; but you can see that we have to make public all of the state variables we'll use in the constructor.  (The alternatives are to either initialize the state variables in each function, where they would still be public; or to create an <tt>init</tt> function, which would still cause the variables to be public AND would require the user to know to call the init function before calling anything else).  </p>
<p>Dan also indicated that you needed a workaround for private functions:</p>
<blockquote><p>There are a few <a href="http://jimmycuadra.com/posts/organizing-javascript-with-namespaces-and-function-prototypes" target="_blank">tricks</a> that can be used to deal with this, but to work around the context change I simply pass “this” from the public functions into the private functions.</p></blockquote>
<p>Personally, I prefer to try to avoid things one might call <a href="http://www.joelonsoftware.com/articles/fog0000000018.html" target="_blank">clever</a> or tricky, because that's code for "so complex you can't understand it".  But even in the case where you have a public function, you'll still get an error <em>if you don't reference it via a public function call</em>.  This error is nonintuitive and could otherwise make you go on a bug hunt for a long time.  Consider this change to the above code:</p>
<pre class="brush: jscript; title: ; notranslate">    var _hasMoreTokens = function() { return this.index &lt; this.tokens.length; };
    var _nextToken = function()
    {
        if (!_hasMoreTokens())   // changed from:   if (!this.hasMoreTokens())
            return false;

        var next = this.tokens[this.index];
        this.index += 1;
        return next;
    };</pre>
<p>Simply removing the 'this' reference <em>in the caller</em> is enough to cause 'this' to go out-of-scope in the <tt>_hasMoreTokens</tt> function.  <strong>This is completely unintuitive behavior for developers who grew up in the classical inheritance model</strong>.</p>
<h2>Alternatives</h2>
<p>I wouldn't want to give you all of these options without giving you an alternative.  The alternative I present here is one in which the entire object is populated in the constructor:</p>
<pre class="brush: jscript; title: ; notranslate">&quot;use strict&quot;;
function StringTokenizer(srcString, delim)
{
    if (typeof srcString === 'undefined')
        throw new ReferenceError(&quot;Parameter 0 'srcString' is required.&quot;);
    if (typeof srcString !== 'string')
        srcString = srcString.toString();
    if (typeof delim !== 'string')
        delim = ' ';

    if (!(this instanceof StringTokenizer))    // enforce constructor usage
        return new StringTokenizer(srcString, delim);

    if (typeof Object.defineProperty !== 'undefined')
    {
        Object.defineProperty(this, 'sourceString', { value: srcString });
        Object.defineProperty(this, 'delimiter', { value: delim });
    }
    else
    {
        this.sourceString = srcString;
        this.delimiter = delim;
    }

    var _tokens = this.sourceString.split(this.delimiter);
    var _index = 0;

    var _countTokens = function() { return _tokens.length; };
    var _hasMoreTokens = function() { return _index &lt; _tokens.length; };
    var _nextToken = function()
    {
        if (!_hasMoreTokens())
            return false;

        var next = _tokens[_index];
        _index += 1;
        return next;
    };
    var _reset = function() { _index = 0; };

    if (typeof Object.defineProperty !== 'undefined')
    {
        Object.defineProperty(this, 'countTokens', { value: _countTokens });
        Object.defineProperty(this, 'hasMoreTokens', { value: _hasMoreTokens });
        Object.defineProperty(this, 'nextToken', { value: _nextToken });
        Object.defineProperty(this, 'reset', { value: _reset });
    }
    else
    {
        this.countTokens = _countTokens;
        this.hasMoreTokens = _hasMoreTokens;
        this.nextToken = _nextToken;
        this.reset = _reset;
    }
}</pre>
<p>The advantage of a structure like this one is that <em>you always have access to <tt>this</tt></em>.  (Note that this example is unnecessarily large because I've taken the additional step of protecting the properties with <tt>Object.defineProperty</tt> where it is supported).  You always have access to private variables and you always have access to the state.  The unfortunate side effect of this strategy is that it doesn't take advantage of prototypal inheritance (it's not that you can't do it with this strategy - more of that coming in the future) and that the entire private and public states (including functions) are closed-over, so you use more memory.  Although, one may ask: is that <em>really</em> such a big deal in THIS sample?</p>
<h2>Usage Considerations</h2>
<p>The Revealing Prototype Pattern can be a good pattern to follow if you're less concerned with maintaining data integrity and state.  You have to be careful with access non-public data and functions with it, but it's pretty elegant; and if you're working on a lot of objects, you have the opportunity to save on some memory usage by delegating the function definitions into the prototype rather than the specific object definition.  It falls short, though, when trying to emulate classical data structures and enforce protection mechanisms.  As such, it can require complicated or clever tricks to work around its shortcomings, which can ultimately lead to overly-complex or difficult-to-maintain code.</p>
<p>Like most patterns, your mileage may vary.</p>
]]></content:encoded>
			<wfw:commentRss>http://robpaveza.net/revealing-prototype-pattern-pros-and-cons/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Defining Variables in JavaScript</title>
		<link>http://robpaveza.net/defining-variables-in-javascript</link>
		<comments>http://robpaveza.net/defining-variables-in-javascript#comments</comments>
		<pubDate>Sat, 07 Jan 2012 00:09:44 +0000</pubDate>
		<dc:creator>Rob Paveza</dc:creator>
				<category><![CDATA[Computing]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[best practices]]></category>
		<category><![CDATA[comma operator]]></category>
		<category><![CDATA[crockford]]></category>
		<category><![CDATA[gotchas]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[Languages]]></category>

		<guid isPermaLink="false">http://robpaveza.net/?p=127</guid>
		<description><![CDATA[I've lately been reviewing different patterns and practices recently, and after reading his article about the Revealing Prototype Pattern, I wanted to take some time to analyze Dan Wahlin's approach to defining variables. It's hard to believe I found some common ground with Douglas Crockford, but as they say about broken clocks.... [Addendum: apparently, since [...]]]></description>
			<content:encoded><![CDATA[<p>I've lately been reviewing different patterns and practices recently, and after reading his article about the Revealing Prototype Pattern, I wanted to take some time to analyze Dan Wahlin's approach to defining variables.  It's hard to believe I found some common ground with Douglas Crockford, but as they say about broken clocks....  <i>[Addendum: apparently, since JSlint says to 'combine with previous var statement,' I don't agree with Crockford.]</i>  Anyway, to begin, this post is inspired by Dan Wahlin's presentation of the <a href="http://weblogs.asp.net/dwahlin/archive/2011/08/03/techniques-strategies-and-patterns-for-structuring-javascript-code-revealing-prototype-pattern.aspx" target="_blank">Revealing Prototype Pattern</a>; I noticed what I thought was a curious way for him to define his private variables, and looking back through his blog posts he discussed it in the original blog post of the series, <a href="http://weblogs.asp.net/dwahlin/archive/2011/07/31/techniques-strategies-and-patterns-for-structuring-javascript-code.aspx">Techniques, Strategies, and Patterns for Structuring JavaScript Code</a>.  For the most part, I like what Dan has to say, but I'm going to have to disagree when it comes to defining variables.</p>
<h3>The Proposition</h3>
<p>As Dan points out, this is the standard way of defining variables in JavaScript:</p>
<pre class="brush: jscript; title: ; notranslate">
var eqCtl;
var currNumberCtl;
var operator;
var operatorSet = false;
var equalsPressed = false;
var lastNumber = null;
</pre>
<p>He advocates trading that for this:</p>
<pre class="brush: jscript; title: ; notranslate">
var eqCtl,
    currNumberCtl,
    operator,
    operatorSet = false,
    equalsPressed = false,
    lastNumber = null;
</pre>
<p>It saves on 20 keystrokes, and he claims improved readability.  Now, I disagree with Crockford's argument that, because JavaScript hoists variables to the top of the function, that you should always declare the variable there.  I believe that, whenever possible, you should try to maximize locality of a variable.  This is a principle discussed in Steve McConnell's <a href="http://www.cc2e.com/" target="_blank">Code Complete</a>; the reasoning behind maximization of locality is that the human brain can only comprehend so much at once.  (This is, of course, another argument in favor of many, simple, and small subroutines).  By delaying the declaration of a variable until it needs to be used, we are able to better-comprehend the meaning of the variable and how its use affects and relates to the rest of the program.  As such, I believe that one of the premises for moving these declarations into a combined var statement - specifically, to reflect the hoisting - is a poor rationale.</p>
<p>Let's carry on.</p>
<h3>Similarities to Other Elements</h3>
<p>In <a href="http://weblogs.asp.net/dwahlin/archive/2011/08/01/techniques-strategies-and-patterns-for-structuring-javascript-code-the-prototype-pattern.aspx" target="_blank">The Prototype Pattern</a>, Dan demonstrates the use of a JavaScript object literal in assignment to the Calculator prototype, so that any object created using the <tt>Calculator</tt> constructor would inherit all of those properties:</p>
<pre class="brush: jscript; title: ; notranslate">
Calculator.prototype = {
    add: function (x, y) {
        return x + y;
    },
    subtract: function (x, y) {
        return x - y;
    },
    multiply: function (x, y) {
        return x * y;
    },
    // ...
};
</pre>
<p>The important thing to note here is that we are simply <i>defining an object literal</i>; we are not writing procedural code, and that comma is not an operator!  It is an important part of the JavaScript grammar, to be sure, but the comma here does not have the same semantic meaning as the comma we saw before.  This subtle difference may lead to coding errors, in which someone who uses comma syntax with both will mistakenly believe they are declaring an object literal and use colons to separate the identifier from the value; or that they are declaring variables and use assignment syntax to separate the property from its value.</p>
<h3>Comma Operator Considered Harmful</h3>
<p>It surprises me to learn that JSlint advocates combining <tt>var</tt> declarations.  Crockford's <a href="http://javascript.crockford.com/style1.html" target="_blank">The Elements of JavaScript Style, Part 1</a> indicates that he isn't terribly fond of it either:</p>
<blockquote><p>The comma operator was borrowed, like much of JavaScript's syntax, from C. The comma operator takes two values and returns the second one. Its presence in the language definition tends to mask certain coding errors, so compilers tend to be blind to some mistakes. It is best to avoid the comma operator, and use the semicolon statement separator instead.</p></blockquote>
<p>Whichever way Crockford prefers it, I think what we need to remember is <i>just because you CAN do something does not mean you SHOULD</i>.  </p>
<p>Let's consider Dan's full body of JavaScript from the Revealing Prototype Pattern.  I'm going to shrink it a little bit, to emphasize the changes I'll make; and I'm removing any of his comments.</p>
<pre class="brush: jscript; title: ; notranslate">
var Calculator = function (cn, eq) {
    this.currNumberCtl = cn;
    this.eqCtl = eq;
};

Calculator.prototype = function () {
    var operator = null,
        operatorSet = false,
        equalsPressed = false,
        lastNumber = null,
        add = function (x, y) { return x + y; },
        subtract = function (x, y) { return x - y; },
        multiply = function (x, y) { return x * y; },
        // I'm going to do something evil here.
        divide = function (x, y) {
            if (y == 0) {
                alert(&quot;Can't divide by 0&quot;);
            }
            return x / y;
        },
        setVal = function (val, thisObj) { thisObj.currNumberCtl.innerHTML = val; },
        setEquation = function (val, thisObj) { thisObj.eqCtl.innerHTML = val; },
        clearNumbers = function () {
            lastNumber = null;
            equalsPressed = operatorSet = false;
            setVal('0',this);
            setEquation('',this);
        },
        setOperator = function (newOperator) {
            if (newOperator == '=') {
                equalsPressed = true;
                calculate(this);
                setEquation('',this);
                return;
            }
            if (!equalsPressed) calculate(this);
            equalsPressed = false;
            operator = newOperator;
            operatorSet = true;
            lastNumber = parseFloat(this.currNumberCtl.innerHTML);
            var eqText = (this.eqCtl.innerHTML == '') ?
                lastNumber + ' ' + operator + ' ' :
                this.eqCtl.innerHTML + ' ' + operator + ' ';
            setEquation(eqText,this);
        },
        numberClick = function (e) {
            var button = (e.target) ? e.target : e.srcElement;
            if (operatorSet == true ||
                this.currNumberCtl.innerHTML == '0') {
                setVal('', this);
                operatorSet = false;
            }
            setVal(this.currNumberCtl.innerHTML + button.innerHTML, this);
            setEquation(this.eqCtl.innerHTML + button.innerHTML, this);
        },
        calculate = function (thisObj) {
            if (!operator || lastNumber == null) return;
            var displayedNumber = parseFloat(thisObj.currNumberCtl.innerHTML),
                newVal = 0;
            switch (operator) {
                case '+':
                    newVal = add(lastNumber, displayedNumber);
                    break;
                case '-':
                    newVal = subtract(lastNumber, displayedNumber);
                    break;
                case '*':
                    newVal = multiply(lastNumber, displayedNumber);
                    break;
                case '/':
                    newVal = divide(lastNumber, displayedNumber);
                    break;
            }
            setVal(newVal, thisObj);
            lastNumber = newVal;
        };
    return {
        numberClick: numberClick,
        setOperator: setOperator,
        clearNumbers: clearNumbers
    };
} ();
</pre>
<p>Note my comment: "I'm going to do something evil here."  Here goes:<br />
<tt>console.log('Hello, world')</tt></p>
<p>Do you see what happened here?  Let me put it in context.</p>
<pre class="brush: jscript; title: ; notranslate">
        subtract = function (x, y) { return x - y; },
        multiply = function (x, y) { return x * y; },
        console.log('Hello, world')
        divide = function (x, y) {
            if (y == 0) {
                alert(&quot;Can't divide by 0&quot;);
            }
            return x / y;
        },
</pre>
<p>JavaScript semicolon insertion blew away the <tt>var</tt> when I inserted any valid statement or expression.  In fact, I could have simply put <tt>'Hello, world!'</tt> or <tt>5</tt> there, on its own line, and because the next line is a valid statement that stands on its own, JavaScript semicolon insertion blew away the <tt>var</tt>.  As such, <tt>divide</tt>, <tt>setVal</tt>, <tt>setEquation</tt>, <tt>clearNumbers</tt>, <tt>setOperator</tt>, <tt>numberClick</tt>, and <tt>calculate</tt> were all just elevated to global scope, possibly blowing away existing variables and leaking a whole bunch of information with them.  This could happen in any instance in which someone mistakenly types a semicolon (let's be honest - JavaScript is a semicolon-terminated language; it will happen somewhat frequently), or if they forget to put a comma at the end of a line.</p>
<p>As such, joining variable declarations together by using the comma operator is inherently an unsafe operation.  You might think of it as a <a href="http://en.wikipedia.org/wiki/Run-on_sentence" target="_blank">run-on sentence</a>; it's not a good thing to do in English, so why would it be good to do in JavaScript or any other programming language?</p>
<p>And if that's not reason enough, here's another: <i>declaring a variable is a statement</i>.  You are stating to the compiler, "I am declaring this variable to be a variable."  Use the <tt>var</tt> statement to make a statement, and use the comma operator to indicate that there are operations.  (Specifically, the one and only place I can think of in which a comma operator would be appropriate is if you need a single for-loop with multiple iterator variables, e.g., <tt>for (var i = 0, j = myArray.length - 1; i = 0; i++, j--)</tt>.  Of course, I don't want to say you should <strong>never</strong> use it, or else I'd be like Crockford with his dogmatic "I have never seen a piece of code that was not improved by refactoring it to remove the <tt>continue</tt> statement," which is patently silly.  </p>
<p>But, beware the comma.  He is correct in that it is easy to mark programming errors with commas.  If you're going to declare a variable, do everyone a favor and declare it, using <tt>var</tt>, make it feel special by giving it its own line and declaration and semicolon.  It will help in maintenance down the line.</p>
]]></content:encoded>
			<wfw:commentRss>http://robpaveza.net/defining-variables-in-javascript/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

