<?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>Cameron McKay</title>
	<atom:link href="http://cdmckay.org/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://cdmckay.org/blog</link>
	<description>Programming and Game Development</description>
	<lastBuildDate>Mon, 14 May 2012 21:11:58 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>Creating ASP.NET HttpCookie-compatible multi-valued cookies in JavaScript</title>
		<link>http://cdmckay.org/blog/2012/02/12/creating-asp-net-httpcookie-compatible-multi-valued-cookies-in-javascript/</link>
		<comments>http://cdmckay.org/blog/2012/02/12/creating-asp-net-httpcookie-compatible-multi-valued-cookies-in-javascript/#comments</comments>
		<pubDate>Sun, 12 Feb 2012 21:40:31 +0000</pubDate>
		<dc:creator>cdmckay</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://cdmckay.org/blog/?p=1969</guid>
		<description><![CDATA[Cookies are ubiquitous on the web. They&#8217;re used to store usernames, login tokens, shopping cart contents, and so on. In libraries, cookies are typically modeled as name-value pairs. An API consumer requests a cookie using a known name (e.g. $.cookie('user') in jQuery with the Cookie plugin) and the library returns a string (e.g. alice). Sometimes, [...]]]></description>
			<content:encoded><![CDATA[<p>Cookies are ubiquitous on the web.  They&#8217;re used to store usernames, login tokens, shopping cart contents, and so on.  In libraries, cookies are typically modeled as name-value pairs.  An API consumer requests a cookie using a known name (e.g. <code>$.cookie('user')</code> in jQuery with the Cookie plugin) and the library returns a string (e.g. <code>alice</code>).  Sometimes, however, just plain old name-value pairs aren&#8217;t enough.  In this article, we will take a look at how to bake multi-valued cookies in JavaScript that are compatible with the <a href="http://msdn.microsoft.com/en-us/library/system.web.httpcookie.values.aspx">Values</a> property of ASP.NET&#8217;s <a href="http://msdn.microsoft.com/en-us/library/system.web.httpcookie.aspx">HttpCookie</a> class.</p>
<p><span id="more-1969"></span></p>
<h3>Serialization</h3>
<p>The .NET HttpCookie class stores multiple values in a single cookie by <a href="http://en.wikipedia.org/wiki/Serialization">serializing</a> them into a single string.  For example, this code:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">HttpCookie cookie <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> HttpCookie<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Cookie1&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
cookie<span style="color: #008000;">.</span><span style="color: #0000FF;">Values</span><span style="color: #008000;">&#91;</span><span style="color: #666666;">&quot;Val1&quot;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;1&quot;</span><span style="color: #008000;">;</span>
cookie<span style="color: #008000;">.</span><span style="color: #0000FF;">Values</span><span style="color: #008000;">&#91;</span><span style="color: #666666;">&quot;Val2&quot;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;2&quot;</span><span style="color: #008000;">;</span>
cookie<span style="color: #008000;">.</span><span style="color: #0000FF;">Values</span><span style="color: #008000;">&#91;</span><span style="color: #666666;">&quot;Val3&quot;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;3&quot;</span><span style="color: #008000;">;</span>
Response<span style="color: #008000;">.</span><span style="color: #0000FF;">Cookies</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>cookie<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>&#8230;will result in a cookie that looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Cookie1<span style="color: #008000;">=</span>Val1<span style="color: #008000;">=</span><span style="color: #FF0000;">1</span><span style="color: #008000;">&amp;</span>Val2<span style="color: #008000;">=</span><span style="color: #FF0000;">2</span><span style="color: #008000;">&amp;</span>Val3<span style="color: #008000;">=</span><span style="color: #FF0000;">3</span></pre></div></div>

<p>Thus, we can see the HttpCookie serializes the Values property in a similar way to how parameters are encoded in query strings.</p>
<h3>The JavaScript (for MS .NET and Mono)</h3>
<p>Based on the example output <code>Cookie1=Val1=1&#038;Val2=2&#038;Val3=3</code>, we can work out some JavaScript code to generate it:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Works with Microsoft .NET and Mono runtimes, with reservations.</span>
<span style="color: #003366; font-weight: bold;">var</span> setMultiValuedCookie <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #000066;">name</span><span style="color: #339933;">,</span> values<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> valuePairs <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> n <span style="color: #000066; font-weight: bold;">in</span> values<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        valuePairs.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>n <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;=&quot;</span> <span style="color: #339933;">+</span> values<span style="color: #009900;">&#91;</span>n<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #003366; font-weight: bold;">var</span> cookieValue <span style="color: #339933;">=</span> valuePairs.<span style="color: #660066;">join</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;&amp;&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    document.<span style="color: #660066;">cookie</span> <span style="color: #339933;">=</span> <span style="color: #000066;">name</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;=&quot;</span> <span style="color: #339933;">+</span> cookieValue<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This is more or less how the Microsoft .NET implementation of HttpCookie works.  It also happens to be compatible with the Mono implementation (more on that below). The problem with this code is that it does not take into account edge cases, such as when a name or value contain the &#8220;=&#8221; or &#8220;&amp;&#8221; characters.  In those cases, things can get weird.  For example, consider this code:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">HttpCookie cookie <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> HttpCookie<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Cookie1&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
cookie<span style="color: #008000;">.</span><span style="color: #0000FF;">Values</span><span style="color: #008000;">&#91;</span><span style="color: #666666;">&quot;Val1&quot;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;1&amp;Val2=2&quot;</span><span style="color: #008000;">;</span>
cookie<span style="color: #008000;">.</span><span style="color: #0000FF;">Values</span><span style="color: #008000;">&#91;</span><span style="color: #666666;">&quot;Val3&quot;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;3&quot;</span><span style="color: #008000;">;</span>
Response<span style="color: #008000;">.</span><span style="color: #0000FF;">Cookies</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>cookie<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>Notice how only two values are set.  Yet, when encoded by Microsoft&#8217;s HttpCookie class the resulting output is <code>Cookie1=Val1=1&#038;Val2=2&#038;Val3=3</code>, the exact same output that results the previous three value example in article.  However, the cookie, when parsed by HttpCookie, will always be interpreted as having 3 values.  This means that Microsoft&#8217;s .NET HttpCookie serialization scheme is ambiguous and care must be taken when using it with non-alphanumeric characters.</p>
<h3>The JavaScript (just for Mono)</h3>
<p>The <a href="https://github.com/mono" title="Mono Project" target="_blank">Mono Project</a>&#8216;s <a href="https://github.com/mono/mono/blob/master/mcs/class/System.Web/System.Web/HttpCookie.cs" title="HttpCookie.cs" target="_blank">HttpCookie class</a> fares a lot better than it&#8217;s Microsoft counterpart.  In the HttpCookie source, there is a nested CookieNVC class (NVC stands for NameValueCollection) with the serialization code in the overridden ToString method:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">override</span> <span style="color: #6666cc; font-weight: bold;">string</span> ToString<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
    StringBuilder builder <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StringBuilder<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #6666cc; font-weight: bold;">bool</span> first_key <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> key <span style="color: #0600FF; font-weight: bold;">in</span> Keys<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">!</span>first_key<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span> 
            builder<span style="color: #008000;">.</span><span style="color: #0000FF;">Append</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;&amp;&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
        <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> vals <span style="color: #008000;">=</span> GetValues<span style="color: #008000;">&#40;</span>key<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>        
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>vals <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
           vals <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #FF0000;">1</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">&#123;</span><span style="color: #6666cc; font-weight: bold;">String</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Empty</span><span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
        <span style="color: #6666cc; font-weight: bold;">bool</span> first_val <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> v <span style="color: #0600FF; font-weight: bold;">in</span> vals<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">!</span>first_val<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
               builder<span style="color: #008000;">.</span><span style="color: #0000FF;">Append</span> <span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;&amp;&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>key <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span> <span style="color: #008000;">&amp;&amp;</span> key<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span> <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
                builder<span style="color: #008000;">.</span><span style="color: #0000FF;">Append</span> <span style="color: #008000;">&#40;</span>HttpUtility<span style="color: #008000;">.</span><span style="color: #0000FF;">UrlEncode</span><span style="color: #008000;">&#40;</span>key<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                builder<span style="color: #008000;">.</span><span style="color: #0000FF;">Append</span> <span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;=&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>v <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span> <span style="color: #008000;">&amp;&amp;</span> v<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span> <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&#123;</span>
                builder<span style="color: #008000;">.</span><span style="color: #0000FF;">Append</span> <span style="color: #008000;">&#40;</span>HttpUtility<span style="color: #008000;">.</span><span style="color: #0000FF;">UrlEncode</span><span style="color: #008000;">&#40;</span>v<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>    
            first_val <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">false</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>        
        first_key <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">false</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">return</span> builder<span style="color: #008000;">.</span><span style="color: #0000FF;">ToString</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p>Notice that in the Mono HttpCookie, the names and values are URL encoded in order to escape the &#8220;=&#8221; and &#8220;&amp;&#8221; characters.  This means that we can use &#8220;=&#8221; and &#8220;&amp;&#8221; characters in the name and value of the Values property and they will be serialized unambiguously.  To make our JavaScript work with the Mono HttpCookie class improvements, the name and value strings must be URL encoded using <code>encodeURIComponent</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Warning: Does not work well with the Microsoft .NET runtime.</span>
<span style="color: #003366; font-weight: bold;">var</span> setMonoMultiValuedCookie <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #000066;">name</span><span style="color: #339933;">,</span> values<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #003366; font-weight: bold;">var</span> valuePairs <span style="color: #339933;">=</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> n <span style="color: #000066; font-weight: bold;">in</span> values<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        valuePairs.<span style="color: #660066;">push</span><span style="color: #009900;">&#40;</span>encodeURIComponent<span style="color: #009900;">&#40;</span>n<span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;=&quot;</span> <span style="color: #339933;">+</span> encodeURIComponent<span style="color: #009900;">&#40;</span>values<span style="color: #009900;">&#91;</span>n<span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #003366; font-weight: bold;">var</span> cookieValue <span style="color: #339933;">=</span> valuePairs.<span style="color: #660066;">join</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;&amp;&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    document.<span style="color: #660066;">cookie</span> <span style="color: #339933;">=</span> <span style="color: #000066;">name</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;=&quot;</span> <span style="color: #339933;">+</span> cookieValue<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></div></div>

<p>And presto, we have a Mono-compatible verison of <code>setMultiValuedCookie</code>.</p>
<h3>Conclusion</h3>
<p>In this article we examined how the Microsoft and Mono versions HttpCookie class serialize multiple values into a single cookie.  By looking at a sample cookies encoded by HttpCookie, as well as perusing the Mono HttpCookie source code, two JavaScript functions were written: <code>setMultiValuedCookie</code>, a function that serializes multi-valued cookies in manner compatible with both Microsoft and Mono .NET runtimes and <code>setMonoMultiValuedCookie</code>, a function that more robustly serializes multi-valued cookies but is only compatible with the Mono .NET runtime.</p>
]]></content:encoded>
			<wfw:commentRss>http://cdmckay.org/blog/2012/02/12/creating-asp-net-httpcookie-compatible-multi-valued-cookies-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introducing CoffeeDOM, a JDOM fork for Java 5</title>
		<link>http://cdmckay.org/blog/2011/05/20/introducing-coffeedom-a-jdom-fork-for-java-5/</link>
		<comments>http://cdmckay.org/blog/2011/05/20/introducing-coffeedom-a-jdom-fork-for-java-5/#comments</comments>
		<pubDate>Fri, 20 May 2011 16:44:26 +0000</pubDate>
		<dc:creator>cdmckay</dc:creator>
				<category><![CDATA[CoffeeDOM]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://cdmckay.org/blog/?p=1881</guid>
		<description><![CDATA[When it comes time to work with XML in Java, the first thing I usually do is go to the JDOM website to check for a Java 5 update. Unfortunately, I am always disappointed. There has not been a major JDOM release in over 6 years and, if the JDOM mailing list is to be [...]]]></description>
			<content:encoded><![CDATA[<p>When it comes time to work with XML in Java, the first thing I usually do is go to <a href="http://jdom.org">the JDOM website</a> to check for a Java 5 update.  Unfortunately, I am always disappointed.  There has not been a major JDOM release in over 6 years and, <a href="http://www.jdom.org/pipermail/jdom-interest/2005-August/014982.html">if the JDOM mailing list is to be believed</a>, no Java 5 version is planned.  As a result, I have decided to take my own initiative and make <a href="http://coffeedom.googlecode.com">CoffeeDOM</a>, a JDOM fork with Java 5 support.</p>
<p>CoffeeDOM is intended as a natural evolution for JDOM developers.  As such, there have been minimal changes to the API.  CoffeeDOM adds support for Java 5 features like generics, enums, and covariant method return types, and reduces the amount of boilerplate required by making previously checked exceptions (like JDOMException) unchecked.  In this article, I will briefly go over these changes.</p>
<p><em>(If you don&#8217;t want to bother with the article, you can skip right to the <a href="http://coffeedom.googlecode.com/">Google Code page</a> or <a href="http://cdmckay.org/coffeedom/apidocs/">browse the Javadoc API documentation</a>.)</em></p>
<p><span id="more-1881"></span></p>
<h3>Generic collections</h3>
<p>JDOM makes heavy use of the <a href="http://download.oracle.com/javase/tutorial/collections/index.html">Java Collections Framework</a>, principally Lists and Iterators.  Thus, in JDOM, to get a list of all child elements of an element, we do the following:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">Element</span> element <span style="color: #339933;">=</span> ...<span style="color: #339933;">;</span>
List<span style="color: #339933;">&lt;?&gt;</span> children <span style="color: #339933;">=</span> element.<span style="color: #006633;">getChildren</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> childObject <span style="color: #339933;">:</span> children<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// Cast :(</span>
    <span style="color: #003399;">Element</span> child <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Element</span><span style="color: #009900;">&#41;</span> childObject<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// ...</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>See that pesky cast?  How inconvenient.  Another approach is to cast the List:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">Element</span> element <span style="color: #339933;">=</span> ...<span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// Cast :(</span>
List<span style="color: #339933;">&lt;</span>Element<span style="color: #339933;">&gt;</span> children <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>List<span style="color: #339933;">&lt;</span>Element<span style="color: #339933;">&gt;</span><span style="color: #009900;">&#41;</span> element.<span style="color: #006633;">getChildren</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Element</span> child <span style="color: #339933;">:</span> children<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// ...</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>&#8230; but then we would need to either ignore a warning (not recommended) or add a <code>@SuppressWarnings("unchecked")</code> annotation.  Neither is a desirable solution.</p>
<p>Fortuantely, CoffeeDOM comes to the rescue.  In CoffeeDOM, all JCF classes like List, Collection, Iterable, etc. have appropriate generic parameters:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">Element</span> element <span style="color: #339933;">=</span> ...<span style="color: #339933;">;</span>
List<span style="color: #339933;">&lt;</span>Element<span style="color: #339933;">&gt;</span> children <span style="color: #339933;">=</span> element.<span style="color: #006633;">getChildren</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Element</span> child <span style="color: #339933;">:</span> children<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// ...</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Enjoy the comfort of compile time type-checking.</p>
<h3>Covariant method return types</h3>
<p>In JDOM, in order to copy nodes, the built-in <code>Object#clone()</code> method is used:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">Element</span> element <span style="color: #339933;">=</span> ...<span style="color: #339933;">;</span>
<span style="color: #003399;">Element</span> clonedElement <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Element</span><span style="color: #009900;">&#41;</span> element.<span style="color: #006633;">clone</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Oh look, another silly cast.  Fortunately, thanks to covariant method return types, CoffeeDOM eliminates this unneeded cast:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">Element</span> element <span style="color: #339933;">=</span> ...<span style="color: #339933;">;</span>
<span style="color: #003399;">Element</span> clonedElement <span style="color: #339933;">=</span> element.<span style="color: #006633;">clone</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>CoffeeDOM also removes the need for casting when using <code>detach</code>, <code>setParent</code> and <code>getParent</code> (in most cases).</p>
<h3>Enums instead of int constants</h3>
<p>This one is pretty straightforward.  In JDOM, when we make a new Attribute, we can set the attribute type using an int constant like <code>Attribute.CDATA_TYPE</code>, <code>Attribute.ENTITIES_TYPE</code>, etc.  Here&#8217;s a (contrived) example:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">Element</span> element <span style="color: #339933;">=</span> ...<span style="color: #339933;">;</span>
<span style="color: #003399;">Attribute</span> attribute <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Attribute</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;name&quot;</span>, <span style="color: #0000ff;">&quot;value&quot;</span>, 
        <span style="color: #003399;">Attribute</span>.<span style="color: #006633;">UNDECLARED</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
element.<span style="color: #006633;">setAttribute</span><span style="color: #009900;">&#40;</span>attribute<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #666666; font-style: italic;">// ...or just element.setAttribute(&quot;name&quot;, &quot;value&quot;)</span></pre></div></div>

<p>Unfortunately, modern IDEs have issues with int constants (they can&#8217;t tell which ones go with a particular method).  Moreover, operations like iterating through the enum or converting from a string to a constant, are more difficult and messy.</p>
<p>CoffeeDOM remedies this by using Java 5&#8242;s enum structure.  The above code turns into something rather similar:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">Element</span> element <span style="color: #339933;">=</span> ...<span style="color: #339933;">;</span>
<span style="color: #003399;">Attribute</span> attribute <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Attribute</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;name&quot;</span>, <span style="color: #0000ff;">&quot;value&quot;</span>, 
        <span style="color: #003399;">Attribute</span>.<span style="color: #006633;">Type</span>.<span style="color: #006633;">UNDECLARED</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
element.<span style="color: #006633;">setAttribute</span><span style="color: #009900;">&#40;</span>attribute<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>&#8230;but with the added plus that we can do things like:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Cycle through the constants.</span>
<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">Attribute</span>.<span style="color: #006633;">Type</span> type <span style="color: #339933;">:</span> <span style="color: #003399;">Attribute</span>.<span style="color: #006633;">Type</span>.<span style="color: #006633;">values</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    ...
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Get a constant from a string.</span>
<span style="color: #003399;">Attribute</span>.<span style="color: #006633;">Type</span> type <span style="color: #339933;">=</span> <span style="color: #003399;">Attribute</span>.<span style="color: #006633;">Type</span>.<span style="color: #006633;">valueOf</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;UNDECLARED&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<h3>Improved for-each compatibility</h3>
<p>In Java 5, Sun juiced up the for loop by enabling it to cycle through Iterable instances.  Unfortunately, since JDOM predated this enhancement, some methods return for loop unfriendly Iterator instances.  This results in a lot of unneeded boilerplate:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">Element</span> element <span style="color: #339933;">=</span> ...<span style="color: #339933;">;</span>
Iterator<span style="color: #339933;">&lt;?&gt;</span> it <span style="color: #339933;">=</span> element.<span style="color: #006633;">getDescendants</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span>it.<span style="color: #006633;">hasNext</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    Content descendant <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>Content<span style="color: #009900;">&#41;</span> it.<span style="color: #006633;">next</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #666666; font-style: italic;">// ...</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>CoffeeDOM corrects this by making <code>getDescendants</code> return an Iterable instance instead, allowing it to be used with the for loop:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #003399;">Element</span> element <span style="color: #339933;">=</span> ...<span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span>Content descendant <span style="color: #339933;">:</span> element.<span style="color: #006633;">getDescendants</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">// ...</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This change only affects classes implementing the JDOM Parent interface.</p>
<h3>Unchecked exceptions</h3>
<p>Constantly having to write exception checking code in Java can obfuscate code, especially if you&#8217;re just only re-throwing or logging checked exceptions to make the compiler happy.  Consider this example in JDOM:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
    SAXBuilder builder <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> SAXBuilder<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #003399;">Document</span> document <span style="color: #339933;">=</span> builder.<span style="color: #006633;">build</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;path/to/file.xml&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    XMLOutputter outputter <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> XMLOutputter<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    outputter.<span style="color: #006633;">output</span><span style="color: #009900;">&#40;</span>doc, <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">IOException</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    e.<span style="color: #006633;">printStackTrace</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span>JDOMException e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    e.<span style="color: #006633;">printStackTrace</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>To address this issue, CoffeeDOM changes CoffeeDOMException (the CoffeeDOM equivalent to JDOMException) to an unchecked exception.  This reduces some of the exception noise:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// Ahhh... fewer checked exceptions.</span>
<span style="color: #000000; font-weight: bold;">try</span> <span style="color: #009900;">&#123;</span>
    SAXBuilder builder <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> SAXBuilder<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #003399;">Document</span> document <span style="color: #339933;">=</span> builder.<span style="color: #006633;">build</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;path/to/file.xml&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    XMLOutputter outputter <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> XMLOutputter<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    outputter.<span style="color: #006633;">output</span><span style="color: #009900;">&#40;</span>doc, <span style="color: #003399;">System</span>.<span style="color: #006633;">out</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>  <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">IOException</span> e<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    e.<span style="color: #006633;">printStackTrace</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h3>Now with less noise</h3>
<p>CoffeeDOM was designed to be an evolutionary step forward for JDOM.  The main design goal of CoffeeDOM was to build on the excellent JDOM API by using modern Java features like generics, enums and covariance method return types.  The result is better compile-time checking, fewer casts and less annoying exception handling.</p>
<h3>Where do I get it? When can I use it?</h3>
<p>CoffeeDOM is available now via Google Code as <a href="http://code.google.com/p/coffeedom/downloads/list">a downloadable JAR file</a> or <a href="http://code.google.com/p/coffeedom/source/browse/">a Mercurial repository</a>.  It is also available from Maven Central using the following dependency markup:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>org.cdmckay.coffeedom<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/groupId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>coffeedom<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/artifactId<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
  <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>1.0.0<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/version<span style="color: #000000; font-weight: bold;">&gt;</span></span></span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/dependency<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>

<h3>Learn more</h3>
<p>As CoffeeDOM is brand new, there isn&#8217;t a whole lot of documentation available beyond <a href="http://cdmckay.org/coffeedom/apidocs/">the Javadoc reference</a> and this article.  However, since CoffeeDOM shares a similar API to JDOM, any JDOM tutorial can make a good starting point.  See <a href="http://www.jdom.org/downloads/docs.html">the JDOM documentation page</a> for links to several tutorials that can get you started.</p>
<p>If code samples are your thing, the CoffeeDOM Mercurial repository has a <a href="http://code.google.com/p/coffeedom/source/browse/#hg%2FCoffeeDOM-samples">CoffeeDOM-samples</a> project that contains all the JDOM sample projects updated for CoffeeDOM.</p>
]]></content:encoded>
			<wfw:commentRss>http://cdmckay.org/blog/2011/05/20/introducing-coffeedom-a-jdom-fork-for-java-5/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>Things I miss from Java while programming in C#</title>
		<link>http://cdmckay.org/blog/2011/05/02/things-i-miss-from-java-while-programming-in-c/</link>
		<comments>http://cdmckay.org/blog/2011/05/02/things-i-miss-from-java-while-programming-in-c/#comments</comments>
		<pubDate>Mon, 02 May 2011 22:19:17 +0000</pubDate>
		<dc:creator>cdmckay</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Programming Languages]]></category>

		<guid isPermaLink="false">http://cdmckay.org/blog/?p=1841</guid>
		<description><![CDATA[One of the perks of being a freelance programmer is that I get to program in a lot of different languages, either because the client has dictated a certain language, has left the choice up to me, or limited me by what is supported by a host (Hi PHP!). As fate would have it, I [...]]]></description>
			<content:encoded><![CDATA[<p>One of the perks of being a freelance programmer is that I get to program in a lot of different languages, either because the client has dictated a certain language, has left the choice up to me, or limited me by what is supported by a host (Hi PHP!).</p>
<p>As fate would have it, I have had the good fortune to have extensive experience with both C# and Java.  While many articles will list things a programmer misses from C# while coding in Java (properties, LINQ, reified generics, type inference, named and optional parameters, closures, continuations), this post intends to look at things a Java programmer might miss while coding in C#.</p>
<p><span id="more-1841"></span></p>
<h3>1. Method return type covariance</h3>
<p>Covariant method return types are one of the lesser known Java features (see <a href="http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.5">Section 8.4.5 in the JLS</a>).  Basically, Java allows you to narrow the return type of a method when overriding it in a sub-class.  For example:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Foo <span style="color: #009900;">&#123;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SubFoo <span style="color: #000000; font-weight: bold;">extends</span> Foo <span style="color: #009900;">&#123;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> Bar <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">final</span> Foo foo <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Foo<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> Foo getFoo<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> foo<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> SubBar <span style="color: #000000; font-weight: bold;">extends</span> Bar <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">final</span> SubFoo subFoo <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> SubFoo<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> SubFoo getFoo<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> subFoo<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Although situations where this is needed are seldom, it is a nice feature to have when you need it.  An good example of its usage is in the <a href="http://wicket.apache.org">Apache Wicket framework</a>.  All pages in Wicket typically derive from the <a href="http://wicket.apache.org/apidocs/1.4/org/apache/wicket/markup/html/WebPage.html">WebPage</a> class.  Thus, when you want to access information from a custom Wicket session you need to do something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> UserInfoPage <span style="color: #000000; font-weight: bold;">extends</span> WebPage <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> UserInfoPage<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        FooSession session <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>FooSession<span style="color: #009900;">&#41;</span> getSession<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #003399;">String</span> userName <span style="color: #339933;">=</span> session.<span style="color: #006633;">getUserName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        ...
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>However, if you add a class above <code>UserInfoPage</code> called <code>FooPage</code>, you can use a covariant return type to eliminate the unsightly cast:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> FooPage <span style="color: #000000; font-weight: bold;">extends</span> WebPage <span style="color: #009900;">&#123;</span>
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> FooSession getSession<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #009900;">&#40;</span>FooSession<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">super</span>.<span style="color: #006633;">getSession</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> UserInfoPage <span style="color: #000000; font-weight: bold;">extends</span> FooPage <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> UserInfoPage<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        FooSession session <span style="color: #339933;">=</span> getSession<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #003399;">String</span> userName <span style="color: #339933;">=</span> session.<span style="color: #006633;">getUserName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        ...
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>To me this is preferable to adding another method called <code>getFooSession()</code>.  Having two methods can be confusing to a future maintainer (do I want <code>getFooSession()</code> or <code>getSession()</code>? What&#8217;s the difference?) and needlessly clutters your IDE&#8217;s code completion.</p>
<p>There is no equivalent in C#, short of adding a method.  Will C# ever support such a feature?   It&#8217;s hard to say, but probably not anytime soon.  There has been <a href="http://connect.microsoft.com/VisualStudio/feedback/details/90909/need-covariant-return-types-in-c-all-net-langage">a request for covariant method return types since 2004</a>.  Microsoft response then was:</p>
<blockquote><p>We hear this request a lot. We&#8217;ll consider it for the next release.</p></blockquote>
<p>After seven years and three major C# releases, it looks like they&#8217;re still considering it.</p>
<h3>2. Class-like enums</h3>
<p>This one is not a big surprise, as it is typically mentioned as one of the few things that Java has done better that C#.  In C#, enums are basically glorified integral types.  As such, they can&#8217;t contain any extra data without using attributes.  While attributes are nice, accessing them requires quite a bit of boilerplate.</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">enum</span> MotionType <span style="color: #008000;">&#123;</span>
    Stationary,
    Walking,
    Running,
    <span style="color: #008000;">&#91;</span>Description<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Time Travelling&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#93;</span>,
    TimeTravelling
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #008000;">...</span>
&nbsp;
<span style="color: #0000FF;">MotionType</span> type <span style="color: #008000;">=</span> MotionType<span style="color: #008000;">.</span><span style="color: #0000FF;">TimeTravelling</span><span style="color: #008000;">;</span>
var description <span style="color: #008000;">=</span> type
    <span style="color: #008000;">.</span><span style="color: #0000FF;">GetType</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">.</span><span style="color: #0000FF;">GetField</span><span style="color: #008000;">&#40;</span>type<span style="color: #008000;">.</span><span style="color: #0000FF;">ToString</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">.</span><span style="color: #0000FF;">GetCustomAttributes</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>DescriptionAttribute<span style="color: #008000;">&#41;</span>, <span style="color: #0600FF; font-weight: bold;">false</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">.</span><span style="color: #0000FF;">Cast</span><span style="color: #008000;">&lt;</span>DescriptionAttribute<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">.</span><span style="color: #0000FF;">First</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">.</span><span style="color: #0000FF;">Description</span><span style="color: #008000;">;</span>
Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>description<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>A further restriction of C# enums if that they can&#8217;t be used as a generic constraint.  For example, the following code would not compile:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> Monster<span style="color: #008000;">&lt;</span>TMotionType<span style="color: #008000;">&gt;</span> <span style="color: #0600FF; font-weight: bold;">where</span> TMotionType <span style="color: #008000;">:</span> <span style="color: #6666cc; font-weight: bold;">enum</span> <span style="color: #008000;">&#123;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>

<p><a href="https://msmvps.com/blogs/jon_skeet/archive/2009/09/10/generic-constraints-for-enums-and-delegates.aspx">According to C# MVP Jon Skeet</a>, this is not a restriction of the CLR, but is actually a restriction of the Microsoft C# compiler.  The best you can do to work around this is to use the broader constraint <code>where : struct</code>, or the <a href="http://code.google.com/p/unconstrained-melody/">Unconstrained Melody library</a>.</p>
<p>Java enums, on the other hand, are specialized classes.  Like C# enums, Java enums can be used with <code>switch</code> statements and be converted to integral types.  However, Java enums go far beyond these simple uses.  Java enums can have instance fields, instance methods and even per-constant methods.    Java generics can also be constrained to take only enums.  </p>
<p>Here&#8217;s how the <code>MotionType</code> enum could be written in Java (notice how easy it is to get the description in this case):</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">enum</span> MotionType <span style="color: #009900;">&#123;</span>
    STATIONARY<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Stationary&quot;</span><span style="color: #009900;">&#41;</span>,
    WALKING<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Walking&quot;</span><span style="color: #009900;">&#41;</span>,
    RUNNING<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Running&quot;</span><span style="color: #009900;">&#41;</span>,
    TIME_TRAVELLING<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Time Travelling&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">final</span> <span style="color: #003399;">String</span> description<span style="color: #339933;">;</span>
    MotionType<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> description<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">description</span> <span style="color: #339933;">=</span> description<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
...
&nbsp;
<span style="color: #006633;">MotionType</span> type <span style="color: #339933;">=</span> MotionType.<span style="color: #006633;">TIME_TRAVELLING</span><span style="color: #339933;">;</span>
<span style="color: #003399;">System</span>.<span style="color: #006633;">out</span>.<span style="color: #006633;">println</span><span style="color: #009900;">&#40;</span>type.<span style="color: #006633;">description</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This is just scratching the surface of Java enum capabilities.  I highly recommend reading Chapter 6 of Effective Java or <a href="http://download.oracle.com/javase/1.5.0/docs/guide/language/enums.html">the Oracle enum documentation</a>.</p>
<h3>3. Anonymous inner classes</h3>
<p>This is another it&#8217;s-useful-when-you-need-it feature of Java that C# mostly addresses with events and delegates.  The most common situation for anonymous inner classes in Java is for listeners:</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;">Widget widget <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Widget<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> onInteraction<span style="color: #009900;">&#40;</span>WidgetState state<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        ...
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></div></div>

<p>In C#, this is handled using events and delegates:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Widget widget <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Widget<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
widget<span style="color: #008000;">.</span><span style="color: #0000FF;">Interaction</span> <span style="color: #008000;">+=</span> state <span style="color: #008000;">=&gt;</span> <span style="color: #008000;">&#123;</span>
    <span style="color: #008000;">...</span>
<span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span></pre></div></div>

<p>The C# approach is superior in most cases.  There&#8217;s far less clutter and it&#8217;s a lot easier to add listener support to a class in C#.  Furthermore, since it&#8217;s a language feature, you can count on it being more or less the same everywhere.  However, it&#8217;s not without drawbacks.  You&#8217;ll notice in the previous Java example, we can guarantee that there is only one listener.  Furthermore, if we declare <code>onInteraction</code> as abstract, we can also ensure that all concrete implementations of <code>Widget</code> have an <code>onInteraction</code> handler.  The event/delegate approach as written cannot make the same guarantees.</p>
<p>Since C# does not support anonymous inner classes, the best we can do to emulate them is something like this:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Widget widget <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Widget<span style="color: #008000;">&#40;</span>state <span style="color: #008000;">=&gt;</span> <span style="color: #008000;">&#123;</span>
    <span style="color: #008000;">...</span>
<span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>&#8230;or, if we wanted to make it a little more clear, we could use named parameters:</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">Widget widget <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Widget<span style="color: #008000;">&#40;</span>onInteraction<span style="color: #008000;">:</span> state <span style="color: #008000;">=&gt;</span> <span style="color: #008000;">&#123;</span>
    <span style="color: #008000;">...</span>
<span style="color: #008000;">&#125;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<h3>Locally scoped final/readonly variables</h3>
<p><a href="http://www.cc2e.com/">In the book Code Complete 2</a>, Steve McConnell recommends that you use final keyword whenever possible.  The justification for this being that less mutable code is easier to keep track of mentally and less likely to be accidentally modified.  Although the practice of making everything final can be weird at first, you eventually become so used to using final that you start to feel a little bit exposed whenever a variable isn&#8217;t marked final.</p>
<p>C# has a nearly equivalent keyword to <code>final</code>: <code>readonly</code>.  However, for some reason, readonly is only usable on the field level.  In the local scope, there is no direct equivalent to final in C#.  The best you can do is use <code>const</code>, but this only works with compile-time constants, so</p>

<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">const</span> <span style="color: #6666cc; font-weight: bold;">string</span> foo <span style="color: #008000;">=</span> Foo<span style="color: #008000;">.</span><span style="color: #0000FF;">getString</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>

<p>&#8230;won&#8217;t work.</p>
<h3>Conclusion</h3>
<p>In this article we looked at four features of Java that lack direct C# equivalents: covariant method return types, class-like enums, anonymous inner classes and locally-scoped final/readonly keywords.  C# is often thought of as a &#8220;better Java&#8221;.  However, as this article has shown, this is not true.  Java may not have as many bells and whistles as its newer cousin, but it still offers some compelling features that may never find their way into C#.</p>
]]></content:encoded>
			<wfw:commentRss>http://cdmckay.org/blog/2011/05/02/things-i-miss-from-java-while-programming-in-c/feed/</wfw:commentRss>
		<slash:comments>41</slash:comments>
		</item>
		<item>
		<title>Eager boolean operators in JavaScript</title>
		<link>http://cdmckay.org/blog/2010/09/09/eager-boolean-operators-in-javascript/</link>
		<comments>http://cdmckay.org/blog/2010/09/09/eager-boolean-operators-in-javascript/#comments</comments>
		<pubDate>Thu, 09 Sep 2010 06:22:11 +0000</pubDate>
		<dc:creator>cdmckay</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://cdmckay.org/blog/?p=1741</guid>
		<description><![CDATA[In most programming languages like Java, JavaScript, C and C#, the boolean operators &#038;&#038; and &#124;&#124; perform short-circuited evaluation. Essentially, this means that a program, when evaluating boolean operators, will only evaluate as many arguments as is necessary to determine the value of a boolean expression. Sometimes, however, this is not the behaviour we want. [...]]]></description>
			<content:encoded><![CDATA[<p>In most programming languages like Java, JavaScript, C and C#, the boolean operators <code>&#038;&#038;</code> and <code>||</code> perform <a href="http://en.wikipedia.org/wiki/Short-circuit_evaluation">short-circuited evaluation</a>. Essentially, this means that a program, when evaluating boolean operators, will only evaluate as many arguments as is necessary to determine the value of a boolean expression.  Sometimes, however, this is not the behaviour we want.</p>
<p>In this article we will look at how to implement non-short-circuited or &#8220;eager&#8221; versions of the JavaScript boolean operators <code>&#038;&#038;</code> and <code>||</code>.</p>
<p><span id="more-1741"></span></p>
<p>As mentioned earlier, most programming languages have short-circuited boolean operators. Short-circuited operators are possible due to certain properties of conjunctions and disjunctions in Boolean logic.  In Boolean logic, for a conjunction <code>x1 &#038;&#038; x2</code>, if the first argument evaluates to false, the whole expression will be false, regardless of what the other argument evaluates to.  Similarly, for a disjunction <code>x1 || x2</code>, if the first argument evaluates to true, the whole expression will be true, regardless of what the other argument evaluates to.</p>
<p>For a more concrete example, consider this snippet of JavaScript:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> str <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #339933;">;</span>
<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>str <span style="color: #339933;">!==</span> <span style="color: #003366; font-weight: bold;">null</span> <span style="color: #339933;">&amp;&amp;</span> str.<span style="color: #660066;">length</span> <span style="color: #339933;">&gt;</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;String is not null or empty&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;String is null or empty&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>If executed by a browser, this snippet will alert <code>String is null or empty</code>.  It does not throw a <code>TypeError</code> when it hits <code>str.length</code> because <code>str.length</code> is never evaluated.  The JavaScript interpreter skips it once it sees <code>str !== null</code> evaluates to false.  This is an advantage of short-circuiting.</p>
<h3>What if we don&#8217;t want to short the circuit?</h3>
<p>Although short-circuiting is almost always what we want, there are rare instances where we may want to have non-short-circuited or <strong>eager</strong> evaluation.  Consider this example using jQuery:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> validate <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>element<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>element.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">===</span> <span style="color: #3366CC;">&quot;&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        element.<span style="color: #660066;">addClass</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;invalid&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
        element.<span style="color: #660066;">removeClass</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;highlight&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">true</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">var</span> form <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#comments-form&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> <span style="color: #000066;">name</span> <span style="color: #339933;">=</span> form.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#name&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> email <span style="color: #339933;">=</span> form.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#email&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> comments <span style="color: #339933;">=</span> form.<span style="color: #660066;">find</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#comments&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
form.<span style="color: #660066;">submit</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">return</span> validate<span style="color: #009900;">&#40;</span><span style="color: #000066;">name</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span> validate<span style="color: #009900;">&#40;</span>email<span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span> validate<span style="color: #009900;">&#40;</span>comments<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>In this example, we are validating a comments form for a website.  In order to do that, we use a <code>validate</code> function to verify that an HTML input is not empty.  If it is empty, then we add a CSS class to highlight it and then return false to indicate validation failed.  Conversely, if it&#8217;s not empty, we remove the highlight CSS class and then return true to indicate validation succeeded.</p>
<p>Unfortunately, this code will only highlight the first field that fails validation.  Why?  Because the <code>&#038;&#038;</code> short-circuits the first time it evaluates an argument to false and thus the rest of the validations will not be executed.</p>
<p>So how do we force them run?  Well, if we were using a language like Java or C#, we would simply use the <code>&#038;</code> and <code>|</code> operators, which are eager versions of the short-circuited <code>&#038;&#038;</code> and <code>||</code> operators.  Unfortunately, although JavaScript does provide the <code>&#038;</code> and <code>|</code> operators, they return numeric (0 or 1) instead of boolean (true or false) results.</p>
<h3>Eager boolean operators in JavaScript</h3>
<p><em>(Aside: In the following section I use the arithmetic operators <code>*</code> and <code>+</code> to emulate eager boolean operators.  You can just as easily use the bitwise operators <code>&#038;</code> and <code>|</code> in their place.  The only reason I used the arithmetic operators was because I thought they would make for a more interesting article).</em></p>
<p>So we&#8217;ve established that JavaScript has no eager boolean operators.  JavaScript does, however, offer us two arithmetic operators that can almost accomplish our goal: <code>*</code> and <code>+</code>.  These operators, in conjunction with JavaScript&#8217;s type coercion semantics, produce the following truth tables when fed all combinations of true and false (<code>&#038;&#038;</code> and <code>||</code> are shown for comparison):</p>
<table>
<tr>
<th>a</th>
<th>b</th>
<th>a &#038;&#038; b</th>
<th>a * b</th>
<th>a || b</th>
<th>a + b</th>
</tr>
<tr>
<td>false</td>
<td>false</td>
<td>false</td>
<td>0</td>
<td>false</td>
<td>0</td>
</tr>
<tr>
<td>false</td>
<td>true</td>
<td>false</td>
<td>0</td>
<td>true</td>
<td>1</td>
</tr>
<tr>
<td>true</td>
<td>false</td>
<td>false</td>
<td>0</td>
<td>true</td>
<td>1</td>
</tr>
<tr>
<td>true</td>
<td>true</td>
<td>true</td>
<td>1</td>
<td>true</td>
<td>2</td>
</tr>
</table>
<p>In the table you&#8217;ll notice that <code>*</code> and <code>+</code> operators yield almost identical truth tables to the <code>&#038;&#038;</code> and <code>||</code> operators, with the exception being that the short-circuited operators produce boolean values (true and false) while the arithmetic operators produce integer values (0, 1 or 2).  Moreover, unlike the boolean operators, the arithmetic operators are eager.</p>
<p>That means that, in order to use the arithmetic operators to implement eager boolean operators that produce the exact same results as the built-in boolean operators, we need to map 0 to false and map any non-0 values to true.  Fortunately, this is exactly what JavaScript&#8217;s type coercion does when forced to coerce a number into a boolean, which can be accomplished by prefixing the number with two <code>!</code> operators.</p>
<table>
<tr>
<th>a</th>
<th>b</th>
<th>a &#038;&#038; b</th>
<th>!!(a * b)</th>
<th>a || b</th>
<th>!!(a + b)</th>
</tr>
<tr>
<td>false</td>
<td>false</td>
<td>false</td>
<td>false</td>
<td>false</td>
<td>false</td>
</tr>
<tr>
<td>false</td>
<td>true</td>
<td>false</td>
<td>false</td>
<td>true</td>
<td>true</td>
</tr>
<tr>
<td>true</td>
<td>false</td>
<td>false</td>
<td>false</td>
<td>true</td>
<td>true</td>
</tr>
<tr>
<td>true</td>
<td>true</td>
<td>true</td>
<td>true</td>
<td>true</td>
<td>true</td>
</tr>
</table>
<p>And there we have it.  We&#8217;ve implemented eager boolean operators using JavaScript&#8217;s type coercion, the arithmetic operators <code>*</code> and <code>+</code> and the logical not operator <code>!</code>.</p>
<h3>Conclusion</h3>
<p>Boolean operators in most programming languages are short-circuited: they evaluate their terms left to right and stop (i.e. short-circuit) once they can definitively determine the truth value of expression. This behaviour is usually what we want.  However, in some rare cases, we want to evaluate all terms in a boolean expression.  Such an operator is called an eager boolean operator.</p>
<p>Although JavaScript does not provide eager boolean operators, they can be emulated by using a combination of JavaScript&#8217;s type coercion semantics and arithmetic and logical operators.</p>
]]></content:encoded>
			<wfw:commentRss>http://cdmckay.org/blog/2010/09/09/eager-boolean-operators-in-javascript/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>How to do an AJAX search with jQTouch, Part 2</title>
		<link>http://cdmckay.org/blog/2010/07/31/how-to-do-an-ajax-search-with-jqtouch-part-2/</link>
		<comments>http://cdmckay.org/blog/2010/07/31/how-to-do-an-ajax-search-with-jqtouch-part-2/#comments</comments>
		<pubDate>Sat, 31 Jul 2010 15:53:25 +0000</pubDate>
		<dc:creator>cdmckay</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://cdmckay.org/blog/?p=1667</guid>
		<description><![CDATA[In the last installment of How to do an AJAX search with jQTouch we looked at how to setup a jQTouch interface with the goal of performing an AJAX search. In this article, we will write the necessary JavaScript to perform that AJAX search, as well as a PHP script to respond to those calls. [...]]]></description>
			<content:encoded><![CDATA[<p>In the last installment of <a href="http://cdmckay.org/blog/2010/04/22/how-to-do-an-ajax-search-with-jqtouch-part-1/">How to do an AJAX search with jQTouch</a> we looked at how to setup a jQTouch interface with the goal of performing an AJAX search. In this article, we will write the necessary JavaScript to perform that AJAX search, as well as a PHP script to respond to those calls.</p>
<p>This article assumes you have read <a href="http://cdmckay.org/blog/2010/04/22/how-to-do-an-ajax-search-with-jqtouch-part-1/">the first part of this series</a>.</p>
<p><span id="more-1667"></span></p>
<p>Before we start, we should take a step back and consider what we&#8217;re about to do.  Our Searcher app has three parts:</p>
<ul>
<li>the client-side jQTouch UI,</li>
<li>the client-side jQuery AJAX calls,</li>
<li>the server-side PHP script (that could easily be backed by a database)</li>
</ul>
<p>At this point we have finished the jQTouch UI.  However, instead of immediately moving on to writing the jQuery AJAX calls, let&#8217;s start with the PHP script instead.  This will help us understand our AJAX calls when it comes time to write them.</p>
<h3>The PHP Script</h3>
<p>Since our PHP script will be performing a search, let&#8217;s create a file called <code>search.php</code> and add a single line of boilerplate:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span></pre></div></div>

<p>There&#8217;s no need for an end tag.  In fact, in files containing only PHP, <a href="http://framework.zend.com/manual/en/coding-standard.php-file-formatting.html">it is recommended that you do not include an end tag</a>:</p>
<blockquote><p>For files that contain only PHP code, the closing tag (&#8220;?&gt;&#8221;) is never permitted. It is not required by PHP, and omitting it prevents the accidental injection of trailing white space into the response.</p></blockquote>
<p>Our Searcher app needs to search for something, so let&#8217;s pretend it&#8217;s an interface for a music player and we&#8217;re searching for songs. In order to express that idea into PHP code, we need the following elements:</p>
<ul>
<li>a Song class to hold the artist name and the title,</li>
<li>an array holding a bunch of Song objects,</li>
<li>a function for searching the Song array,</li>
<li>a way to get a search value from the AJAX request,</li>
<li>a way to set the MIME type to JSON,</li>
<li>a way to encode our Song array as JSON</li>
</ul>
<p>First, we&#8217;ll need a class to hold the songs (place this starting at line 3 in <code>search.php</code>):</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Song <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000088;">$artist</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000088;">$title</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span><span style="color: #000088;">$artist</span><span style="color: #339933;">,</span> <span style="color: #000088;">$title</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">artist</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$artist</span><span style="color: #339933;">;</span>
        <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">title</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$title</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Let&#8217;s break it down for those not familiar with PHP classes:</p>
<ul>
<li>at line 3, we declare the class name</li>
<li>at lines 4-5, we declare two public fields to represent the artist&#8217;s name and the title of the song,</li>
<li>at lines 7-10, we declare the class constructor that we use to initialize the two fields of a Song object</li>
</ul>
<p>Now that we have a way to model songs in our PHP script, we need to make an array of some dummy songs that we can query using AJAX:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>13
14
15
16
17
18
19
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$songs</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
    <span style="color: #000000; font-weight: bold;">new</span> Song<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Weezer&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;Say It Ain't So&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
    <span style="color: #000000; font-weight: bold;">new</span> Song<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Weezer&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;Undone&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
    <span style="color: #000000; font-weight: bold;">new</span> Song<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Cake&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;Meanwhile, Rick James...&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
    <span style="color: #000000; font-weight: bold;">new</span> Song<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;The Stars&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;Ageless Beauty&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
    <span style="color: #000000; font-weight: bold;">new</span> Song<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Roy Orbison&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;In Dreams&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Now we have something of a faux database setup. How will we search it?  Why, with a search function, of course! Let&#8217;s write that now:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>21
22
23
24
25
26
27
28
29
30
31
32
33
34
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">function</span> search<span style="color: #009900;">&#40;</span><span style="color: #000088;">$songs</span><span style="color: #339933;">,</span> <span style="color: #000088;">$value</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">empty</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$value</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #b1b100;">return</span> <span style="color: #000088;">$songs</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000088;">$matches</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$songs</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$s</span><span style="color: #009900;">&#41;</span>
    <span style="color: #009900;">&#123;</span>
        <span style="color: #000088;">$matchArtist</span> <span style="color: #339933;">=</span> <span style="color: #990000;">stripos</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$s</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">artist</span><span style="color: #339933;">,</span> <span style="color: #000088;">$value</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">!==</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">;</span>
        <span style="color: #000088;">$matchTitle</span> <span style="color: #339933;">=</span> <span style="color: #990000;">stripos</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$s</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">title</span><span style="color: #339933;">,</span> <span style="color: #000088;">$value</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">!==</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">;</span>
        <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$matchArtist</span> <span style="color: #339933;">||</span> <span style="color: #000088;">$matchTitle</span><span style="color: #009900;">&#41;</span>
            <span style="color: #000088;">$matches</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$s</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #000088;">$matches</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>So what does this function do? Let&#8217;s take a look line-by-line:</p>
<ul>
<li>at lines 22-23, we check to see if the search value is empty (i.e. an empty string or null). If that&#8217;s the case, then we just return all the songs</li>
<li>at line 25, we declare the <code>$matches</code> array. This will contain all the songs that match the search value <code>$value</code></li>
<li>at line 26, we use a foreach loop to iterate through all the Song objects in the <code>$songs</code> array</li>
<li>at lines 28-29, we check to see if the artist name or song title contain the search value <code>$value</code></li>
<li>at line 30-31, we add the Song object to the <code>$matches</code> array if it matches the artist name or song title</li>
<li>at line 33, we return whatever matches (if any) we have found</li>
</ul>
<p>Ok, so now we have a Song class, an array of Song objects, and a function that searches that array. What&#8217;s left in our PHP script? Well, as it stands, we have no way to interface with it. What we need to do now is have some sort of way to respond to the AJAX GET request that our Searcher app will send. To do that, we harness the awesome power of the <code>$_GET</code> <a href="http://php.net/manual/en/language.variables.superglobals.php">superglobal</a>:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>36
37
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$value</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$_GET</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'value'</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$matches</span> <span style="color: #339933;">=</span> search<span style="color: #009900;">&#40;</span><span style="color: #000088;">$songs</span><span style="color: #339933;">,</span> <span style="color: #000088;">$value</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>On the first line, we extract &#8220;value&#8221; parameter from the <code>$_GET</code> superglobal and assign it to the <code>$value</code> variable.  The second line runs our search function on the <code>$songs</code> database and searches for songs that have an artist or title that contains the <code>$value</code> string.</p>
<p>We&#8217;re almost there!  At this point we&#8217;ve managed to get an array of Song objects that match the passed search value.  All we need to do now is return that PHP array of objects as a JSON-encoded array of objects.  Let&#8217;s do that now:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>39
40
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Content-Type: application/json'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #990000;">json_encode</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$matches</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>The first line sets the the <a href="http://en.wikipedia.org/wiki/Internet_media_type">MIME type</a> of an HTTP response.  MIME types are a sort of meta data that is used to describe what sort of content is being returned.  In this case, we are telling jQuery (or whatever client that issued the request) that we are returning content that is JSON formatted.  The second line is a built-in PHP function that converts PHP types into a string containing their JSON counterparts.  Basically, it allows us to encode our PHP objects into JavaScript and allow us to access them in a nearly identical way:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// PHP</span>
<span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
    <span style="color: #000000; font-weight: bold;">new</span> Song<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Artist 1&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;Title 1&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
    <span style="color: #000000; font-weight: bold;">new</span> Song<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Artist 2&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;Title 2&quot;</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Becomes... (after json_encode)</span>
<span style="color: #666666; font-style: italic;">// JavaScript</span>
<span style="color: #009900;">&#91;</span>
    <span style="color: #009900;">&#123;</span> artist<span style="color: #339933;">:</span> <span style="color: #0000ff;">&quot;Artist 1&quot;</span><span style="color: #339933;">,</span> title<span style="color: #339933;">:</span> <span style="color: #0000ff;">&quot;Title 1&quot;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
    <span style="color: #009900;">&#123;</span> artist<span style="color: #339933;">:</span> <span style="color: #0000ff;">&quot;Artist 2&quot;</span><span style="color: #339933;">,</span> title<span style="color: #339933;">:</span> <span style="color: #0000ff;">&quot;Title 2&quot;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span></pre></div></div>

<p>And we&#8217;re done the PHP script! If we want to test it, we can load execute the PHP file on our server and try different search values.  For example, entering this URL should return a JSON array with two Song objects:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// URL</span>
http<span style="color: #339933;">:</span><span style="color: #666666; font-style: italic;">//example.com/jQTouch-ajax-search/search.php?value=Weezer</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// Response</span>
<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#123;</span><span style="color: #0000ff;">&quot;artist&quot;</span><span style="color: #339933;">:</span><span style="color: #0000ff;">&quot;Weezer&quot;</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;title&quot;</span><span style="color: #339933;">:</span><span style="color: #0000ff;">&quot;Say It Ain't So&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span><span style="color: #009900;">&#123;</span><span style="color: #0000ff;">&quot;artist&quot;</span><span style="color: #339933;">:</span><span style="color: #0000ff;">&quot;Weezer&quot;</span><span style="color: #339933;">,</span><span style="color: #0000ff;">&quot;title&quot;</span><span style="color: #339933;">:</span><span style="color: #0000ff;">&quot;Undone&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#93;</span></pre></div></div>

<h3>The jQuery AJAX calls</h3>
<p>The finish line is now in sight.  We&#8217;ve successfully written our jQTouch UI and our PHP script.  The last thing we need to do is write some jQuery AJAX calls to execute our search and load the results into our UI.  In order to do that, we need to do the following:</p>
<ul>
<li>listen for the submission of the search form in the jQTouch UI</li>
<li>when the submission happens, get the search value from the form and set it as a parameter in an AJAX call to <code>search.php</code></li>
<li>register a callback that will populate the jQTouch search results when the AJAX call completes</li>
</ul>
<p>Let&#8217;s start with listening for the submit event on the search form.  First, we&#8217;ll need to create a new JavaScript source file <code>search.js</code> and fill it with the following boilerplate:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>$<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #006600; font-style: italic;">// Put code here.    </span>
&nbsp;
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span>jQuery<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>What this boilerplate does is give our JavaScript script its own context so that can minimize leaking variables into the global JavaScript namespace.  It also gives us access to the jQuery object in the convenient <code>$</code> form, regardless of whether or not <a href="http://api.jquery.com/jQuery.noConflict/">&#8220;no conflict&#8221; mode is enabled</a>.</p>
<p>Recall in part 1 we defined an HTML search form that looked like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="html4strict" style="font-family:monospace;"><span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">form</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;search&quot;</span> <span style="color: #000066;">action</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;&quot;</span>&gt;</span>
    <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;toolbar&quot;</span>&gt;</span>
        <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">h1</span>&gt;</span>Search<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">h1</span>&gt;</span>
        <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;#&quot;</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;back&quot;</span>&gt;</span>Back<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;</span>
    <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
    <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">ul</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;rounded&quot;</span>&gt;</span>
        <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">li</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">input</span> <span style="color: #000066;">type</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;text&quot;</span> <span style="color: #000066;">name</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;search-text&quot;</span> placeholder<span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;Search&quot;</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;search-text&quot;</span> <span style="color: #66cc66;">/</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">li</span>&gt;</span>
    <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">ul</span>&gt;</span>
    <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">ul</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;edgetoedge&quot;</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;search-results&quot;</span>&gt;</span>
        <span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">li</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #ff0000;">&quot;sep&quot;</span>&gt;</span>Results<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">li</span>&gt;</span>                
    <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">ul</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">form</span>&gt;</span></pre></td></tr></table></div>

<p>Note that on line 1 we defined the id of the form as <code>search</code>. We&#8217;ll use that to find the form and register a handler for its submit event so that we can take action when someone tries to perform a search using the jQTouch UI.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>$<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
&nbsp;
$<span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
&nbsp;
    $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#search&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">submit</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>event<span style="color: #339933;">,</span> info<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #003366; font-weight: bold;">var</span> text <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;input[id=search-text]&quot;</span><span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        text.<span style="color: #000066;">blur</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #003366; font-weight: bold;">var</span> results <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#search-results&quot;</span><span style="color: #339933;">,</span> <span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">empty</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        results.<span style="color: #660066;">append</span><span style="color: #009900;">&#40;</span>$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;&lt;li&gt;&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #3366CC;">&quot;class&quot;</span><span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;sep&quot;</span><span style="color: #339933;">,</span>
            text<span style="color: #339933;">:</span> <span style="color: #3366CC;">'Results for &quot;'</span> <span style="color: #339933;">+</span> text.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">'&quot;'</span>
        <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        $.<span style="color: #660066;">get</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;search.php&quot;</span><span style="color: #339933;">,</span>
            <span style="color: #009900;">&#123;</span> value<span style="color: #339933;">:</span> text.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
            <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                $.<span style="color: #660066;">each</span><span style="color: #009900;">&#40;</span>data<span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>i<span style="color: #339933;">,</span> song<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    <span style="color: #003366; font-weight: bold;">var</span> str <span style="color: #339933;">=</span> song.<span style="color: #660066;">artist</span> 
                        <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot; - &quot;</span>
                        <span style="color: #339933;">+</span> song.<span style="color: #660066;">title</span><span style="color: #339933;">;</span>
                    $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;&lt;li&gt;&quot;</span><span style="color: #009900;">&#41;</span>
                        .<span style="color: #660066;">text</span><span style="color: #009900;">&#40;</span>str<span style="color: #009900;">&#41;</span>
                        .<span style="color: #660066;">appendTo</span><span style="color: #009900;">&#40;</span>results<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #339933;">;</span>       
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#40;</span>jQuery<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>There&#8217;s a lot there, so let&#8217;s break it down line-by-line:</p>
<ul>
<li>starting at line 3 and ending at line 32 we have <a href="http://api.jquery.com/ready/">the jQuery ready handler</a> which is run once the DOM has finished loading</li>
<li>starting at line 5 and ending at line 30 we bind a submit event handler to the submit event for the <code>#search</code> form</li>
<li>at lines 6-7, we retrieve the <code>search-text</code> element, assign it to a variable (for later use on line 16), and then blur (i.e. deselect) the element so that the iPhone keyboard will go away</li>
<li>at lines 9-13, we clear any previous items in the list that may be hanging around from a previous search and then load in a new separator (&#8220;sep&#8221;) that contains the search value</li>
<li>at line 15-27, we perform our AJAX GET request to <code>search.php</code> with the value of the search text field as our value parameter (line 16) and a callback that adds the results to the list (lines 17-26)</li>
<li>finally, at line 29, we return false to prevent the default form behaviour (i.e. submitting the form) from being carried out</li>
</ul>
<p>And we&#8217;re done.  All we need to do now and include <code>search.php</code> in the header of <code>index.html</code> so that it&#8217;ll be run:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>12
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;script src=&quot;search.js&quot; type=&quot;application/x-javascript&quot; charset=&quot;utf-8&quot;&gt;&lt;/script&gt;</pre></td></tr></table></div>

<h3>Conclusion</h3>
<p>In this, the final installment of <em>How to do an AJAX search with jQTouch</em>, we finished off the example application we started in <a href="http://cdmckay.org/blog/2010/04/22/how-to-do-an-ajax-search-with-jqtouch-part-1/">the first part of this series</a>.  </p>
<p>In part 1, we covered building a UI using jQTouch.  In part 2, we helped visualize our problem by pretending that we were writing a front-end UI to a server-side music player.  To do that, we jumped into server side programming with PHP to write a script to serve us JSON-encoded Song objects.  Once we had that setup, we moved back into JavaScript.  In order to make use of the PHP script, we wrote a jQuery handler to respond to a jQTouch form submission.  The handler, once triggered, issued an AJAX call to the PHP script to pull down the appropriate Song objects for display in our UI.</p>
<h3>What Now?</h3>
<p>With respect to the goals of this tutorial, nothing.  However, if you want to pimp up the application a bit more, some things you could do are: </p>
<ul>
<li>Add genres and albums to the PHP Song object and then make the jQTouch UI menu have two additional options: Genres and Albums</li>
<li>Try to make a Now Playing sub-menu that is activated when a Song is picked from the Search screen</li>
</ul>
<h3>Source</h3>
<p>The source code I have written in this article is public domain, and you are free to do what you will with it. Here is <a href="http://cdmckay.org/files/jqtouch-ajax-search-part2.zip">a zip of the source, along with the required jQTouch source</a>. It should work pretty much right out of the box.</p>
]]></content:encoded>
			<wfw:commentRss>http://cdmckay.org/blog/2010/07/31/how-to-do-an-ajax-search-with-jqtouch-part-2/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>How to use custom jQuery animation queues</title>
		<link>http://cdmckay.org/blog/2010/06/22/how-to-use-custom-jquery-animation-queues/</link>
		<comments>http://cdmckay.org/blog/2010/06/22/how-to-use-custom-jquery-animation-queues/#comments</comments>
		<pubDate>Tue, 22 Jun 2010 05:07:53 +0000</pubDate>
		<dc:creator>cdmckay</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://cdmckay.org/blog/?p=1620</guid>
		<description><![CDATA[You may not know this, but whenever you use jQuery commands like fadeIn, slideDown, and delay, you are implicitly making use of a jQuery queue behind the scenes. That queue is named fx, and it is the default queue that all animations use unless otherwise specified. In this article, we will look at how jQuery [...]]]></description>
			<content:encoded><![CDATA[<p>You may not know this, but whenever you use jQuery commands like <code>fadeIn</code>, <code>slideDown</code>, and <code>delay</code>, you are implicitly making use of a jQuery queue behind the scenes.  That queue is named <code>fx</code>, and it is the default queue that all animations use unless otherwise specified.</p>
<p>In this article, we will look at how jQuery animation queues work, how to create and manipulate them, and how to use them in a meaningful way.</p>
<p><span id="more-1620"></span></p>
<h3>Queue fundamentals</h3>
<p>Each element has its own set of queues.  For example, if we execute this code:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#foo&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">fadeOut</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#bar&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">fadeOut</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The elements <code>#foo</code> and <code>#bar</code> will fade out more or less simultaneously. This is because they have their own <code>fx</code> queues. However, if we execute the code:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#foo&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">fadeOut</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#foo&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">fadeIn</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The element <code>#foo</code> will fade out and then fade in, instead of getting stuck in some sort of tug of war for opacity. This is because they are both using the <code>fx</code> queue of <code>#foo</code>, and thus run one after another.</p>
<h3>Creating and manipulating queues</h3>
<p>jQuery provides 5 commands for interacting with queues, which are summarized in the table below.</p>
<table>
<tr>
<th>Command</th>
<th>Summary</th>
</tr>
<tr>
<td>animate</td>
<td>Perform a custom animation of a set of CSS properties.</td>
</tr>
<tr>
<td>queue</td>
<td>Show the queue of functions to be executed on the matched elements, or manipulate the queue of functions to be executed on the matched elements.</td>
</tr>
<tr>
<td>dequeue</td>
<td>Execute the next function on the queue for the matched elements.</td>
</tr>
<tr>
<td>clearQueue</td>
<td>Remove from the queue all items that have not yet been run.</td>
</tr>
<tr>
<td>delay</td>
<td>Set a timer to delay execution of subsequent items in the queue.</td>
</tr>
</table>
<p>So how do we create a queue? We simply use a queue command that takes a <code>queueName</code> argument.  For example, we can use the <code>queue</code> command and add a function to queue. Let&#8217;s try it first with the regular <code>fx</code> queue.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#foo&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">queue</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>next<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;I was queued!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    next<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>When this code is run on a page with a <code>#foo</code> element, it immediately emits an alert saying &#8220;I was queued!&#8221;.  This is because the <code>fx</code> queue will dequeue elements right after they&#8217;re added.   We can verify that the <code>fx</code> queue is being used by queuing an animation before our alert.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#foo&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">fadeOut</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">queue</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>next<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;I was queued!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    next<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>When this code is run the <code>#foo</code> element fades out and then an alert is shown. Now let&#8217;s try it with a custom queue.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#foo&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">queue</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;custom&quot;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>next<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;I was queued!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    next<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Nothing happens. Why? Because unlike the default <code>fx</code> queue, custom queues are not dequeued immediately. They require an explicit <code>dequeue</code> call to get them started.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#foo&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">queue</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;custom&quot;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>next<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;I was queued!&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    next<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
.<span style="color: #660066;">dequeue</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;custom&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<h3>What&#8217;s the point?</h3>
<p>At this point you may be wondering, what&#8217;s the point? Why would I ever need to use queues? The answer is: to implement animation time-lines. Imagine you&#8217;re making a game and you want to have an object float up wards for 2000 milliseconds. Furthermore, you would like said object to stay completely opaque for 1000 milliseconds before slowly becoming completely transparent over the remaining 1000 milliseconds.  This time-line is shown below in tabular form (assuming that the object starts at <code>top: 100px</code>).</p>
<table>
<tr>
<th>Time</th>
<th>Top</th>
<th>Opacity</th>
</tr>
<tr>
<td>0</td>
<td>100px</td>
<td>1.0</td>
</tr>
<tr>
<td>500</td>
<td>90px</td>
<td>1.0</td>
</tr>
<tr>
<td>1000</td>
<td>80px</td>
<td>1.0</td>
</tr>
<tr>
<td>1500</td>
<td>70px</td>
<td>0.5</td>
</tr>
<tr>
<td>2000</td>
<td>60px</td>
<td>0.0</td>
</tr>
</table>
<p>At first glance, it appears that the <code>animate</code> command could take care of this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#object&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">animate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>opacity<span style="color: #339933;">:</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> top<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;-=40&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span>duration<span style="color: #339933;">:</span> <span style="color: #CC0000;">2000</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Unfortunately, this code will fade the object out over 2000 ms, instead of waiting 1000 ms then fading out over the remaining 1000 ms. <code>delay</code> can&#8217;t help either, because it would delay the upward floating as well. At this point we can either fiddle with timeouts or, you guessed it, use queues.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#object&quot;</span><span style="color: #009900;">&#41;</span>
.<span style="color: #660066;">delay</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">1000</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;fader&quot;</span><span style="color: #009900;">&#41;</span>
.<span style="color: #660066;">queue</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;fader&quot;</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>next<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    $<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">animate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>opacity<span style="color: #339933;">:</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> 
        <span style="color: #009900;">&#123;</span>duration<span style="color: #339933;">:</span> <span style="color: #CC0000;">1000</span><span style="color: #339933;">,</span> queue<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">false</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    next<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
.<span style="color: #660066;">dequeue</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;fader&quot;</span><span style="color: #009900;">&#41;</span>
.<span style="color: #660066;">animate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>top<span style="color: #339933;">:</span> <span style="color: #3366CC;">&quot;-=40&quot;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span>duration<span style="color: #339933;">:</span> <span style="color: #CC0000;">2000</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span></pre></td></tr></table></div>

<p>In this example, we have two queues: the <code>fx</code> queue and the <code>fader</code> queue. First off, we setup the <code>fader</code> queue. Since we want to wait 1000 ms before fading, we use the <code>delay</code> command with 1000 ms (line 2). Next, we queue up an animation that fades the object out over 1000 ms (line 3-7). Pay close attention to the <code>queue: false</code> option (line 5) we set in the <code>animate</code> command. This is critical, as it ensures that the animate doesn&#8217;t use the <code>fx</code> queue. Finally, we unleash the queue using <code>dequeue</code> and immediately follow it with a regular <code>fx</code>-using <code>animate</code> call to move the top of the object up 40 pixels (line 9).</p>
<h3>Conclusion</h3>
<p>jQuery makes use of implicit animation queues behind the scenes whenever you run an animation. By taking advantage of jQuery queue commands, custom animation queues can be constructed that enable certain complex animation stuctures, like time-lines, that would be otherwise impossible without using intervals or timeouts.</p>
]]></content:encoded>
			<wfw:commentRss>http://cdmckay.org/blog/2010/06/22/how-to-use-custom-jquery-animation-queues/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Biomorph.js: Natural Selection in JavaScript</title>
		<link>http://cdmckay.org/blog/2010/06/06/biomorph-js-natural-selection-in-javascript/</link>
		<comments>http://cdmckay.org/blog/2010/06/06/biomorph-js-natural-selection-in-javascript/#comments</comments>
		<pubDate>Mon, 07 Jun 2010 00:44:44 +0000</pubDate>
		<dc:creator>cdmckay</dc:creator>
				<category><![CDATA[Gaming]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web Development]]></category>

		<guid isPermaLink="false">http://cdmckay.org/blog/?p=1588</guid>
		<description><![CDATA[For his 1986 book The Blind Watchmaker, Richard Dawkins developed a program that created &#8220;biomorphs&#8221;: virtual creatures created by a computer simulation. The simulation, called Biomorph, was developed in order to demonstrate the power of natural selection. Recently, in an effort to better understand how the Biomorph program worked, I decided to implement it myself [...]]]></description>
			<content:encoded><![CDATA[<p>For his 1986 book <a href="http://en.wikipedia.org/wiki/The_Blind_Watchmaker">The Blind Watchmaker</a>, <a href="http://en.wikipedia.org/wiki/Richard_Dawkins">Richard Dawkins</a> developed a program that created &#8220;biomorphs&#8221;: virtual creatures created by a computer simulation.  The simulation, called <a href="http://www.rennard.org/alife/english/biomintrgb.html">Biomorph</a>, was developed in order to demonstrate the power of natural selection.</p>
<p><a href="http://cdmckay.org/biomorph"><img class="aligncenter size-full wp-image-1606" title="Biomorph" src="http://cdmckay.org/blog/wp-content/blogs.dir/2/files/2010/06/biomorph-ui.png" alt="" width="350" height="190" /></a></p>
<p>Recently, in an effort to better understand how the Biomorph program worked, I decided to implement it myself in JavaScript using the HTML5 canvas element.  <a href="http://cdmckay.org/biomorph">The result of this endeavour can be found here.</a> Read more to learn how to use the Biomorph program.</p>
<p><span id="more-1588"></span></p>
<h3>How do I work it?</h3>
<p>The user interface contains 9 biomorphs arranged in a 3&#215;3 grid.  This is a biomorph generation.  The centre the grid (with the blue border) contains the parent biomorph.  The parent is the biomorph that the remaining 8 children biomorphs are based on.  The children biomorphs are created by slightly mutating each of the eight genes in a biomorph.</p>
<p>In order to evolve a biomorph towards a certain goal, look at the 8 child biomorphs and select the one that is closest to looking like the biomorph you are aiming for.  For example, if you&#8217;re trying to make a bat biomorph, pick the biomorph that looks most like a bat.  Once you have a chosen a biomorph, click it to generate a new generation of biomorphs based on it.</p>
<p>If you choose the parent biomorph, you will simple be regenerating the child generation.  However, since each gene can move in two directions, you have 16 possible children for each parent.  Thus, if you are unhappy with your choice of children, you can try clicking the parent biomorph again to get one of the 8 other child biomorphs you haven&#8217;t seen.</p>
]]></content:encoded>
			<wfw:commentRss>http://cdmckay.org/blog/2010/06/06/biomorph-js-natural-selection-in-javascript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A little bit about Webble and JavaScript games</title>
		<link>http://cdmckay.org/blog/2010/05/19/a-little-bit-about-webble-and-javascript-games/</link>
		<comments>http://cdmckay.org/blog/2010/05/19/a-little-bit-about-webble-and-javascript-games/#comments</comments>
		<pubDate>Wed, 19 May 2010 21:37:48 +0000</pubDate>
		<dc:creator>cdmckay</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[Wezzle]]></category>
		<category><![CDATA[Wezzle Development]]></category>

		<guid isPermaLink="false">http://cdmckay.org/blog/?p=1535</guid>
		<description><![CDATA[Webble is a pure HTML/CSS/JavaScript implementation of some of the core features Wezzle game engine. By &#8220;pure&#8221; I mean that there are no external plugins like Flash used. Furthermore, Webble does not make use of the HTML5 canvas element: all the animation is done purely by moving around HTML elements using JavaScript. Writing a simple [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://couchware.ca/webble">Webble</a> is a pure HTML/CSS/JavaScript implementation of some of the core features <a href="http://couchware.ca/www/wezzle">Wezzle game engine</a>.  By &#8220;pure&#8221; I mean that there are no external plugins like Flash used.  Furthermore, Webble does not make use of the HTML5 canvas element: all the animation is done purely by moving around HTML elements using JavaScript.</p>
<p>Writing a simple game engine using the DOM and JavaScript poses some interesting problems that are atypical to regular website development.  In this article I will discuss a few of the problems that I encountered while writing Webble and how I solved them.</p>
<p><span id="more-1535"></span></p>
<h3>Tracking Mouse Movement</h3>
<p>In Wezzle, there is a selector that follows around the mouse cursor.  This was fairly easy to implement in Java, as having a mouse movement listener isn&#8217;t too costly.  In JavaScript, however, listening to the <code>mousemove</code> event is very expensive.  In fact, listening to <code>mousemove</code> slows down the browser window so much that JavaScript animations become unusable.  This is fine if your game does not animate while you listen to mouse movements.  Unfortunately, with Webble, this was not the case.  I needed to be able to follow the cursor at all times.</p>
<p>What was the solution? Webble has a 8&#215;10 grid called the &#8220;board&#8221; (see image below).  Each board cell can contain a tile. Overlayed on that board is a selector centered on whatever board cell the mouse cursor is on. Thus, Webble only needs to know when the mouse moves over a new board cell. This means that instead of using the <code>mousemove</code> event, I could instead use an invisible 8&#215;10 grid of divs and listen for their less expensive <code>mouseover</code> event.  This solution ended up working extremely well, allowing me to easily keep track of the mouse while simultaneously running animations.</p>
<p><img class="aligncenter size-full wp-image-1557" title="The We*le Board" src="http://cdmckay.org/blog/wp-content/blogs.dir/2/files/2010/05/board.png" alt="" width="256" height="320" /></p>
<h3>Animation</h3>
<p>Animation in Webble was quite painless, thanks to jQuery. For most animations, it was as easy as setting the correct parameters for the <a href="http://api.jquery.com/animate/">animate function</a>. In particular, there were some situations were I needed animations to run in lockstep.  In Webble, when you get a line, all the tiles in that line must animated away together.  Thus, doing something like this&#8230;</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Gets all the line tiles on the board.</span>
<span style="color: #003366; font-weight: bold;">var</span> tiles <span style="color: #339933;">=</span> board.<span style="color: #660066;">findLineTiles</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Get all the underlying DOM elements.</span>
<span style="color: #003366; font-weight: bold;">var</span> elements <span style="color: #339933;">=</span> $<span style="color: #009900;">&#40;</span>tiles.<span style="color: #660066;">map</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>tile<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> 
    <span style="color: #000066; font-weight: bold;">return</span> tile.<span style="color: #660066;">element</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span> 
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">// Fade out the elements.</span>
tiles.<span style="color: #660066;">fadeOut</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">500</span><span style="color: #339933;">,</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #006600; font-style: italic;">// Remove tiles from internal board structure.</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>&#8230;would not work very well and would be inefficient. Why? Because if I had, say, 10 tiles to animate, jQuery would create 10 tile animations.  This wasteful.  Moreover, since they&#8217;re independent animations, there&#8217;s no guarantee they will be moving the same amount each animation step. This visual disparity is exacerbated when the JS engine lags.</p>
<p>Fortunately, the jQuery animate function provides <a href="http://cdmckay.org/blog/2010/03/01/the-jquery-animate-step-callback-function/">a convenient step callback function</a> that allows you to animate many elements in lockstep. As a result, the code above can become a single animation that looks like this:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// The elements to animate in lockstop.</span>
<span style="color: #003366; font-weight: bold;">var</span> elements <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span> ... <span style="color: #660066;">same</span> <span style="color: #000066; font-weight: bold;">as</span> above ... <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> elementsTail <span style="color: #339933;">=</span> elements.<span style="color: #660066;">slice</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
elements
    .<span style="color: #660066;">eq</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span>
    .<span style="color: #660066;">animate</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#123;</span>opacity<span style="color: #339933;">:</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span>
        duration<span style="color: #339933;">:</span> <span style="color: #CC0000;">500</span><span style="color: #339933;">,</span>
        step<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>now<span style="color: #339933;">,</span> fx<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            elementsTail.<span style="color: #660066;">css</span><span style="color: #009900;">&#40;</span>fx.<span style="color: #660066;">prop</span><span style="color: #339933;">,</span> fx.<span style="color: #660066;">now</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
        complete<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #006600; font-style: italic;">// Remove tiles from internal board structure.</span>
        <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<h3>Audio</h3>
<p>The Wezzle game has several sound effects that need to play at specifc times (i.e. when a tile is inserted, when a line is removed, etc.).  Webble features some experimental sound support via the HTML5 audio element.  Unfortunately, like HTML5 video, not everyone can agree on a format.  Firefox supports Vorbis.  Safari (and Safari Mobile) supports MP3.  Chrome supports both.  IE supports none (until IE9, in the distant, distant future).  Thus, in order to support sounds across all modern browsers I needed to make both Vorbis and MP3 versions of all the sound effects.  This is a minor inconvenience that could have been avoided if Apple just played nice and included Vorbis support, at the very least on desktop Safari.</p>
<p>Other than that issue, HTML5 audio is pretty nice to work with.  All it takes to play a sound is:</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> lineSound <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Audio<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;sounds/line.ogg&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
lineSound.<span style="color: #660066;">play</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>This is a cinche compared to the hoops that need to be jumped through to get decent sound in Java.  Although HTML5 audio still has a little bit further to go, I think it has a happy future in HTML5.</p>
<h3>Conclusion</h3>
<p>Writing games purely in HTML, CSS and JavaScript is easier than it ever has been thanks to wonderful libraries like jQuery and next generation technologies like HTML5.  Although clever hacks are still required to make everything work together across browsers, I firmly believe that HTML/CSS/JavaScript combo will be a viable browser game platform in the near future.</p>
]]></content:encoded>
			<wfw:commentRss>http://cdmckay.org/blog/2010/05/19/a-little-bit-about-webble-and-javascript-games/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How to query posts by template in WordPress</title>
		<link>http://cdmckay.org/blog/2010/05/13/how-to-query-posts-by-template-in-wordpress/</link>
		<comments>http://cdmckay.org/blog/2010/05/13/how-to-query-posts-by-template-in-wordpress/#comments</comments>
		<pubDate>Thu, 13 May 2010 17:39:37 +0000</pubDate>
		<dc:creator>cdmckay</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://cdmckay.org/blog/?p=1508</guid>
		<description><![CDATA[Ever wanted to filter a query_posts call by template? If you&#8217;re reading this post, you probably have or need to right now. You probably went to the query_posts documentation and scanned for something like &#8220;template=foo&#8221; and were deeply disappointed. Then maybe, in an act of desperation, you started to trudge around the plugin library. Stop! [...]]]></description>
			<content:encoded><![CDATA[<p>Ever wanted to filter a query_posts call by template?  If you&#8217;re reading this post, you probably have or need to right now.  You probably went to <a href="http://codex.wordpress.org/Function_Reference/query_posts">the query_posts documentation</a> and scanned for something like &#8220;template=foo&#8221; and were deeply disappointed.  Then maybe, in an act of desperation, you started to trudge around <a href="http://wordpress.org/extend/plugins/">the plugin library</a>.  Stop!  Stop right there!  You don&#8217;t need a plugin to do this.  Everything you need is already in <a href="http://wordpress.org">WordPress</a>.</p>
<p><span id="more-1508"></span></p>
<p>Let&#8217;s start with a question: how does WordPress associate templates?  The answer: as a secret custom field.  What&#8217;s a custom field, you ask?  They&#8217;re those useful little suckers under the content area in the WP editor:</p>
<p><a href="http://cdmckay.org/blog/wp-content/blogs.dir/2/files/2010/05/wordpress-custom-fields.png" rel="lightbox[1508]"><img class="aligncenter size-full wp-image-1522" title="WordPress Custom Fields" src="http://cdmckay.org/blog/wp-content/blogs.dir/2/files/2010/05/wordpress-custom-fields.png" alt="" width="300" height="406" /></a></p>
<p>But if the template is a custom field, you ask, then how come I don&#8217;t see it down there?  Well, I just said they&#8217;re secret.  After poking around WP database, I discovered the template for a page is determined by the custom field name <code>_wp_page_template</code>.  My suspicion is that anything with the prefix _wp is hidden from the WP admin area and therefore secret.</p>
<h3>Harnessing the awesome power of custom fields</h3>
<p>On the bright side, even if you can&#8217;t see the <code>_wp_page_template</code> in the custom fields area, I can assure you it&#8217;s still there.  And if it&#8217;s there, you can use it in any of your nefarious schemes.</p>
<p>Query_posts provides 3 parameters relating to custom fields: meta_key, meta_value, and meta_compare.  With those in mind, imagine you have a template called Profile (profile.php), and you want to exclude any page that is a Profile from our query.  In order to do that, you&#8217;d would make a query_posts call like so:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">query_posts<span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
    <span style="color: #0000ff;">'post_type'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'page'</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">'meta_key'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'_wp_page_template'</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">'meta_value'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'profile.php'</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">'meta_compare'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'!='</span>
<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>The main thing to note here is that the template is identified by the name of the PHP file (profile.php) and not by the the name of template (Profile).</p>
<h3>Wrap-up</h3>
<p>Filtering your query_posts query by template is as easy as filtering by any custom field.  No plugin required.  Just remember: use the PHP file name as the template identifier, not the template name.</p>
]]></content:encoded>
			<wfw:commentRss>http://cdmckay.org/blog/2010/05/13/how-to-query-posts-by-template-in-wordpress/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>PHP interfaces and optional parameters</title>
		<link>http://cdmckay.org/blog/2010/04/24/php-interfaces-and-optional-parameters/</link>
		<comments>http://cdmckay.org/blog/2010/04/24/php-interfaces-and-optional-parameters/#comments</comments>
		<pubDate>Sun, 25 Apr 2010 03:03:32 +0000</pubDate>
		<dc:creator>cdmckay</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://cdmckay.org/blog/?p=1480</guid>
		<description><![CDATA[Interfaces in object-oriented languages like Java, C# and PHP are useful language constructs for ensuring that objects will respond to certain methods. However, unlike Java and C# (until recently), PHP has optional parameters. As it turns out, this feature has an interesting (and a little bit unexpected) effect on how we can implement interfaces in [...]]]></description>
			<content:encoded><![CDATA[<p>Interfaces in object-oriented languages like <a href="http://java.sun.com/docs/books/tutorial/java/IandI/createinterface.html">Java</a>, <a href="http://msdn.microsoft.com/en-us/library/ms173156.aspx">C#</a> and <a href="http://php.net/manual/en/language.oop5.interfaces.php">PHP</a> are useful language constructs for ensuring that objects will respond to certain methods.  However, unlike Java and C# (<a href="http://msdn.microsoft.com/en-us/library/dd264739.aspx">until recently</a>), <a href="http://php.net/manual/en/functions.arguments.php">PHP has optional parameters</a>.  As it turns out, this feature has an interesting (and a little bit unexpected) effect on how we can implement interfaces in PHP.</p>
<p><span id="more-1480"></span></p>
<p>Consider a simple interface for making objects comparable:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">interface</span> IComparable <span style="color: #009900;">&#123;</span>
     <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> compareTo<span style="color: #009900;">&#40;</span><span style="color: #000088;">$object</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Normally, in Java and C# (before 4.0) the only way to implement this interface would be to make a carbon copy of the method signature (save for the name of the parameter) and then fill in the method body.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> NetString implements IComparable <span style="color: #009900;">&#123;</span>
     <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> compareTo<span style="color: #009900;">&#40;</span><span style="color: #000088;">$object</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
          <span style="color: #339933;">...</span>
     <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>This satisfies the interface requirements because we need to have a method that responds to a method named <code>compareTo</code> with a single argument.  However, things get interesting when we introduce optional parameters.  That&#8217;s because we can write a method signature that is different from that found in the interface but still satisfies the requirement that the method have the correct name and accept only 1 parameter.</p>
<p>How is that possible?  Well, imagine we wanted our NetString class to optionally ignore case when comparing:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> NetString implements IComparable <span style="color: #009900;">&#123;</span>
     <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> compareTo<span style="color: #009900;">&#40;</span><span style="color: #000088;">$object</span><span style="color: #339933;">,</span> <span style="color: #000088;">$ignoreCase</span> <span style="color: #339933;">=</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
          <span style="color: #339933;">...</span>
     <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>Notice how we slipped in another (optional) argument <code>$ignoreCase</code>? Does this code still satisfy the IComparable interface?  Absolutely.  Why?  Because we can still call <code>compareTo($object)</code> in a meaningful way, and that&#8217;s all the matters.</p>
]]></content:encoded>
			<wfw:commentRss>http://cdmckay.org/blog/2010/04/24/php-interfaces-and-optional-parameters/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

