<?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>unitstep.net &#187; tutorials</title>
	<atom:link href="http://unitstep.net/blog/category/tutorials/feed/" rel="self" type="application/rss+xml" />
	<link>http://unitstep.net</link>
	<description>the home of peter chng</description>
	<lastBuildDate>Mon, 06 Feb 2012 01:23:17 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>The Flyweight Pattern: (Mis&#124;ab)used at times.</title>
		<link>http://unitstep.net/blog/2012/01/08/the-flyweight-pattern-misabused-at-times/</link>
		<comments>http://unitstep.net/blog/2012/01/08/the-flyweight-pattern-misabused-at-times/#comments</comments>
		<pubDate>Sun, 08 Jan 2012 23:21:10 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[software development java design-patterns]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=1312</guid>
		<description><![CDATA[In my brief career in software development thus far, I have seen a lot of &#8220;WTF&#8221; code, that is, code that deserves to be posted to The Daily WTF. Some of this code was admittedly developed by myself and upon reviewing it a few months after it was written, I secretly wondered what I&#8217;d been [...]]]></description>
			<content:encoded><![CDATA[<p>In my brief career in software development thus far, I have seen a lot of &#8220;WTF&#8221; code, that is, code that deserves to be posted to <a href="http://thedailywtf.com/">The Daily WTF</a>. Some of this code was admittedly developed by myself and upon reviewing it a few months after it was written, I secretly wondered what I&#8217;d been thinking.</p>
<p>This isn&#8217;t going to be an indictment of bad programming; in fact, I think it&#8217;s good if you can look back at your old code and see where it could be improved. Such a process suggests that you are continually <em>self-improving</em>, a skill crucial in software development. Besides, all of us have made a mistake or two at times when we were stressed, tired or just plain not thinking straight.</p>
<p>However, there&#8217;s one mistake that I&#8217;ve seen that I think warrants bringing to light, and that is the misuse of the <em>Flyweight pattern</em>.</p>
<h2>Who wants to be a Flyweight?</h2>
<p>Flyweight is typically used to describe one of the smaller weight classes in boxing or other fighting sports. This &#8220;minimal&#8221; aspect is what is shared with the design pattern of the same name. Simply put, a Flyweight object is one that reduces memory use by sharing common data with other objects.  Despite this plain definition, implementing the Flyweight pattern can be tricky.</p>
<p>Perhaps this is why I have seen examples like this: (<em>Java pseudo-code below; may not compile, but you shouldn&#8217;t use it anyways</em>)</p>
<pre><code>public class WidgetWithManyFields() {
  private Data field1;
  private String field2;
  private int field3;
  // A lot more fields...
  private SomeOtherData fieldN;

  // Getters and setters...
}</code></pre>
<p>Now, obviously the memory footprint of <code>WidgetWithManyFields</code> can be quite large, and since not all aspects of an application will need access to all data fields, it was decided that a &#8220;Flyweight&#8221; was needed:</p>
<pre><code>public class WidgetFlyweight() {
  // Only these fields are needed.
  private Data field1;
  private String field2;

  public WidgetFlyweight() {
    // Default constructor.
  }

  // Constructor to make one from the regular widget class.
  public WidgetFlyweight(WidgetWithManyFields widget) {
    this.field1 = widget.getField1();
    this.field2 = widget.getField2();
  }
  // Getters and setters...
}</code></pre>
<p>This isn&#8217;t really the Flyweight pattern at all. In fact, I don&#8217;t even know if it is a pattern at all. It might be considered something like the Proxy pattern, <em>if</em> the &#8220;Flyweight&#8221; class contained an instance of the regular class. But I don&#8217;t really know.</p>
<h2>So what is a Flyweight?</h2>
<p>Consider the example of a document that can have images embedded in it. There might be multiple copies of the same image present in the document, but each copy would be sized and positioned differently within the document. </p>
<p>In this case, you wouldn&#8217;t want to load and store the data in memory for multiple copies of the same image as that would be wasteful. However, each instance of the image displayed in the document might be formatted or positioned differently. How might this be done?</p>
<p>Firstly, some assumptions:</p>
<ul>
<li>An image is uniquely identified by some resource path.</li>
<li>The underlying image data does not change during the lifetime of the application.</li>
</ul>
<p>With these assumptions, we can define three classes that allow us to implement the Flyweight pattern.</p>
<p>Firstly, an <code>ImageData</code> class that encapsulates the actual image data. There should be only one canonical instance of this class for each unique resource path. Because of this, we can pool these objects for reuse.</p>
<p>However, the <code>ImageData</code> objects won&#8217;t be directly used by other parts of the application. Instead, we create an <code>ImageFlyweight</code> class that is manipulated. Each instance contains a reference to a canonical <code>ImageData</code> object and also stores information about how to format and position the image.</p>
<p>In this way, there can be multiple <code>ImageFlyweight</code> instances that reference the same image and hence the same <code>ImageData</code> instance, but each instance would define separate formatting and positioning details.</p>
<p>Tying everything together is a factory (<code>ImageFlyweightFactory</code>) that maintains the pool and is the access point for getting instances of <code>ImageFlyweight</code>.</p>
<p>Below is the code: (Sorry, it&#8217;s a lot of code to throw at you at once, but I didn&#8217;t feel like breaking it down into separate chunks, and you can just copy &#038; paste it into your favourite IDE for inspection/compilation)</p>
<pre><code>/**
 * Copyright (c) 2012 Peter Chng, http://unitstep.net/
 */
package net.unitstep.examples.flyweight;

import java.util.HashMap;
import java.util.Map;

/**
 * In order for the Flyweight Pattern to be effective, ImageFlyweight instances
 * should only be obtained via ImageFlyweightFactory.getImageFlyweight().
 *
 * This ensures that for each unique resource path, there is only one instance
 * of the backing ImageData existing in the application.
 *
 * @author Peter Chng
 */
public class ImageFlyweightFactory {
  private Map&lt;String, ImageData&gt; imageDataPool =
      new HashMap&lt;String, ImageData&gt;();

  public ImageFlyweight getImageFlyweight(final String resourcePath) {
    // This will return a new ImageFlyweight object each time; however, the
    // backing ImageData might be shared across multiple ImageFlyweight
    // instances.
    return new ImageFlyweight(this.getImageData(resourcePath));
  }

  private ImageData getImageData(final String resourcePath) {
    ImageData imageData = this.imageDataPool.get(resourcePath);
    if (null == imageData) {
      imageData = new ImageData(resourcePath);
      this.imageDataPool.put(resourcePath, imageData);
    }
    return imageData;
  }

  /**
   * @return the current count of ImageData instances in the pool; only for
   *         testing purposes.
   */
  public int getImageDataPoolCount() {
    return this.imageDataPool.size();
  }

  /**
   * Will contain the data representing an image loaded from some resource, i.e.
   * the file system.
   *
   * This is a private inner class because it should never need to be used
   * externally by callers. It is considered an implementation detail.
   *
   * We assume that the resource path is the uniquely-identifying aspect of an
   * image and that the underlying image resource/data will not change over the
   * lifetime of the application.
   *
   * Thus, only one instance of the ImageData class is needed for each image
   * uniquely identified by its resource path.
   *
   * @author Peter Chng
   */
  private class ImageData {
    private final byte[] data;
    private final String resourcePath;

    public ImageData(final String resourcePath) {
      this.resourcePath = resourcePath;

      // Image data would be loaded here based on the resource path supplied.
      // For brevity, it's not really done.
      this.data = new byte[] {};
    }

    public byte[] getData() {
      // Note: If we really intend to make this class immutable, we should
      // return a defensive copy instead so that callers cannot modify the
      // data stored in this instance.
      return this.data;
    }

    public String getResourcePath() {
      return resourcePath;
    }

    // Note: Not strictly necessary to override equals() and hashCode() for this
    // example, but it's done to indicate we only consider the resource path
    // in determining equality.
    @Override
    public boolean equals(final Object object) {
      if (null == object) {
        return false;
      }
      if (object == this) {
        return true;
      }
      if (object.getClass() != this.getClass()) {
        return false;
      }
      return this.resourcePath.equals(((ImageData) object).getResourcePath());
    }

    @Override
    public int hashCode() {
      return this.resourcePath.hashCode();
    }
  }

  /**
   * The ImageFlyweight object contains a reference to a canonical ImageData
   * object containing the actual image data we wish to render.
   *
   * By making this a static inner class of {@link ImageFlyweightFactory} and
   * the constructor private, instantiation of this class can be controlled and
   * limited to only the {@link ImageFlyweightFactory}. Callers MUST obtain an
   * instance of the ImageFlyweight through the factory and not by direct
   * instantiation.
   *
   * It also contains other properties that will affect the rendering of the
   * image in the application, such as height, width and position.
   *
   * Reusing the same ImageData object across different ImageFlyweight instances
   * allows us to display the same image in different ways within the
   * application, without having to load (or store in memory) the image data
   * multiple times.
   *
   * @author Peter Chng
   */
  public static class ImageFlyweight {
    private final ImageData imageData;

    private int height;
    private int width;
    private int positionX;
    private int positionY;

    private ImageFlyweight(final ImageData imageData) {
      this.imageData = imageData;
    }

    public byte[] getData() {
      return this.imageData.getData();
    }

    // Getters/setters for height, width, positionX, positionY...

    public int getHeight() {
      return height;
    }

    public void setHeight(int height) {
      this.height = height;
    }

    public int getWidth() {
      return width;
    }

    public void setWidth(int width) {
      this.width = width;
    }

    public int getPositionX() {
      return positionX;
    }

    public void setPositionX(int positionX) {
      this.positionX = positionX;
    }

    public int getPositionY() {
      return positionY;
    }

    public void setPositionY(int positionY) {
      this.positionY = positionY;
    }
  }
}</code></pre>
<p>Everything is contained within the <code>ImageFlyweightFactory</code> class, because the <code>ImageData</code> class does not need to be visible to outsiders and callers should not be able to instantiate <code>ImageFlyweight</code> instances on their own.</p>
<p>With this code, we have a simple test harness to verify whether it&#8217;s working:</p>
<pre><code>/**
 * Copyright (c) 2012 Peter Chng, http://unitstep.net/
 */
package net.unitstep.examples.flyweight;

import net.unitstep.examples.flyweight.ImageFlyweightFactory.ImageFlyweight;

import org.apache.log4j.Logger;

/**
 * @author Peter Chng
 */
public class ImageFlyweightTest {

  private static final Logger LOGGER =
      Logger.getLogger(ImageFlyweightTest.class);

  public static void main(final String[] args) {
    final ImageFlyweightFactory factory = new ImageFlyweightFactory();

    final String resourcePath1 = "/path/to/images/someImage.png";
    final String resourcePath2 = "/path/to/images/anotherImage.png";

    final ImageFlyweight image1 = factory.getImageFlyweight(resourcePath1);

    displayImageDataCountInPool(factory);

    final ImageFlyweight image2 = factory.getImageFlyweight(resourcePath2);

    displayImageDataCountInPool(factory);

    // Should not create an new ImageData instance in the pool.
    final ImageFlyweight image3 = factory.getImageFlyweight(resourcePath1);

    displayImageDataCountInPool(factory);
  }

  private static void displayImageDataCountInPool(
      final ImageFlyweightFactory factory) {
    LOGGER.debug("Current number of ImageData instances: "
        + factory.getImageDataPoolCount());
  }
}</code></pre>
<p>Running the code yields the following results:</p>
<pre>
DEBUG ImageFlyweightTest - Current number of ImageData instances: 1
DEBUG ImageFlyweightTest - Current number of ImageData instances: 2
DEBUG ImageFlyweightTest - Current number of ImageData instances: 2
</pre>
<p>The key point is that after the third <code>ImageFlyweight </code> object is created, the count in the <code>ImageData</code> pool does not increase since the same image has already been &#8220;loaded&#8221;.</p>
<h2>Other examples</h2>
<p>Note that Java itself implements something similar to the Flyweight pattern for Strings; this is known as <em>string interning</em> and many other languages support this feature as well.</p>
<p>Basically, because Strings are immutable, Java can store each distinct value in a pool and then reuse these instances when appropriate.  As an example, the following code displays &#8220;EQUAL&#8221;:</p>
<pre><code>String string1 = "A test of the string intern pool.";
String string2 = "A test of the string intern pool.";
// Note that we are comparing object identity, NOT equality.
if (string1 == string2) {
  System.out.println("EQUAL");
} else {
 System.out.println("NOT EQUAL");
}</code></pre>
<p>Note that this doesn&#8217;t work if you directly create a String using the <code>new</code> keyword.</p>
<h2>Conclusion</h2>
<p>I know that this was a fairly contrived example (aren&#8217;t they all?), but I hope it provided the basics of the Flyweight pattern to readers. There are a lot of holes and I don&#8217;t suggest you directly copy this example for production code, but instead learn the skills to effectively develop the pattern on your own.</p>
<p>As always, I welcome questions or comments and especially corrections if I&#8217;ve made a mistake! Thanks for reading!</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2012/01/08/the-flyweight-pattern-misabused-at-times/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Folding changesets with the Mercurial Queues extension</title>
		<link>http://unitstep.net/blog/2011/01/26/folding-changesets-with-the-mercurial-queues-extension/</link>
		<comments>http://unitstep.net/blog/2011/01/26/folding-changesets-with-the-mercurial-queues-extension/#comments</comments>
		<pubDate>Thu, 27 Jan 2011 00:59:55 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[mercurial]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[changeset]]></category>
		<category><![CDATA[folding]]></category>
		<category><![CDATA[hg]]></category>
		<category><![CDATA[queues]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=1215</guid>
		<description><![CDATA[Mercurial is my distributed revision control system of choice, a trait I picked up at my previous job. I haven&#8217;t had the opportunity to deal with Git for any period of time, so I can&#8217;t comment on the various &#8220;Why X is better than Y&#8221; arguments out there. Most of you using Mercurial/Hg (or revision [...]]]></description>
			<content:encoded><![CDATA[<p class="image align-right"><img src="http://unitstep.net/wordpress/wp-content/uploads/2011/01/mercurial-logo.png" alt="" title="mercurial-logo" width="100" height="120" class="alignnone size-full wp-image-1231" /></p>
<p>Mercurial is my distributed revision control system of choice, a trait I picked up at my previous job.  I haven&#8217;t had the opportunity to deal with Git for any period of time, so I can&#8217;t comment on the various &#8220;<a href="http://whygitisbetterthanx.com/">Why X is better than Y</a>&#8221; <a href="http://stevelosh.com/blog/2010/01/the-real-difference-between-mercurial-and-git/">arguments</a> <a href="http://code.google.com/p/support/wiki/DVCSAnalysis">out there</a>. </p>
<p>Most of you using Mercurial/Hg (or revision control in general) will be familiar with the concept of <em>merging</em>, where the changes in a source branch are merged into a target branch, creating a new revision or changeset on the target branch.  But what about the times when you would like to combine two or more changesets/revisions into a single one that has the combined/overall changes of all of them? In that case, the Mercurial Queues extension provides for the concept of <em>folding</em>, which accomplishes just that.</p>
<h2>Mercurial Queues</h2>
<p>The <a href="http://mercurial.selenic.com/wiki/MqExtension">Mercurial Queues extension</a> (<strong>mq</strong>) is one of the most useful Hg extensions available, as it allows for <a href="http://hgbook.red-bean.com/read/mercurial-queues-reference.html">much more</a> than folding.  Basically, mq allows you to import changesets to a <em>patch queue</em>, where they can be manipulated.  In this way, previously immutable changesets can be modified.  One such modification is the concept of <em>folding</em>, where one more more changesets are combined to produce a single changeset with the equivalent effect.</p>
<h2>Proceed with caution</h2>
<p>Because mq can directly modify changesets (i.e. revision history), it can have adverse on your Hg repository; data can be permanently lost, since the changes that can be made cannot be &#8220;backed out&#8221; or &#8220;reverted&#8221;.  <strong>I strongly recommend cloning your Hg repo before undertaking any actions with Mercurial Queues for the first time</strong>, if only for peace of mind and the fact that cloning is such an easy operation with Mercurial.</p>
<h2>The case for folding</h2>
<p>Generally, it&#8217;s not a good idea to go and change revision history, which is what folding does. The purpose of revision control is to <em>preserve</em> history and provide a timeline for how the codebase has evolved.  In the case of Mercurial, it&#8217;s especially troublesome to go and modify revision history on a central server that others are pushing to/pulling from, as this may cause inconsistencies.  Having said that, there are times when combining multiple changesets into one may be beneficial.</p>
<p>Some examples that come to mind are:</p>
<ul class="note">
<li>You have made many intermediate commits to your local Hg repository during development, but would like to combine them into a single one before pushing to a remote/central repository for clarity. (The multiple local commits were for your own sake)</li>
<li>You accidentally committed some sensitive data (i.e. hard-coded passwords) to a repository, followed by some other changes that also removed that sensitive data.  You don&#8217;t want to strip the intermediate (password-containing) revision because of the subsequent work. You can combine the two to one revision that contains the subsequent work but no record of the sensitive data.</li>
</ul>
<p>Folding will help in both situations.</p>
<h2>Tutorial</h2>
<p>This tutorial will cover folding using <a href="http://tortoisehg.org/">TortoiseHg</a>, the popular GUI front-end for Mercurial. Before getting started, you&#8217;ll have to ensure that you don&#8217;t have any uncommitted changes, as you won&#8217;t be able to accomplish some of the steps with outstanding changes. </p>
<p>Open up the Repository Explorer. Below, you can see the example one, with our initial commit, which contained the sensitive data, followed by another that removed it. We&#8217;ll merge them into one.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2011/01/1.png"><img src="http://unitstep.net/wordpress/wp-content/uploads/2011/01/1-300x138.png" alt="" title="1" width="300" height="138" class="alignnone size-medium wp-image-1247" /></a>
</p>
<p>Next, you&#8217;ll need to enable the Mercurial Queues extension, either through the TortoiseHg UI or by manually editing your <code>mercurial.ini</code> file or per-repo setting file. (<code>.hgrc</code>) Below, I&#8217;ve shown it in the UI: <strong>You need to check off the &#8220;mq&#8221; box under &#8220;Extensions&#8221;</strong>.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2011/01/2.png"><img src="http://unitstep.net/wordpress/wp-content/uploads/2011/01/2-286x300.png" alt="" title="2" width="286" height="300" class="alignnone size-medium wp-image-1248" /></a>
</p>
<p>You&#8217;ll need to close the Repository Explorer and re-open it for the mq extension to take effect in the UI. </p>
<p>Next, select the <strong>oldest</strong> changeset and then <strong>right-click the newest one</strong>; in the context menu, select &#8220;Import from here to selected MQ&#8221;.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2011/01/3.png"><img src="http://unitstep.net/wordpress/wp-content/uploads/2011/01/3-300x147.png" alt="" title="3" width="300" height="147" class="alignnone size-medium wp-image-1249" /></a>
</p>
<p>Then, open the Patch Queue by clicking its icon or selecting <strong>View > Patch Queue</strong> from the menu.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2011/01/4.png"><img src="http://unitstep.net/wordpress/wp-content/uploads/2011/01/4-300x147.png" alt="" title="4" width="300" height="147" class="alignnone size-medium wp-image-1250" /></a>
</p>
<p>You should be able to see the changesets in your patch queue on the left side drawer.  They&#8217;ll be labeled 0.diff, 1.diff, etc. You can also see which patch corresponds to which changeset because the imported changesets will have be labeled in the UI with <strong>qbase, qtip, 0.diff, 1.diff</strong>, etc. (They are listed in the patch queue in opposite order)</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2011/01/5.png"><img src="http://unitstep.net/wordpress/wp-content/uploads/2011/01/5-300x106.png" alt="" title="5" width="300" height="106" class="alignnone size-medium wp-image-1251" /></a>
</p>
<p>Now, right-click the <strong>top/oldest one</strong> in the patch queue, and select &#8220;Goto&#8221;. This will bring you back to the oldest changeset and <strong>remove</strong> the previous ones from your repository.  But don&#8217;t worry, the changesets still exist in your (mercurial) queue.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2011/01/6.png"><img src="http://unitstep.net/wordpress/wp-content/uploads/2011/01/6-300x115.png" alt="" title="6" width="300" height="115" class="alignnone size-medium wp-image-1252" /></a>
</p>
<p>Now, right click the next oldest one (which was removed from your repository), click &#8220;Fold&#8221; and then &#8220;Yes&#8221;.  This will effectively fold or combine the two changesets into a single one with the equivalent changes/effects.  <strong>Please note that this operation cannot be reversed</strong>, so make sure you really want to do it. (You did clone/backup your repository before starting, right?)</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2011/01/7.png"><img src="http://unitstep.net/wordpress/wp-content/uploads/2011/01/7-300x138.png" alt="" title="7" width="300" height="138" class="alignnone size-medium wp-image-1253" /></a>
</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2011/01/8.png"><img src="http://unitstep.net/wordpress/wp-content/uploads/2011/01/8.png" alt="" title="8" width="256" height="155" class="alignnone size-full wp-image-1254" /></a>
</p>
<p>You can now adjust the commit comment/message and username, if you like, by clicking &#8220;Commit&#8221; or by selecting <strong>Tools > Commit</strong> from the menu. You may need to select <strong>View > Advanced</strong> to change/show the username.  By default the commit message of the folded/unified changeset is an aggregate of the changesets that were combined to form it. You&#8217;ll probably want to adjust this down to something more meaningful. </p>
<p>After you are done, be sure to click <strong>&#8220;QRefresh&#8221;</strong> before closing the window.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2011/01/9.png"><img src="http://unitstep.net/wordpress/wp-content/uploads/2011/01/9-300x103.png" alt="" title="9" width="300" height="103" class="alignnone size-medium wp-image-1255" /></a>
</p>
<p>After you&#8217;ve done the folding and modifying the commit message, you can right click the patch file (0.diff in this case) and select &#8220;Finish Applied&#8221; to put the folded/unified changeset back into your repository.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2011/01/10.png"><img src="http://unitstep.net/wordpress/wp-content/uploads/2011/01/10-300x122.png" alt="" title="10" width="300" height="122" class="alignnone size-medium wp-image-1256" /></a>
</p>
<p>Your MQ patch queue should now be <strong>empty</strong> and the repository browser should show only one changeset, with your updated comments and no MQ tags/labels on the changeset. You can close the patch queue sidebar now, if you&#8217;d like.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2011/01/11.png"><img src="http://unitstep.net/wordpress/wp-content/uploads/2011/01/11-300x156.png" alt="" title="11" width="300" height="156" class="alignnone size-medium wp-image-1257" /></a>
</p>
<p>There! Now all evidence of your nefarious activities has now been removed. Only the beginning and the end remain. Use wisely.</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2011/01/26/folding-changesets-with-the-mercurial-queues-extension/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Triggering links from JavaScript using jQuery</title>
		<link>http://unitstep.net/blog/2010/04/12/triggering-links-from-javascript-using-jquery/</link>
		<comments>http://unitstep.net/blog/2010/04/12/triggering-links-from-javascript-using-jquery/#comments</comments>
		<pubDate>Tue, 13 Apr 2010 00:56:48 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[jquery javascript tutorials]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=1107</guid>
		<description><![CDATA[Sometimes, you may want to trigger a link (that is, an anchor element) directly from JavaScript. That is, you may want to simulate the user clicking on the link programmatically. If you&#8217;re using jQuery, you&#8217;ll no doubt be aware of the click() method which can be used to trigger that event on an object. One [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes, you may want to trigger a link (that is, an <a href="http://htmlhelp.com/reference/html40/special/a.html">anchor element</a>) directly from JavaScript.  That is, you may want to simulate the user clicking on the link programmatically.</p>
<p>If you&#8217;re using jQuery, you&#8217;ll no doubt be aware of the <a href="http://api.jquery.com/click/"><code>click()</code></a> method which can be used to trigger that event on an object.  One would think that executing <code>click()</code> on an anchor element would cause the browser to navigate to the <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym>, but this isn&#8217;t the case.  <strong>You cannot use jQuery&#8217;s <code>click()</code> method to fully trigger or simulate a user clicking on a link.</strong></p>
<p>Instead, <code>click()</code>, when executed on links, only seems to trigger any event handlers attached to the DOM element rather than any default behaviour.  I&#8217;m not sure if this is the case with other event methods or other DOM elements.</p>
<h2>The solution</h2>
<p>Instead, the solution is to directly manipulate the <code>window.location</code> object from JavaScript.  One would think that since preventing the default action is quite simple (with jQuery&#8217;s <a href="http://api.jquery.com/event.preventDefault/"><code>event.preventDefault()</code></a>), triggering the default action of a link click would also be.  But this isn&#8217;t the case.  Here&#8217;s a simple example on how to simulate a user clicking on a link.</p>
<p>In this contrived example, we have an ordered list of links that we&#8217;ve prevented the default action from executing on each.  Instead, to activate a link we&#8217;ve provided an input box for the user to input the link number and then hit &#8216;Go&#8217;.  When this happens, we grab the identified link and assign the <code>href</code> attribute value of the link to <code>window.location</code>, effectively recreating the default action of clicking the link.</p>
<p><acronym class="uttInitialism" title="HyperText Markup Language">HTML</acronym> Source:</p>
<pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD <a href="http://www.w3.org/MarkUp/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="eXtensible HyperText Markup Language - HTML reformulated as XML">XHTML</acronym></a> 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
&lt;head&gt;
  &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt;

  &lt;title&gt;jQuery Demos&lt;/title&gt;
  &lt;link rel="stylesheet" href="styles.css" media="all" /&gt;
  &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
  &lt;script type="text/javascript" src="scripts.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;h1&gt;jQuery Demos&lt;/h1&gt;

&lt;ol id="outboundLinks"&gt;
  &lt;li&gt;&lt;a href="http://www.google.com"&gt;Google&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href="http://www.theglobeandmail.com/"&gt;The Globe and Mail&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href="http://stackoverflow.com/"&gt;Stack Overflow&lt;/a&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;
Link Number to activate:
&lt;input id="linkNumber" type="text" size="3" /&gt;
&lt;input id="activateLink" type="button" value="Go" /&gt;
&lt;/p&gt;

&lt;/body&gt;
&lt;/html&gt;</code></pre>
<p>JavaScript in <code>scripts.js</code>:</p>
<pre><code>jQuery(function(e)
{
  jQuery("#outboundLinks").click(function(e)
  {
    e.preventDefault();
  });

  jQuery("#activateLink").click(function(e)
  {
    var links = jQuery("#outboundLinks li a");
    var value = parseInt(jQuery("#linkNumber").val());

    if (!isValidNumber(value, links))
    {
      window.alert("Invalid link number.");
      return;
    }
    else
    {
      // This won't work.  We cannot trigger the default
      // behaviour of clicking on a link this way.
      // links.eq(value - 1).click();

      // Instead, manipulate window.location directly.
      window.location = links.eq(value - 1).attr("href");
    }
  });
});

function isValidNumber(value, links)
{
    if (isNaN(value))
    {
      return false;
    }
    else if (value &lt;= 0 || value &gt; links.size())
    {
      return false;
    }
    else {
      return true;
    }
}</code></pre>
<p>Note that <a href="https://developer.mozilla.org/En/DOM/Window.location"><code>window.location</code> is not a regular property</a>; it&#8217;s a special object that when assigned to, changes the <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> in the address bar of the browser.  There&#8217;s some debate over whether to directly <a href="https://developer.mozilla.org/Talk:en/DOM/window.location">use the location object or to use the <code>window.location.href</code> property</a>.</p>
<p>This accomplishes the task of triggering the default action of clicking on a link, albeit in a roundabout fashion.  Note that this example will only work for regular links that use <code>href</code> attributes as the source of the new <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym>.  If you have links doing more complicated things via the use of event handlers (i.e. Ajax), then you&#8217;re better off using <a href="http://api.jquery.com/click/"><code>click()</code></a> or directly invoking the JavaScript methods involved.</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2010/04/12/triggering-links-from-javascript-using-jquery/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Determine your visitor&#8217;s location based on IP address</title>
		<link>http://unitstep.net/blog/2009/06/29/determine-your-visitors-location-based-on-ip-address/</link>
		<comments>http://unitstep.net/blog/2009/06/29/determine-your-visitors-location-based-on-ip-address/#comments</comments>
		<pubDate>Tue, 30 Jun 2009 02:37:17 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[geolocation]]></category>
		<category><![CDATA[maps]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[ip address]]></category>
		<category><![CDATA[location]]></category>
		<category><![CDATA[lookup ip-geolocation]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=935</guid>
		<description><![CDATA[If you&#8217;re running a website that provides a service, it&#8217;s likely that it would be beneficial to know a user&#8217;s location (or have a rough idea) so that the content could be tailored to their specific geographic area. But how do you get their location, without having to ask them? By using their IP address, [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re running a website that provides a service, it&#8217;s likely that it would be beneficial to know a user&#8217;s location (or have a rough idea) so that the content could be tailored to their specific geographic area.  But how do you get their location, without having to ask them? By using their IP address, it&#8217;s possibly to determine their general area with fairly good accuracy. In this tutorial, I&#8217;ll explain how to do that using the free <a href="http://ipinfodb.com/ip_database.php">IP address geolocation database</a> from <a href="http://ipinfodb.com/">IPInfoDB</a>.</p>
<h2>Motivation and Usage</h2>
<p>There are numerous reasons for using the user&#8217;s location to improve the quality of a service.  For example, the restaurant guide and review site, <a href="http://www.restaurantica.com/">Restaurantica</a>, automatically makes a guess as to your location and populates the &#8220;Search&#8221; field so that you are one click away from finding information tailored to your geographic area.  </p>
<p>This determination is based on the user&#8217;s IP address.  Usually, the lookup is done based on a static set of mappings from IP addresses to geographical locations, like cities.  In fact, this is exactly what the <a href="http://ipinfodb.com/ip_database.php">IP address geolocation database</a> (that we&#8217;ll use) does.  It has the advantage of being easy to understand but unfortunately the accuracy can degrade over time, as IP addresses are usually not hardwired to specific locations.  For example, most DSL users are subject to DHCP, so the same IP address may be re-used across different cities. (The IP address database from IPInfoDB is updated periodically to help reduce this inaccuracy)</p>
<p>Thus, you should not rely on the information provided to be 100% accurate; it should only be used as a suggestion.  This is why <a href="http://www.restaurantica.com/">Restaurantica</a> only <em>populates</em> the search field with your estimated location, rather than giving you the results for that location right away; if it was wrong, the results for a different location would certainly be confusing to a user.  This gives the user a chance to correct any inaccurate lookups.</p>
<h2>Using the IP Address geolocation database</h2>
<p>The first step is to <a href="http://ipinfodb.com/ip_database.php">download the database</a> and import it into your local database; for this example I&#8217;ll use MySQL.  Note that the site also offers an <a href="http://ipinfodb.com/ip_location_api.php">IP location Lookup API</a>, which has the advantage of not requiring a local database but may be subject to usage limits; if you&#8217;ll be getting a lot of traffic you&#8217;ll be better off using the local database.</p>
<h3>Import the contents into MySQL</h3>
<p>I downloaded the <a href="http://mirrors.portafixe.com/ipinfodb/ip_database/current/ipinfodb_one_table_full.sql.bz2">Complete (City) database as one table in SQL format</a>.  Extracting the file from the archive, you&#8217;ll see that it&#8217;s well over 300 MB in size. If you&#8217;re fond of using <a href="http://www.phpmyadmin.net/home_page/index.php">phpMyAdmin</a>, you unfortunately won&#8217;t be able to import such a large file using that tool, so we&#8217;ll have to rely on the command line to import the contents.  Go to your <code>mysql/bin</code> folder and enter the following command, assuming you extracted the SQL file to the same location:</p>
<pre><code>mysql -u root -p [name of database] &lt; ipinfodb_one_table_full.sql</code></pre>
<p><strong>Running this command will take some time, as it won&#8217;t be fast having to import such a huge table</strong>.  Take a break and come back in a few minutes. <img src='http://unitstep.net/wordpress/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  (You may want to create a new database to hold just this table, do that before running this command)  After that&#8217;s done, you should be able to see the contents in phpMyAdmin, like below:</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/06/ip-geolocation-1.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/06/ip-geolocation-1-300x84.jpg" alt="ip-geolocation-1" title="ip-geolocation-1" width="300" height="84" class="alignnone size-medium wp-image-945" /></a>
</p>
<h3>Using the database</h3>
<p>Querying the database is straightforward, and the IP Info DB website has plenty of examples <a href="http://ipinfodb.com/ip_database.php">at the bottom of the download page</a>.  Basically, once you have the user&#8217;s IP, you can use a query like this to find the most likely city it originated from:</p>
<pre><code>SELECT *
FROM `ip_group_city`
WHERE `ip_start` &lt;= INET_ATON([ip address as a string])
ORDER BY ip_start DESC
LIMIT 1;</code></pre>
<p>The INET_ATON function converts a string that is the dotted-quad octet form of an IP address (the form you&#8217;re most used to seeing) into a 32-bit unsigned integer.  This integer is then used to locate the record that most likely corresponds to the geographical location.  The database is structured such that row with the highest <code>ip_start</code> value not greater than the given IP address is deemed to be the most likely location.</p>
<p>An example:</p>
<pre><code>SELECT * FROM `ip_group_city` WHERE `ip_start` &lt;= INET_ATON('69.156.150.155') ORDER BY ip_start DESC limit 1;</code></pre>
<p>(This returns the city of Toronto, Ontario, Canada) If you want to get a list of likely locations, just increase the LIMIT argument to something like 10, and this will return 10 locations that are likely close to where the IP address is located.  <strong>Note that there may be duplicates in this list</strong>.</p>
<h2>A simple example</h2>
<p>Here&#8217;s a simple <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> script that takes the user&#8217;s IP address and displays their most likely location on a map using the <a href="http://code.google.com/apis/maps/documentation/staticmaps/">Google Static Maps API</a>.</p>
<pre><code>&lt;?php
$ipGeolocationDatabaseName = 'ip_geolocation';

$link = mysql_connect('localhost', 'root', '');
$ipAddress = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);

echo $ipAddress;

mysql_select_db($ipGeolocationDatabaseName, $link);

$query = "SELECT * FROM `ip_group_city` " .
         "WHERE `ip_start` &lt;= INET_ATON( '$ipAddress' ) " .
         "ORDER BY ip_start DESC " .
         "LIMIT 1";
$resultLocation = mysql_query($query);

$numRows = mysql_num_rows($resultLocation);

if (0 == $numRows)
{
  echo "No likely locations found.";
}

while ($row = mysql_fetch_array($resultLocation))
{
  echo "&lt;pre&gt;";
  print_r($row);
  echo "&lt;/pre&gt;";

  $lat = urlencode($row['latitude']);
  $lng = urlencode($row['longitude']);
  if (!empty($lat) &amp;&amp; !empty($lng))
  {
    // NOTE: Replace the `key` parameter with your own, obtained from:
    // http://code.google.com/apis/maps/signup.html
    // (The one in use is only good for URLs on `localhost`)
    $queryString = "center=$lat,$lng";
    $queryString .= "&amp;zoom=10";
    $queryString .= "&amp;size=300x300";
    $queryString .= "&amp;markers=$lat,$lng,blue";
    $queryString .= "&amp;key=ABQIAAAAicCf6MqoHlR-MsfivtVWPRT2yXp_ZAY8_ufC3CFXhHIE1NvwkxTNmqRdvnM9orG9QdyALHoUZfmFuQ";
    $queryString .= "&amp;sensor=false";

    echo '&lt;img src="http://maps.google.com/staticmap?' . htmlentities($queryString) . '" alt="location" /&gt;';
  }
}
?&gt;</code></pre>
<p>Here&#8217;s what it display for my IP address:</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/06/ip-geolocation-2.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/06/ip-geolocation-2.jpg" alt="ip-geolocation-2" title="ip-geolocation-2" width="300" height="300" class="alignnone size-full wp-image-956" /></a>
</p>
<p>As you can see, it&#8217;s not always accurate, but it&#8217;s a good start to enhancing your website to offer localized services and features.</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2009/06/29/determine-your-visitors-location-based-on-ip-address/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Open Cygwin Bash Shell Here</title>
		<link>http://unitstep.net/blog/2009/05/16/open-cygwin-bash-shell-here/</link>
		<comments>http://unitstep.net/blog/2009/05/16/open-cygwin-bash-shell-here/#comments</comments>
		<pubDate>Sun, 17 May 2009 01:57:41 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[bash]]></category>
		<category><![CDATA[cygwin]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[prompt]]></category>
		<category><![CDATA[shell]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=898</guid>
		<description><![CDATA[If you&#8217;re like me, you love shortcuts and]]></description>
			<content:encoded><![CDATA[<p class="image align-right"><a href="http://unitstep.net/wordpress/wp-content/uploads/2009/05/cygwin-prompt-here-3.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/05/cygwin-prompt-here-3-150x150.jpg" alt="cygwin-prompt-here-3" title="cygwin-prompt-here-3" width="150" height="150" class="alignnone size-thumbnail wp-image-902" /></a></p>
<p>If you&#8217;re like me, you love shortcuts and <a href="/blog/2007/07/08/using-launchy-to-improve-productivity-with-a-graphical-command-line/"">other tools</a> that improve productivity.  One of the other things I&#8217;ve gained a liking for is the Bash shell, after spending time in a Unix environment.  Since I couldn&#8217;t live without this, and the other tools that typically come with a Unix environment, I installed the great <a href="http://www.cygwin.com/">Cygwin</a>, in order to create a Linux-like environment on my Windows PC. (Not ready to make the full jump to Linux yet, for gaming reasons)</p>
<p>However, one thing that always irked me was having to manually navigate to a certain folder after opening up a Bash shell in Cygwin.  For Windows, there is a <a href="http://www.microsoft.com/windowsxp/Downloads/powertoys/Xppowertoys.mspx">PowerToy</a> called &#8220;Open Command Window Here&#8221;, that provides a context menu option for quickly opening a (Windows) command prompt with the location set to the selected folder.  This is helpful, since you often have the folder open when you want to also have a command prompt at the same location.  Now, all I needed was the equivalent function, but for the Cygwin Bash shell, instead of the Windows Command prompt.</p>
<h2>Creating a &#8220;Bash Prompt Here&#8221; shortcut</h2>
<p>I did some searching and found a <a href="http://www.kertdawg.net/index.php?itemid=67">myriad</a> of <a href="http://www.burgaud.com/open-command-window-here/">solutions</a> to my problem, <a href="http://www.mindview.net/Etc/Cygwin/BashHere">most of which</a> were <a href="http://alecthegeek.wordpress.com/2006/10/19/windows-explorer-open-bash-here/">somewhat complicated</a>.  Thankfully, I did find one link that suggested an <a href="http://www.bombinator.com/gamedev/archives/12/command-line/cygwin-bash-prompt-here/">easier solution</a>.</p>
<p>Basically, here&#8217;s what you do.  When you install Cygwin (of if you&#8217;ve already installed it, download it again and start setup again to run an update), make sure that you select the <strong>chere</strong> package under the &#8220;Shells&#8221; category.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/05/cygwin-prompt-here-1.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/05/cygwin-prompt-here-1-300x281.jpg" alt="cygwin-prompt-here-1" title="cygwin-prompt-here-1" width="300" height="281" class="alignnone size-medium wp-image-900" /></a>
</p>
<p>After Cygwin is launched, open it up and type the command <strong><code>chere -i</code></strong>, like so:</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/05/cygwin-prompt-here-2.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/05/cygwin-prompt-here-2-300x207.jpg" alt="cygwin-prompt-here-2" title="cygwin-prompt-here-2" width="300" height="207" class="alignnone size-medium wp-image-901" /></a>
</p>
<p>You should now see the following option in your folder&#8217;s context menu, and more importantly, it works!</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/05/cygwin-prompt-here-3.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/05/cygwin-prompt-here-3.jpg" alt="cygwin-prompt-here-3" title="cygwin-prompt-here-3" width="293" height="208" class="alignnone size-full wp-image-902" /></a>
</p>
<p>Hope you found this helpful!</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2009/05/16/open-cygwin-bash-shell-here/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>JavaScript functions: First-class objects</title>
		<link>http://unitstep.net/blog/2009/03/23/javascript-functions-first-class-objects/</link>
		<comments>http://unitstep.net/blog/2009/03/23/javascript-functions-first-class-objects/#comments</comments>
		<pubDate>Tue, 24 Mar 2009 02:55:05 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[functions]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=806</guid>
		<description><![CDATA[In JavaScript, functions are first-class objects, meaning that they can be created, manipulated and passed around in the same manner as other objects/variables in JavaScript. For example, a function can be created, stored in a variable or even be the return value of another function, as seen below: function getPower(power) { return function(x) { return [...]]]></description>
			<content:encoded><![CDATA[<p>In JavaScript, <a href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Functions_and_function_scope">functions are first-class objects</a>, meaning that they can be created, manipulated and passed around in the same manner as other objects/variables in JavaScript.  For example, a function can be created, stored in a variable or even be the return value of another function, as seen below:</p>
<pre><code>function getPower(power)
{
  return function(x)
  {
    return Math.pow(x, power);
  }
}

var x3 = getPower(3);
window.alert(x3(3)); // Outputs 27.</code></pre>
<p>In the rather stupid and contrived example above, we make a function <code>getPower()</code> that returns another function which raises the given value to the exponent supplied by calling <code>getPower()</code>.  (This is a bad way to do things for numerous reasons, but is just shown for the sake of providing a simple example)</p>
<p>We then call <code>getPower</code> with a power of 3 and assign the returned function to the variable <code>x3</code>, and the output is as expected.  Defining &#8220;inline&#8221; functions this way and manipulating them is closely associated with the concept of anonymous functions.</p>
<h2>Functions: Copied and passed by reference</h2>
<p>Since functions are objects, and <a href=" http://nefariousdesigns.co.uk/archive/2006/05/object-oriented-javascript/">objects are passed and copied <em>by reference</em></a>, <a href="https://developer.mozilla.org/Talk:En/Core_JavaScript_1.5_Guide/Defining_Functions">the behaviour</a> should be fairly straightforward to those familiar with the concept.  Here&#8217;s a quick example of what I&#8217;m talking about.  Since JavaScript functions can be treated just like plain old objects, this means we can attach arbitrary properties to them &#8211; let&#8217;s see how that relates to making a &#8220;copy&#8221; of a function:</p>
<pre><code>function test() {window.alert("A Test");}
f = window.test;
window.test.aProperty = 'Hello!';
window.alert(f.aProperty); // Outputs "Hello!"

f.aProperty = 'Goodbye!';
window.alert(window.test.aProperty); // Outputs "Goodbye!"</code></pre>
<p>The key here is that the expression <code>f = window.test;</code> doesn&#8217;t make a complete copy of the function; instead it just ensures that the variable <code>f</code> will point at the same function object as <code>window.test</code>.  So expressions that modify the underlying function object and its data will reflect in both <code>window.test</code> <strong>and</strong> <code>f</code>.  Just think of those two variables as being different ways of accessing the same underlying data.</p>
<p>But let&#8217;s consider another example: <strong>What happens if we make a copy of a function and then redefine the original?</strong></p>
<pre><code>function test() {window.alert("A Test");}

f = window.test;
f(); // "A Test"

// Redefine the original function.
test = function() {window.alert("A changed test");};

f(); // Still "A Test"!
window.test(); // "A changed test"</code></pre>
<p>The results are a bit strange &#8211; it appears that when we redefine <code>test</code>, the changes <strong>are not reflected</strong> in the copy we created in variable <code>f</code>! Why is this?</p>
<p>Closer inspection yields the following answer: <strong>We were not actually redefining the function pointed to by <code>test</code></strong>.  Instead, we created a new <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function"><code>Function</code></a> object in memory and then &#8220;pointed&#8221; <code>test</code> at this new function.  The old function, formerly referenced by <code>test</code>, is still referenced by the variable <code>f</code> so that is why it continues to invoke that code.</p>
<p>This is illustrated by the following diagrams.  In the first, the original function has been defined and two variables refer to it.</p>
<p class="image">
<img src="http://unitstep.net/wordpress/wp-content/uploads/2009/03/javascript-function-1.png" alt="javascript-function-1" title="javascript-function-1" width="272" height="75" class="alignnone size-full wp-image-815" />
</p>
<p>In the second diagram, we have created a new function and altered the variable <code>test</code> to refer to it; however the variable <code>f</code> still refers to the original function.  Thus, the important thing to note is that when using the assignment operator for functions, they are copied by reference.</p>
<p class="image">
<img src="http://unitstep.net/wordpress/wp-content/uploads/2009/03/javascript-function-2.png" alt="javascript-function-2" title="javascript-function-2" width="280" height="130" class="alignnone size-full wp-image-816" /><br />
The original function is still referenced by <code>f</code>
</p>
<h2>Where this matters</h2>
<p>This point has relevance when talking about event handlers.  Typically, when we bind functions to a specific events this involves copying a function reference over to some other variable or property.  Whether we directly do this using <a href="http://www.quirksmode.org/js/events_tradmod.html">traditional event registration</a> by using an expression like <code>element.onclick = someFunction</code> or whether it&#8217;s done using jQuery&#8217;s <a href="http://docs.jquery.com/Events">Event Helpers</a>, the effect is the same.</p>
<p>This means that after assigning the event handler, <strong>we cannot simply modify the original function to make changes to how the event handler works</strong>.  This is because when we assign a new function the old one will still be referenced by the event handler.  The proper way to do this at runtime would be simply to register the new function to the event and deregister the old one.</p>
<p>Another way to think of it is that you can often register anonymous functions to events; since they are anonymous you won&#8217;t have a reference to them after you assign them to the event handler so there is no way to modify them after the fact.  This same logic applies equally when assigning non-anonymous functions to events.</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2009/03/23/javascript-functions-first-class-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using the Basic Constraints extension in X.509 v3 certificates for intermediate CAs</title>
		<link>http://unitstep.net/blog/2009/03/16/using-the-basic-constraints-extension-in-x509-v3-certificates-for-intermediate-cas/</link>
		<comments>http://unitstep.net/blog/2009/03/16/using-the-basic-constraints-extension-in-x509-v3-certificates-for-intermediate-cas/#comments</comments>
		<pubDate>Tue, 17 Mar 2009 03:15:36 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[certificates]]></category>
		<category><![CDATA[cryptography]]></category>
		<category><![CDATA[guides]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[pki]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[X.509]]></category>
		<category><![CDATA[bouncy castle]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[extensions]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=773</guid>
		<description><![CDATA[It&#8217;s not often that you&#8217;ll be creating your own X.509 certificates for a web server, since any certificates that you create (self-signed or signed by your own CA) will not be trusted by most browsers (IE, Firefox, etc.) since they were not signed by one of the many Certificate Authorities (CAs) that have been automatically [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s not often that you&#8217;ll be creating your own X.509 certificates for a web server, since any certificates that you create (self-signed or signed by your own CA) will not be trusted by most browsers (IE, Firefox, etc.) since they were not signed by one of the many Certificate Authorities (CAs) that have been automatically trusted by the browser.  If you do decide to use one of these certificates on your web server, you&#8217;ll have to navigate through <a href="http://blog.ivanristic.com/2008/04/firefox-3-ssl-i.html">a Byzantine series of screens to &#8220;confirm&#8221; that you trust the server&#8217;s certificate</a>.  (Though this is annoying, it may be ultimately beneficial in today&#8217;s era of phishing and other malicious behaviour.)</p>
<h2>A bit of background</h2>
<p>However, what I want to discuss today relates to <em>certificate chains</em>.  At the top of every certificate chain is a <strong>root CA</strong>, whose certificate is <em>self-signed</em>.  This sort of certificate can be considered a &#8220;God certificate&#8221; because it essentially says, <em>&#8220;Trust me, because I say so&#8221;</em>.  As you can imagine, that&#8217;s not much of an argument for trusting someone, so that is why your browser has a list of <em>default root CAs</em> that it automatically trusts.  </p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/03/basic-constraints-0.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/03/basic-constraints-0-300x207.jpg" alt="basic-constraints-0" title="basic-constraints-0" width="300" height="207" class="alignnone size-medium wp-image-775" /></a><br />
Some default trusted CAs in Firefox.
</p>
<p>These root CAs are owned and operated by companies that are in the business of <em>issuing certificates</em> to other people for use on their servers.  They have been added to the default trusted list of most browsers so that an end user doesn&#8217;t need to manually add all of them; doing so would be a usability nightmare.  Essentially, these root CAs provide a <strong>trust anchor point</strong>, as not only are they trusted, but <em>any certificates they issue will also be automatically trusted by the browser</em>.  Attempting to visit a HTTPS/SSL website that does not have a trusted certificates results in a <a href="http://jeremy.visser.name/2008/01/26/firefox-3-ssl-error/">nasty warning from modern browsers</a>.</p>
<p>Rarely is the root CA certificate directly used for a web server, but instead it is used to <strong>sign or issue other certificates</strong> that are then used on a web server to confirm its identity and provide for secure end-to-end communication.</p>
<p>As you can imagine, operating a CA is an immense responsibility, so that is why these default lists have been setup: Essentially these companies have to vet entities that purchase certificates from them, to make sure they actually own the domain that they are trying to buy a certificate for, otherwise phishing would become too easy!  Even so, these companies sometimes still have <a href="http://www.win.tue.nl/hashclash/rogue-ca/">lapses due to use of outdated technologies and poor security practices</a>, but that is another complicated issue for another day.</p>
<h2>Issuing a certificate &#8211; An example</h2>
<p>The act of <strong>issuing a certificate</strong> essential entails a CA using its public-private key pair to sign the contents of the certificate that is being issued.  This ties the identity information in the certificate to its key pair and provides confirmation that the CA has affirmed the authenticity of the certificate, I.E., that it has truly issued this certificate and that it has not been forged.</p>
<p>Going back to a certificate chains, it was previously mentioned that the root CA certificate is at the top of the chain.  Any certificates it issues are directly below it, so if these certificates are directly used on a web server, then the chain is of length two.  However, certificate chains can be longer.  If a certificate chain is longer than two, then this indicates the presence of an <strong>intermediate CA</strong>.</p>
<p>An intermediate CA is a CA that does not have a self-signed certificate but still has the capability to issue certificates that are trusted.  For an example of the root CA to intermediate CA relationship, we can look at the certificate chain returned from <a href="https://mail.google.com">https://mail.google.com</a>:</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/03/basic-constraints-1.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/03/basic-constraints-1-254x300.jpg" alt="basic-constraints-1" title="basic-constraints-1" width="254" height="300" class="alignnone size-medium wp-image-785" /></a><br />
The Root CA certificate from VeriSign, an X.509 v1 certificate.
</p>
<p>Above we see the <em>root CA certificate</em>, a self-signed certificate created/issued by <strong>VeriSign</strong>.  I&#8217;ve highlighted the fact that it is an X.509 <strong>version 1</strong> certificate, which also means it doesn&#8217;t have any <strong>certificate extensions</strong>.  This may not mean much right now, but we&#8217;ll get back to it soon.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/03/basic-constraints-2.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/03/basic-constraints-2-254x300.jpg" alt="basic-constraints-2" title="basic-constraints-2" width="254" height="300" class="alignnone size-medium wp-image-787" /></a><br />
The Intermediate CA certificate from Thawte, an X.509 v3 certificate.
</p>
<p>This next shot shows the <em>intermediate CA certificate</em> that was issued by the root CA.  This certificate has been issued to <strong><a href="http://en.wikipedia.org/wiki/Thawte">Thawte</a></strong>, a company coincidentally founded by Mark Shuttleworth, the South African man behind Canonical/Ubuntu.  Thawte was acquired by VeriSign during the dot-com craze for US $575 million.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/03/basic-constraints-3.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/03/basic-constraints-3-254x300.jpg" alt="basic-constraints-3" title="basic-constraints-3" width="254" height="300" class="alignnone size-medium wp-image-788" /></a><br />
The &#8220;Basic Constraints&#8221; extension of the intermediate CA.
</p>
<p>We can clearly see that this certificate is an X.509 <strong>version 3</strong> certificate, meaning it does support certificate extensions.  One of its extensions is a <strong><a href="http://www.alvestrand.no/objectid/2.5.29.19.html">Basic Constraints</a></strong> extension, which has been set to signify that this is indeed a Certificate Authority.  It also specifies one other parameter, which is the maximum number of intermediate CAs allowed <em>beneath</em> this one in the certificate chain hierarchy.  Since this value is set to 0, this means this intermediate CA <strong>cannot</strong> issue any more CA certificates, but instead can only issue <strong>client certificates</strong>.  Any attempt will to use a client certificate from this CA as a CA or signing certificate will fail, when consumed by a conforming client.</p>
<h2>The client certificate</h2>
<p>The last screenshot shows the <strong>client certificate</strong>, which is the last certificate in the chain.  This is the certificate that is used by the server at <code>mail.google.com</code> to secure HTTPS traffic, and as we can see, it is also an X.509 v3 certificate (has extensions) and one of those extensions is the &#8220;Basic Constraints&#8221; extension.  This time it is set to indicate that this is <strong>not</strong> a CA certificate.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/03/basic-constraints-4.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/03/basic-constraints-4-254x300.jpg" alt="basic-constraints-4" title="basic-constraints-4" width="254" height="300" class="alignnone size-medium wp-image-789" /></a><br />
The Basic Constraints of the client certificate, indicating it is <strong>not</strong> a CA certificate.
</p>
<h2>Basic Contraints &#8211; Why it&#8217;s needed</h2>
<p>The &#8220;<strong>Basic Constraints</strong>&#8221; extension is one way for a CA to control the usage of the certificates it issues.  For instance, when the root CA certificate in the example above issued the intermediate CA certificate, it set the Basic Constraints extension to signify that:</p>
<ul>
<li>The issued certificate is for a Certificate Authority, i.e. an intermediate CA.</li>
<li>This certificate <strong>may not</strong> be used to create further CA certificates</li>
</ul>
<p>In turn, the intermediate CA certificate was used to create the client certificate for <code>mail.google.com</code>, and it attached a Basic Constraints extension to signify that this certificate <strong>was not</strong> a CA certificate.  By doing this, it was indicating that this certificate should not be used to sign/create further certificates.</p>
<p>This is necessary because of the how trust relationship works in X.509 PKI.  Someone who trusts the root CA implicitly trusts all the intermediate CAs, and then by extension, all the client certificates issued by those intermediate CAs! (Note how this creates a single point-of-failure at the root CA as well)</p>
<p>If the CA could not control what the certificates it issued were used for, then someone could purchase a VeriSign certificate and use it to sign/create other certificates which would also be trusted by default! Clearly, this is not desirably from a security or financial point of view, if you are VeriSign.  By using extensions such as the Basic Constraints one, the signing CA can enact fine-grained control over how the certificate is used.  If the client certificate was used to sign another certificate, that certificate would be rejected by a browser that conformed to the X.509 v3 specifications.</p>
<h2>The Grey Area</h2>
<p>However, we run into a &#8220;grey area&#8221; of sorts when faced with a certificate that <strong>does not have a Basic Constraints extension</strong>.  In this case, it is not indicated whether this is a CA certificate or not.  How do the browsers respond in this scenario? In this case, it seems to depend on whether the CA is a root CA or an intermediate one.</p>
<p>For root CA certificates, it seems that the Basic Constraints extension is not required in order for the CA certificate to be viewed as valid from the browser&#8217;s point of view.  (I&#8217;ve observed this in Firefox and Internet Explorer)  This most likely stems from the fact that there are root CAs that were created and put into operation well before X.509 v3 extensions were in wide use.  The VeriSign root CA in our example is an X.509 v1 certificate with a starting validity date of 1996-01-28.</p>
<p>However, for intermediate CAs, it seems that the Basic Constraints extension <strong>is required</strong> if you want things to work, at least in Firefox and Internet Explorer.  I encountered this situation when working with a Private Root CA of my own.  I was trying to create an intermediate CA (without any Basic Constraints extension) from this root CA, and was running into problems when using this intermediate CA to create client certificates.  Any of the client certificates from the intermediate CA were being essentially rejected by the browser when attempting to visit the website they were being used for.</p>
<p>Because this was a &#8220;grey area&#8221;, the results were mixed.  In Firefox, the site would load correctly, however when attempting to view the certificate chain (by double-clicking the lock icon in the lower right), only the client certificate could be viewed, not the fully certificate chain.  Internet Explorer would show the full certificate chain but simply failed to load the page.  Neither browser gave any indication as to why things were failing.</p>
<p>However, once I created an Intermediate CA with a Basic Constraints extension set to explicitly signify that this was indeed a CA, everything worked as expected.  I don&#8217;t believe this is well-documented, though this is understandable since most people will not be creating their own Private CAs unless it&#8217;s for a very specialized purpose.</p>
<h2>How to do this using the Bouncy Castle APIs</h2>
<p>I&#8217;ve talked about the <a href="/blog/2008/10/27/extracting-x509-extensions-from-a-csr-using-the-bouncy-castle-apis/">Bouncy Castle Java APIs</a> before, and they have been an invaluable resource for simplifying the creation of a Private CA and for issuing certificates.</p>
<p>When issuing a certificate it&#8217;s fairly easy to set the Basic Constraints extension to indicate you want the certificate to be a CA certificate.  First, take a look at this <a href="http://www.bouncycastle.org/wiki/display/JA1/X.509+Public+Key+Certificate+and+Certification+Request+Generation">guide to under the fundamentals of certificate creation</a> with the Bouncy Castle APIs, then look at this code fragment:</p>
<pre><code>private static final int NUM_ALLOWED_INTERMEDIATE_CAS = 0;
...

// Construct the certificate.
final X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

...

// Need this extension to signify that this certificate is a CA and
// can issue certificates. (Extension is marked as critical)
certGen.addExtension( X509Extensions.BasicConstraints, true, new BasicConstraints(
  NUM_ALLOWED_INTERMEDIATE_CAS ) );

...

final X509Certificate intermediateCaCert = certGen.generate( signingCaPrivateKey, "SunRsaSign" );</code></pre>
<p>By doing this you ensure that the intermediate CA certificate has the proper Basic Constraints extension to work correctly with modern web browsers.</p>
<h2>Conclusion</h2>
<p>I hope you found this helpful.  Certainly if you&#8217;re here, you&#8217;ve been puzzled over the same issues that I struggled through!</p>
<h3>References</h3>
<ol class="note less">
<li><a href="http://www.bouncycastle.org/wiki/display/JA1/X.509+Public+Key+Certificate+and+Certification+Request+Generation">X.509 Public Key Certificate and Certification Request Generation</a></li>
<li><a href="http://www.alvestrand.no/objectid/2.5.29.19.html">OID 2.5.29.19 &#8211; Basic Constraints</a></li>
<li><a href="http://www.oid-info.com/get/2.5.29.19">OID Repository &#8211; basicConstraints(19)</a></li>
</ol>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2009/03/16/using-the-basic-constraints-extension-in-x509-v3-certificates-for-intermediate-cas/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>JavaScript Event Delegation</title>
		<link>http://unitstep.net/blog/2009/02/19/javascript-event-delegation/</link>
		<comments>http://unitstep.net/blog/2009/02/19/javascript-event-delegation/#comments</comments>
		<pubDate>Fri, 20 Feb 2009 03:47:44 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[user interface]]></category>
		<category><![CDATA[XHTML]]></category>
		<category><![CDATA[event delegation]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=720</guid>
		<description><![CDATA[JavaScript Event Delegation is a technique you may have heard of. It&#8217;s a different way of using event handlers that offers clear benefits and is becoming more popular amongst web developers. I&#8217;ll give a brief overview of event delegation in JavaScript, along with why you should consider it. Note that this tutorial will use the [...]]]></description>
			<content:encoded><![CDATA[<p>JavaScript Event Delegation is a technique you may have <a href="http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery">heard of</a>.  It&#8217;s a different way of using event handlers that offers clear benefits and is becoming more popular amongst web developers.  I&#8217;ll give a brief overview of event delegation in JavaScript, along with why you should consider it.  Note that this tutorial will use the great <a href="http://jquery.com">jQuery</a> library (v. 1.3.1) for most examples.</p>
<h3>Delegation</h3>
<p><a href="http://en.wikipedia.org/wiki/Delegation_pattern">Delegation</a> is a fairly well-known design pattern.  In short, it is a way for a method to produce its result simply by calling a method on another object, thus <em>delegating</em> responsibility to that object to provide the functionality needed by the method.  For example, a <code>Cashier</code> object could store a delegate object called <code>Calculator</code>.  Calling <code>Cashier.addToTotal(value)</code> would simply delegate to the contained object, calling <code>Calculator.addToTotal(value)</code>.  </p>
<p>How is delegation different than <em>inheritance</em>?  With inheritance, the subclass inherits all of the functionality/behaviour of the parent class.  You may not want or need this; in the preceding example, it would not make sense to have <code>Cashier</code> extend from <code>Calculator</code> simply because we wanted the <code>addToTotal()</code> behaviour/functionality.  Delegation allows the behaviour advertised by a certain object/class to be provided by another.</p>
<h3>Traditional Event Handling</h3>
<p>In order to understand event delegation in JavaScript, we should first look briefly at how events are handled traditionally.  When I talk of <em>traditional event handling</em>, I am referring to the model that most will know.  In this model, functions are <strong>individually</strong> bound to events of certain elements.  For example, to make all links turn bold upon clicking them (and prevent them from being followed), we could use some JavaScript like this:</p>
<pre><code>window.onload = function()
{
  links = document.getElementsByTagName('a');
  for (var i = 0; i &lt; links.length; ++i)
  {
    links[i].onclick = makeBold;
  }

}

function makeBold()
{
  this.style.fontWeight = 'bold';
  return false;
}</code></pre>
<p>The key point with this example is that the function <code>makeBold()</code>, our <em>event handler</em>, is <strong>bound to each and every</strong> <code>a</code> element.  From a resource point of view, this is may be a bad thing because the more event handlers that are attached, the more memory that is used, in general.</p>
<p>Of course, I promised I&#8217;d be using jQuery, and doing so cleans up the above code substantially, as well as making it cross-browser compatible: (Besides adding a ton of other abilities and making life easier)</p>
<pre><code>jQuery(function()
{
  jQuery('a').click(makeBold);
});

function makeBold(e)
{
  e.preventDefault();
  jQuery(this).css('font-weight', 'bold');
}</code></pre>
<p>While this code is cleaner, it still does basically the same thing as above, that is, the event handler function <code>makeBold()</code> is bound to <strong>each</strong> matched element, that is, each <code>a</code> element.</p>
<p>As a final note, don&#8217;t confuse my use of the term <em>traditional</em> with <a href="http://www.quirksmode.org/">Peter-Paul Koch&#8217;s</a> excellent guide to JavaScript event registration, where he uses the term <a href="http://www.quirksmode.org/js/events_tradmod.html"><em>traditional</em> to refer to one <em>method</em> of event registration</a>, distinct from inline registration and the later <a href="http://www.w3.org/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="World Wide Web Consortium">W3C</acronym></a> and Microsoft &#8220;Advanced&#8221; event registration models.</p>
<h3>Event handling using delegation</h3>
<p>By contrast, <strong>event delegation</strong> uses a single (or comparatively few) event handlers to implement the behaviour required.  This takes advantage of two key features of JavaScript events, namely <strong><a href="http://www.quirksmode.org/js/events_order.html#link3">event bubbling</a></strong> and the <strong><a href="http://docs.jquery.com/Events/jQuery.Event#event.target">target event</a></strong>.</p>
<p><strong>Event bubbling</strong> is a model for how events take place on the page.  It grew out of a need to resolve the order in which events were triggered on ancestor and descendant elements.  For example, assume that I have two event handlers, one attached to the &#8220;click&#8221; event of a <code>div</code> and another attached to the &#8220;click&#8221; event of an <code>a</code> element <strong>within</strong> that <code>div</code>.  If I click the <code>a</code> element, which event fires first?  Event bubbling is one way to solve that question: It states that the event on the <strong>inner</strong> element happens <em>first</em>, and then the event &#8220;bubbles&#8221; upwards to trigger events on ancestor or container elements.  There is another opposing model that works in the opposite way, but bubbling seems to be better supported and is more relevant for this article.</p>
<p>Here&#8217;s a crude diagram of event bubbling, using a pseudo-<a href="http://www.w3.org/TR/CSS21/box.html"><acronym class="uttInitialism" title="Cascading Style Sheets">CSS</acronym> box model</a> of sorts:</p>
<p class="image">
<img src="http://unitstep.net/wordpress/wp-content/uploads/2009/02/javascript-event-delegation.png" alt="Event Bubbling Diagram" title="Event Bubbling Diagram" width="302" height="228" class="size-full wp-image-747" /><br />
Event bubbling diagram
</p>
<p>The <strong>event target</strong> is the DOM element that issued the event, or the originating element.  This is why I believe it&#8217;s a confusing term, since it would make more sense to called it the <em>event source</em>.  But I digress.  The <a href="https://developer.mozilla.org/En/DOM/Event">event object</a>, passed to an event handler as an argument (or available via <code>window.event</code>, though jQuery normalizes this) contains a property, <code>event.target</code>, that allows you to get the reference to the &#8220;target&#8221; element that the event started bubbling up from.</p>
<h3>How it&#8217;s implemented</h3>
<p>All of this is typically accomplished by registering a single event handler to a &#8220;container&#8221; element that holds all of the elements we wish to react to events for.  When an event is triggered on one of the inner elements, it &#8220;bubbles up&#8221; to the container element, where it triggers the event handler function.  From there, we can inspect the source of the event (confusingly called the <em>event target</em>) and then react accordingly.</p>
<p>This is where the delegation aspect comes into play.  Since the container element may hold many inner elements, it is unlikely that we would want the same behaviour for each element when an event was triggered on it.  For example, we might want certain <code>a</code> elements to trigger one action when clicked, while wanting another set of <code>a</code> elements to trigger another action.  We&#8217;d typically differentiate these links by using separate class names or by context and then attaching event handlers as appropriate.</p>
<p>Using event delegation, process is similar, but instead of attaching multiple event handlers we have one on the overall parent element.  When this event handler is triggered, we determine which element triggered the event and then based on this, delegate the remainder of the processing to another function.  An example would be helpful now, as our previous examples with making some text bold weren&#8217;t too useful.  Here&#8217;s the <a href="http://www.w3.org/MarkUp/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="eXtensible HyperText Markup Language - HTML reformulated as XML">XHTML</acronym></a> fragment for the container and elements.</p>
<pre><code >&lt;div class="container"&gt;
&lt;ul class="top"&gt;
  &lt;li&gt;
    &lt;a href="#" class="expandList"&gt;Item A - Click to toggle&lt;/a&gt;
    &lt;ul class="hide"&gt;
      &lt;li&gt;Sub-item 1&lt;/li&gt;
      &lt;li&gt;Sub-item 2&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;a href="#" class="expandList"&gt;Item B - Click to toggle&lt;/a&gt;
    &lt;ul class="hide"&gt;
      &lt;li&gt;Sub-item 1&lt;/li&gt;
      &lt;li&gt;Sub-item 2&lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;
  &lt;li&gt;&lt;a href="#" class="remove"&gt;Item C - Click to remove&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href="#" class="remove"&gt;Item D - Click to remove&lt;/a&gt;&lt;/li&gt;
&lt;/div&gt;</code></pre>
<p>And here&#8217;s the JavaScript:</p>
<pre><code>jQuery(function()
{
  jQuery('div.container').click(handleEvent);
});

function handleEvent(e)
{
  // Obtain the source element through event.target.
  var target = jQuery(e.target);

  // Now decide what to do with it.
  if (target.is('a.expandList'))
  {
    // We use Function.call() to set the context for the `this` keyword.
    return expandList.call(target, e);
  }
  else if (target.is('a.remove'))
  {
    return remove.call(target, e);
  }
  else
  {
    // Otherwise, allow the default action to take place.
    return true;
  }
}

function expandList(e)
{
  e.preventDefault();

  // The `this` keyword now references the jQuery object representing the
  // target, since that is what we set the context to.
  jQuery(this).parent('li').find('ul.hide').slideToggle('fast');
}

function remove(e)
{
  e.preventDefault();
  jQuery(this).parent('li').fadeOut('normal', function(){jQuery(this).remove()});
}</code></pre>
<p>With this example, the steps are clearly outlined.  First, we attach the overall event handler to the container element; events that take place on its inner or children element will bubble up to it.  When an event is received, we inspect <code>event.target</code> to determine the origin and based on that, &#8220;hand off&#8221; to another function to carry out the proper behaviour. </p>
<p>With some standardization of the <acronym class="uttInitialism" title="Cascading Style Sheets">CSS</acronym> class names you use and the associated event handler function names, you can clean up this code to reduce duplication and turn it into a design pattern of sorts.  In fact, that&#8217;s <a href="http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery">exactly what Dan Webb has done</a>.</p>
<h3>More advantages of event delegation</h3>
<p>Besides potentially using less resources by having less event handlers bound, event delegation brings one other significant advantage: <strong>The ability to have event handlers &#8220;auto bind&#8221; to new DOM elements</strong>.  For example, let&#8217;s say we were to dynamically update the DOM and add more list items to our previous example; this sort of action happens frequently during Ajax operations where you want to present new content to the user.  </p>
<p>In the &#8220;traditional&#8221; event handling model, the new elements <strong>would not automatically respond to events</strong> as you would like.  This is because the events were individually bound to each element.  This is <a href="http://docs.jquery.com/Frequently_Asked_Questions#Why_do_my_events_stop_working_after_an_AJAX_request.3F">a well known problem</a>.  However, in event delegation, since there&#8217;s only one event handler bound to the <strong>container or ancestor element</strong>, the newly-created elements will respond to the event properly! This is because an event on them &#8220;bubbles&#8221; up to the container element just as for the original elements.</p>
<h3><a href="/projects/javascript-event-delegation/javascript-event-delegation.html">Demo of Event Delegation</a></h3>
<p>Perhaps <a href="/projects/javascript-event-delegation/javascript-event-delegation.html">a little demo</a> is needed.  With this demo, you can see both the implementation of event delegation as well as the effect of adding new elements.</p>
<h3>Drawbacks of event delegation</h3>
<p>I&#8217;ve already talked about some of the benefits (fewer bound event handlers, so less resources used and the ability to adapt with DOM changes), but it&#8217;s worthwhile to iterate over some of the drawbacks.  </p>
<ol>
<li>Firstly, not all elements &#8220;bubble up&#8221; in the way described.  The <code>blur</code>, <code>focus</code>, <code>change</code> and <code>submit</code> are notable exceptions so you will not be able to use event delegation with these events in the manner described in this article.</li>
<li>Furthermore, the code developed to maintain event delegation can be more complicated to understand than with just using the traditional model.  Indeed, there is an initial investment time everyone must make to get going.  This should obviously be considered since code maintenance is always important.</li>
<li>Because there&#8217;s one event handler being called for all events on inner/descendant elements, there can be some performance implications.  If you&#8217;re calling expensive functions within this event handler, the event processing could slow down significantly.  Careful optimization may be required.</li>
</ol>
<p>However, some of these drawbacks can be mitigated by using solutions developed by the jQuery community.  Even though event delegation is somewhat new, there are already plugins available that take a lot of the grunt-work out of event delegation, abstracting away the details and making things easier for you.  Even jQuery itself also supports event delegation through a built-in function as of v1.3.  Here are some options for pre-built solutions:</p>
<ul>
<li><a href="http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery">Dan Webb&#8217;s Delegate Plugin</a><br />
This is a fairly straightforward way to implement delegation and it&#8217;s easy to setup and understand.</li>
<li><a href="http://docs.jquery.com/Events/live#typefn">jQuery&#8217;s built in <code>live()</code> function</a><br />
This supports a subset of events but is good enough for most uses.</li>
<li><a href="http://plugins.jquery.com/project/livequery">The Live Query plugin</a><br />
This is your best bet if you need the most functionality, though I haven&#8217;t personally tried it out yet.</li>
</ul>
<h3>Conclusion</h3>
<p>Delegation nicely solves the problem of having to rebind events after adding new elements to the DOM.  For that reason alone, I&#8217;ve started to use in my work more often.  At its heart, it&#8217;s a useful design pattern, but should be only with full understanding of the pros and cons.  I hope you enjoyed reading this article!</p>
<h3>References</h3>
<ol class="note less">
<li><a href="http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery">Event Delegation Made Easy</a></li>
<li><a href="http://usabletype.com/weblog/event-delegation-without-javascript-library/">Event delegation without a JavaScript library</a></li>
<li><a href="http://www.sitepoint.com/blogs/2008/07/23/javascript-event-delegation-is-easier-than-you-think/">JavaScript Event Delegation is Easier than You Think</a></li>
<li><a href="http://docs.jquery.com/Frequently_Asked_Questions#Why_do_my_events_stop_working_after_an_AJAX_request.3F">Why do my events stop working after an <acronym class="uttAcronym" title="Asynchronous Javascript And XML">AJAX</acronym> request?</a></li>
</ol>
<h4>Revisions</h4>
<ul class="note less">
<li>2009-02-20: Added a crude diagram of event bubbling</li>
</ul>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2009/02/19/javascript-event-delegation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Getting Xdebug to work with Apache/XAMPP to debug PHP</title>
		<link>http://unitstep.net/blog/2009/01/26/getting-xdebug-to-work-with-apachexampp-to-debug-php/</link>
		<comments>http://unitstep.net/blog/2009/01/26/getting-xdebug-to-work-with-apachexampp-to-debug-php/#comments</comments>
		<pubDate>Tue, 27 Jan 2009 03:00:11 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[debug]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[eclipse]]></category>
		<category><![CDATA[guides]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=661</guid>
		<description><![CDATA[I&#8217;ve written about Eclipse and how useful it can be, with its extensible plugin-based system. It&#8217;s so useful that I use it everyday for almost any language &#8211; Java, PHP, JavaScript to name a few. It&#8217;s even great for things like CSS and XHTML. PHP is currently my favourite &#8220;hobby&#8221; language and has been for [...]]]></description>
			<content:encoded><![CDATA[<p class="image align-right"><a href="http://xdebug.org/"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/01/xdebug-logo.png" alt="xdebug-logo" title="xdebug-logo" width="200" height="116" /></a></p>
<p>I&#8217;ve written <a href="/blog/2008/02/10/eclipse-the-best-and-only-ide-youll-ever-need/">about Eclipse</a> and how <a href="/blog/2008/01/19/using-assemblas-trac-with-eclipse-mylyn-xml-rpc-access/">useful it can be</a>, with its extensible plugin-based system. It&#8217;s so useful that I use it everyday for almost any language &#8211; Java, <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym>, JavaScript to name a few.  It&#8217;s even great for things like <acronym class="uttInitialism" title="Cascading Style Sheets">CSS</acronym> and <a href="http://www.w3.org/MarkUp/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="eXtensible HyperText Markup Language - HTML reformulated as XML">XHTML</acronym></a>. </p>
<p><acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> is currently my favourite &#8220;hobby&#8221; language and has been for some time.  While I like <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym>, one of the things that hasn&#8217;t been straightforward with it is setting up a proper debug session, where you can step through code.  This contrasts heavily with a language like Java, which has always had strong developer tools.  This has resulted in a mass of third-party tools aimed at facilitating <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> debugging.  A while ago, a reader emailed me asking about this very topic, so I decided to put together how-to detailing my experience with the topic and how I went about learning it.</p>
<h2>Xdebug for <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> and XAMPP</h2>
<p>The debugger I&#8217;ll be using will be <a href="http://www.xdebug.org/">Xdebug</a>. Because <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> provide no built-in debugging tools, there are many third-party options for debugging. (See the &#8220;Debugging Tools&#8221; section of <a href="http://www.smashingmagazine.com/2009/01/20/50-extremely-useful-php-tools/">this article</a> for more) However, Xdebug seems to be one of the more popular ones, and <a href="http://www.eclipse.org/pdt/">Eclipse PDT</a> already has support for it.</p>
<p>This guide also assumes use of <a href="http://www.apachefriends.org/en/xampp.html">XAMPP</a>, the great all-in-one solution for quickly setting up a web development environment and to get your code running on the server. XAMPP is great for hitting the ground running, though you&#8217;ll probably not want to use it in a production environment &#8211; though you likely won&#8217;t be debugging there either.  Nevertheless, the instructions provided here should work even if you&#8217;ve setup Apache and <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> separately on your own.</p>
<h2>Getting started</h2>
<p>The first thing you&#8217;ll want to do is head over the <a href="http://www.xdebug.org/download.php">Xdebug</a> page and download the appropriate Zend extension of Xdebug corresponding to the version of <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> you&#8217;re running.  Save the file into your <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> extension path/folder.  Now you&#8217;ll have to edit your <code>php.ini</code> file to begin using the plugin.  The plugin basically exposes or provides an interface for the client debugger (running in Eclipse or your IDE) to attach to the server and debug/trace through the code that&#8217;s running on it.  If you&#8217;re from the Java world, you&#8217;ll know this as &#8220;remote debugging&#8221;, which is provided by most J2EE application servers.</p>
<p>You&#8217;ll also want to have downloaded <a href="http://www.eclipse.org/pdt/">Eclipse PDT</a> have that installed as your IDE, if you haven&#8217;t already done so.  <a href="http://www.zend.com/en/products/studio/">Zend Studio for Eclipse</a> also works, since it&#8217;s based on Eclipse PDT, and offers quite a few more features, out of the box.</p>
<h2>Setting up Xdebug</h2>
<p>You should have already saved the Xdebug extension DLL file to your <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> extension folder.  Record down the full path of it.  Now, open up your <code>php.ini</code> file and go down to the <code>[XDebug]</code> section, or create it if it&#8217;s not there.  Uncomment or add the following lines:</p>
<pre><code>;; Only Zend OR (!) XDebug
zend_extension_ts="D:\XAMPP\php\ext\php_xdebug.dll"
xdebug.remote_enable=On
xdebug.remote_host="localhost"
xdebug.remote_port=9000
xdebug.remote_handler=dbgp</code></pre>
<p>The <code>zend_extension_ts</code> should point to location of your Xdebug extension DLL that you downloaded earlier; modify as appropriate.</p>
<p>Then, you <strong>should disable the Xdebug entry in the list of dynamic extensions</strong>. This is confusing, but since we are already setting up Xdebug as a Zend extension, we don&#8217;t need another entry.  Disable the Xdebug dynamic extension by ensuring the following line is commented out, like below:</p>
<pre><code>;extension=php_xdebug.dll</code></pre>
<p>There is one last very important step you need to do, particularly if you are running XAMPP.  <strong>Current versions of Xdebug are incompatible with the Zend optimizer that is enabled by default in XAMPP, so you must disable that if you want Xdebug to work</strong>.  If you don&#8217;t, you&#8217;ll notice that Apache will crash every time you try to load it with Xdebug enabled.  To disable the Zend optimizer, find the <code>[Zend]</code> section in <code>php.ini</code> and comment out all of the entries under it, like so: (This is an example, there may be more to comment out)</p>
<pre><code>[Zend]
;zend_extension_ts = "D:\XAMPP\php\zendOptimizer\lib\ZendExtensionManager.dll"
;zend_extension_manager.optimizer_ts = "D:\XAMPP\php\zendOptimizer\lib\Optimizer"
;zend_optimizer.enable_loader = 0
;zend_optimizer.optimization_level=15
;zend_optimizer.license_path =</code></pre>
<p>You should be able to start Apache now without troubles.</p>
<h2>Configuring Eclipse for <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> debugging</h2>
<p>The next part will be configuring Eclipse as a debugging client.  Since the code will be executing on the web server (Apache), you&#8217;ll need Eclipse to &#8220;hook in&#8221; using the Xdebug protocol.  Thankfully, configuring Eclipse is fairly straightforward.</p>
<p>Open up Eclipse&#8217;s preferences and go to <strong>PHP -> Debug</strong>, and ensure that XDebug is selected as the <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> debugger.  This sets the default for debugging sessions and lessens the configuration required for each debug session.  You can also make sure that the default web server is <code>localhost</code> if that&#8217;s the case, which it&#8217;ll likely be for a lot of people doing development.</p>
<p><strong>Note that if you are running Zend Studio</strong>, you&#8217;ll need to <a href="http://www.maxhorvath.com/2008/08/how-to-enable-the-xdebug-debugger-in-zend-studio-for-eclipse.html">follow the steps in this article to enable Xdebug support</a>.  It seems that some versions of Zend Studio by default disabled support for the Xdebug plugin in lieu of their own Zend Debugger. </p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/01/php-debug-1.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/01/php-debug-1-300x241.jpg" alt="php-debug-1" title="php-debug-1" width="300" height="241" class="alignnone size-medium wp-image-695" /></a>
</p>
<p>Now you can select a file from a project you&#8217;d like to debug.  In my case, I&#8217;ve selected <code>src/demo/index.php</code> from my <a href="/blog/2008/03/29/a-challenge-response-ajax-php-login-system/">Challenge-Response <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> Login System</a> project.  Open the file, and then go to the <strong>Run Menu</strong> and select <strong>Debug Configurations&#8230;</strong> or <strong>Open Debug Dialog</strong>.</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/01/php-debug-2.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/01/php-debug-2-300x202.jpg" alt="php-debug-2" title="php-debug-2" width="300" height="202" class="alignnone size-medium wp-image-697" /></a>
</p>
<p>Double click the the &#8220;<acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> Web Page&#8221; entry on the left side bar to create a new debug profile.  Here, I&#8217;ve named it &#8220;CHAP-PHP&#8221;.  You should see a dialog like the one above.  Make sure the &#8220;Server Debugger&#8221; is again set to Xdebug and that the <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> Server is set to the localhost configuration you set up previously.  </p>
<p>Then you have to select the file you want to debug.  Click on &#8220;Browse&#8221;, and you&#8217;re confusingly taken to another view of your Eclipse projects; simply select the same file as before &#8211; you have to select a specific file, and not just a project or folder.</p>
<p>After that, you&#8217;ll need to adjust the <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> mapping.  You&#8217;ll probably need to uncheck &#8220;Auto Generate&#8221;, and then <strong>enter the <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> that corresponds to the <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> file you&#8217;re debugging</strong>.  Here, I&#8217;ve manually entered <code>/projects/CHAP/trunk/src/demo/</code> as the <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> fragment that triggers execution of the script.</p>
<p>If you want the debugger to stop right at the first line to allow you to immediately begin stepping through code, check &#8220;Break at First Line&#8221;. (It may be checked by default) Otherwise, uncheck it if you only want the debugger to stop at the breakpoints you&#8217;ve specified in Eclipse, which is the normal behaviour most developers will expect. </p>
<p>You should now be able to click &#8220;Debug&#8221;, and a debug session will launch, opening up the <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> you&#8217;ve specified and allowing you to step through code.  If you don&#8217;t like Eclipse using its own internal web browser (which appears just be a front for IE), you can configure which web browser you&#8217;d like it to launch URLs with by opening up Preferences and then going to <strong>General -> Web Browser</strong> and changing the setting to use an external web browser of your choice.  Personally, Firefox is my preference.</p>
<h2>Start your debugging engines!</h2>
<p>You can now get acquainted with stepping through code, which in my opinion, is one of the best ways to learn! When you launch a debug session, Eclipse should prompt you to switch to a new &#8220;perspective&#8221;, which is just a different layout of Eclipse&#8217;s internal windows that many believe better suit debugging through code.  </p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2009/01/php-debug-3.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2009/01/php-debug-3-300x227.jpg" alt="php-debug-3" title="php-debug-3" width="300" height="227" class="alignnone size-medium wp-image-698" /></a>
</p>
<p>You&#8217;re provided with an informative view of the script your currently debugging, along with the highlighted line that execution has paused on.  You can set debug breakpoints by double-clicking in the left margin of your source code view window; debug breakpoints show up as blue circles here.  The buttons at the top (green &#8220;Play&#8221;, red &#8220;Stop&#8221; and others) provide control over execution of the code, allowing you to step through code line-by-line, step into functions/methods and return from them.  I encourage you to experiment with all of the controls and get acquainted with the keyboard shortcuts.</p>
<p>Another panel also shows all the current variables available to the script as well as their values.  This is useful since you now do not need to <code>echo</code> anything to output or change any of the code to see values.  </p>
<p>When you&#8217;re done, you can just click the red &#8220;stop&#8221; button to disconnect from the server and end the debug session.  If you&#8217;ve completely stepped through a script, you will not be automatically disconnected from the server.  Instead, the debug client in <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> will patiently wait to debug the script again the next time it is executed.  This is useful to know, since you can just go back to the <acronym class="uttInitialism" title="Uniform Resource Locator">URL</acronym> in your web browser and reload the page to trigger the debug session to resume again. </p>
<h2>Conclusion</h2>
<p>I hope you found this useful, as when I was starting out trying to get a <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> debug session to work, it was somewhat frustrating. As always, I welcome your comments, suggestions and questions below via the comments form!</p>
<h3>References</h3>
<ol class="less note">
<li><a href="http://stackoverflow.com/questions/206788/why-does-xdebug-crash-apache-on-every-xampp-install-ive-tried">Why does xdebug crash apache on every XAMPP install I’ve tried?</a></li>
<li><a href="http://xdebug.org/docs/">Xdebug: Documentation</a></li>
<li><a href="http://www.maxhorvath.com/2008/08/how-to-enable-the-xdebug-debugger-in-zend-studio-for-eclipse.html">How to enable the Xdebug debugger in Zend Studio for Eclipse</a></li>
<li><a href="http://devzone.zend.com/article/2930-Debugging-PHP-applications-with-xdebug">Debugging <acronym class="uttInitialism" title="PHP: Hypertext Preprocessor">PHP</acronym> applications with Xdebug</a></li>
</ol>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2009/01/26/getting-xdebug-to-work-with-apachexampp-to-debug-php/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Handling mutable fields in Java</title>
		<link>http://unitstep.net/blog/2008/12/14/handling-mutable-fields-in-java/</link>
		<comments>http://unitstep.net/blog/2008/12/14/handling-mutable-fields-in-java/#comments</comments>
		<pubDate>Mon, 15 Dec 2008 02:11:27 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[mutability]]></category>
		<category><![CDATA[objects]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=604</guid>
		<description><![CDATA[In Java, a mutable object is one whose state can be altered after it has been instantiated. An immutable object is one whose state is fixed after instantiation; that is, the data represented by the object cannot be changed in that object. Perhaps the most well-known immutable type is the built in String class; while [...]]]></description>
			<content:encoded><![CDATA[<p>In Java, a <em>mutable</em> object is one whose state can be altered after it has been instantiated.  An <em>immutable</em> object is one whose state is fixed after instantiation; that is, the data represented by the object cannot be changed in that object.  Perhaps the most well-known immutable type is the built in <a href="http://java.sun.com/javase/6/docs/api/java/lang/String.html">String</a> class; while there are methods on the String class that seemingly alter its state (such as <code>toUpperCase()</code> and <code>trim()</code>), in actuality these methods return a <em>new</em> String object if changes had to be made.  In this article I&#8217;ll discuss how mutability will affect how you expose private fields in objects.</p>
<h2>Pop Quiz</h2>
<p>Consider the following code fragment.  We create a <code>MapContainer</code> object, and then get the contained map, which is guaranteed to have a certain value associated with the key &#8220;today&#8221;.  We then alter the value associated with this key, using our <em>local reference</em> to returned map.  We then query the <code>MapContainer</code> object and get the contained map again.  What is the value associated with the key &#8220;today&#8221; in this map?</p>
<pre><code>final MapContainer mapContainer = new MapContainer();
final Map&lt;String, String&gt; map = mapContainer.getKeyValuePairs();

final String today = map.get("today");
assert null != today;
System.out.println(today);  // Returns the current date-time.

// Change the value using our local reference.
map.put("today", "tomorrow");

final Map&lt;String, String&gt; mapAgain = mapContainer.getKeyValuePairs();
System.out.println(mapAgain.get("today")); // What is output?</code></pre>
<p>Don&#8217;t waste too much time on this problem, as it&#8217;s a trick question.  The answer actually depends on the implementation of <code>MapContainer</code>.  Depending on how it&#8217;s implemented, the second output could be unchanged from the first <strong>or</strong> be changed to the new value of &#8220;tomorrow&#8221;.</p>
<h2>It&#8217;s all in the getters</h2>
<p>Let&#8217;s take a look at the code for <code>MapContainer</code>.  </p>
<pre><code>import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MapContainer
{
  final private Map&lt;String, String&gt; keyValuePairs;

  public MapContainer()
  {
    this.keyValuePairs = new HashMap&lt;String, String&gt;();
    this.keyValuePairs.put("today", new Date().toString());
  }

  public Map&lt;String, String&gt; getKeyValuePairs()
  {
    return keyValuePairs;
  }
}</code></pre>
<p>We have a simple constructor that initializes the <code>keyValuePairs</code> Map and adds one value for the current date-time.  But the real &#8216;key&#8217; (no pun intended) to solving the problem is looking at the getter for the field.  As you can see, it simply returns a reference to the private field.  <strong>Under this implementation, a caller is able to alter the contents of the private field/Map even though no public &#8220;set&#8221; methods are available</strong>.  Why is this? For two reasons: In Java, objects are passed/returned by reference, and <code>HashMap</code> is a mutable object.  Thus using this implementation, the second output from our original code fragment is &#8220;tomorrow&#8221;, since the caller has altered the contents of the Map through the returned reference.</p>
<p>Furthermore, the original reference returned from the getter is not independent either; if some other code were to call the get method on the <code>MapContainer</code> object and make changes to the Map, those changes would also be reflected in the original returned reference!</p>
<p>How can we &#8220;fix&#8221; this? We simply have to ensure that the getter for the field returns a reference to a <em>copy</em> of the private Map.  This is easy since there is a <a href="http://java.sun.com/javase/6/docs/api/java/util/HashMap.html#HashMap(java.util.Map)">constructor for <code>HashMap</code></a> that accepts an existing Map.  Here&#8217;s the altered code:</p>
<pre><code>import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MapContainer
{
  final private Map&lt;String, String&gt; keyValuePairs;

  public MapContainer()
  {
    this.keyValuePairs = new HashMap&lt;String, String&gt;();
    this.keyValuePairs.put("today", new Date().toString());
  }

  public Map&lt;String, String&gt; getKeyValuePairs()
  {
    <strong>return new HashMap&lt;String, String&gt;(keyValuePairs);</strong>
  }
}</code></pre>
<p>With these changes, the private Map cannot be altered by a caller and thus the second output will remain changed in our first code fragment example.</p>
<h2>To change, or not to change?</h2>
<p>It should be noted that sometimes you <em>may want to allow</em> callers to alter the backing data structure that you return from a get method.  For example, some of the data structures from the <a href="http://java.sun.com/javase/6/docs/api/java/util/Collection.html">Java Collection Framework</a> have getters that return references that can be used to alter the state of the original object.  A good example is the <a href="http://java.sun.com/javase/6/docs/api/java/util/HashMap.html#entrySet()"><code>entrySet()</code></a> method of the <code>HashMap</code> object. </p>
<p>But in my opinion, these examples are the exception rather than the rule.  In general, you do not want to allow callers to be able to alter the state of private fields directly since this violates information-hiding principles.  If there is some change a caller needs to make to your object, it&#8217;s best accomplished through a set method since this allows you to control the changes and prevents unwanted/unexpected situations.  If you do decide to allow callers to directly alter the state of private fields, it&#8217;s best to explicitly document this in the JavaDoc.</p>
<h2>Mutability and safety</h2>
<p>Note that in this example the field used was a <code>HashMap</code> object, which was mutable.  If the field consisted of an immutable object, like a <code>String</code>, you would not have to worry about making a copy before returning it.  This is because if the object is immutable, you do not have to worry about a caller changing its state because this is impossible to do!  This is why immutable objects are much easier to deal with in multithreaded/concurrent environments.</p>
<p>Note that mutability has nothing to do with the <code>final</code> keyword in Java, contrary to <a href="http://mindprod.com/jgloss/mutable.html">this definition</a>.  Simply marking a field as &#8220;<code>final</code>&#8221; will not magically change a mutable object into an immutable one.  As we saw earlier, whether an object is mutable or not depends entirely on its implementation, the details of which should be expressed in the JavaDoc for that class.  The <code>final</code> keyword only ensures that you cannot reassign that field/variable to completely new reference or object; it <strong>does not</strong> ensure that you can&#8217;t change the state of the object already referenced.</p>
<hr/>Copyright &copy; 2012 <strong><a href="http://unitstep.net">unitstep.net</a></strong>. This Feed is for personal non-commercial use only. If you are not reading this material in your news aggregator, the site you are looking at is guilty of copyright infringement. Please contact <strong><a href="mailto:webmaster@unitstep.net">webmaster@unitstep.net</a></strong> for more information.<br/><span style="float: right;font-size: 7pt"><a href="http://blog.taragana.com/index.php/archive/wordpress-plugins-provided-by-taraganacom/">Plugin</a> by <a href="http://www.taragana.com/">Taragana</a></span>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2008/12/14/handling-mutable-fields-in-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

