<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>unitstep.net</title>
	
	<link>http://unitstep.net</link>
	<description>the home of peter chng</description>
	<lastBuildDate>Mon, 08 Apr 2013 00:16:29 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.4.2</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/unitstep" /><feedburner:info uri="unitstep" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Spring MVC request parameter conversion with minimal configuration</title>
		<link>http://feedproxy.google.com/~r/unitstep/~3/8E-kOEX44dI/</link>
		<comments>http://unitstep.net/blog/2013/04/07/spring-mvc-request-parameter-conversion-with-minimal-configuration/#comments</comments>
		<pubDate>Mon, 08 Apr 2013 00:16:29 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[guides]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[spring]]></category>
		<category><![CDATA[mvc]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=1402</guid>
		<description><![CDATA[I&#8217;ve been playing around with Spring Web MVC a bit and was looking for something similar to Jersey&#8217;s Parameter Classes that would provide conversion to custom types. I liked how with Jersey, you could encapsulate the conversion logic in a single class and have that reused across multiple methods with minimal configuration. Here&#8217;s how I [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been playing around with Spring Web MVC a bit and was looking for something similar to Jersey&#8217;s <a href="http://codahale.com/what-makes-jersey-interesting-parameter-classes/">Parameter Classes</a> that would provide conversion to custom types.  I liked how with Jersey, you could encapsulate the conversion logic in a single class and have that reused across multiple methods with minimal configuration.</p>
<p>Here&#8217;s how I achieved a similar result in Spring Web MVC. (<em>Note: the following examples were done with Spring 3.2.1</em>)</p>
<h2>Built-in?</h2>
<p>Spring does provide some build-in support for conversion to specific types.  For example, you can convert to <a href="http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/format/annotation/package-summary.html">Date and various numeric types</a>.  But, what if you want to convert a request parameter to some other custom type or a type from a third party? (Such as the date-time classes from <a href="http://joda-time.sourceforge.net/">Joda Time</a>)</p>
<h2>Minimize configuration</h2>
<p>I searched for a bit and <a href="http://stackoverflow.com/questions/3989524/what-should-i-use-i-if-need-a-custom-converter-when-using-requestparam">found</a> <a href="http://stackoverflow.com/questions/4347284/conversionservice-in-spring">various</a> <a href="http://jpgmr.wordpress.com/2011/12/05/convert-a-json-collection-from-string-to-list-with-jackson/">solutions</a>, but they all seemed to require too much configuration: In addition to writing a converter class, you&#8217;d have to manually the converter with a ConversionService (either in code or in <a href="http://www.w3.org/XML/" class="ubernym uttInitialism"><acronym class="uttInitialism" title="eXtensible Markup Language">XML</acronym></a> configuration).  I didn&#8217;t like the idea of having to register the converter class; instead, I wanted it to be registered automatically based on some annotations.</p>
<h2>Solution</h2>
<p>Here&#8217;s what I came up with, based on this <a href="http://stackoverflow.com/questions/6519322/spring-mvc-customized-method-parameter-binding/6519525#6519525">answer on Stack Overflow</a>.</p>
<ol>
<li>
<h3>Define a custom annotation for your converters so they can be automatically found</h3>
<pre><code>@Target({ ElementType.TYPE, ElementType.FIELD })
public @interface MyConverter {
}</code></pre>
</li>
<li>
<h3>Create a converter class, annotated with your custom annotation and <code>@Component</code></h3>
<p>This is so it will be available for injection via <code>@Resource</code>. (In this example, we convert to a Joda Time <code><a href="http://joda-time.sourceforge.net/apidocs/org/joda/time/LocalDate.html">LocalDate</a></code>)</p>
<p>The converter class must implement Spring&#8217;s <code><a href="http://static.springsource.org/spring/docs/3.2.x/javadoc-api/org/springframework/core/convert/converter/Converter.html">Converter</a></code> interface.</p>
<pre><code>@Component
@MyConverter 
public class LocalDateConverter implements Converter&lt;String, LocalDate&gt; {

  public static final String DATE_FORMAT = "YYYY-MM-dd";

  @Override
  public LocalDate convert(final String source) {
    return LocalDate.parse(source, DateTimeFormat.forPattern(DATE_FORMAT));
  }
}</code></pre>
</li>
<li>
<h3>Create a bean that extends <code>FormattingConversionServiceFactoryBean</code> that will auto-register all converters</h3>
<p>Here is where all the converters annotated with your custom annotation (and <code>@Resource</code>) are injected.</p>
<pre><code>public class MyConversionServiceFactoryBean extends FormattingConversionServiceFactoryBean {

  @Resource
  @MyConverter
  private List&lt;Converter&lt;?, ?&gt;&gt; myConverters;

  @Override
  protected void installFormatters(final FormatterRegistry registry) {
    // NOTE: This method call is deprecated.
    super.installFormatters(registry);

    for (final Converter&lt;?, ?&gt; converter : this.myConverters) {
      registry.addConverter(converter);
    }
  }

}</code></pre>
</li>
<li>
<h3>Edit Spring configuration so that the auto-registering bean is loaded</h3>
<p>Ok, I lied: There is one piece of configuration you need, but once it&#8217;s made it need never be changed, even when you define additional converters.</p>
<pre><code>&lt;mvc:annotation-driven conversion-service="applicationConversionService" /&gt;
&lt;bean class="com.myapplication.spring.mvc.controller.converters.MyConversionServiceFactoryBean" id="applicationConversionService"/&gt;</code></pre>
</li>
<li>
<h3>Modify controller method to use the proper type</h3>
<p>Note that if conversion fails (via an uncaught exception from the <code>convert()</code> method) then the client will see a 400 Bad Request response.</p>
<pre><code>@RequestMapping(value = "widget/{date}", method = RequestMethod.GET)
@ResponseBody
public String getWidgetDate(@PathVariable("date") final LocalDate date) {
  // We get auto-conversion to a LocalDate type... 
  // Just spits back the date to the client.
  return date.toString();
}</code></pre>
</li>
</ol>
<h2>Summary</h2>
<p>I hope you found this useful.  With just a little bit of work, we have a bean that will auto-register and make available any new converters you define, so as long as you annotate the converter properly.</p>
<hr/>Copyright &copy; 2013 <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><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/unitstep?a=8E-kOEX44dI:TS07aRUxB6o:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/unitstep?i=8E-kOEX44dI:TS07aRUxB6o:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=8E-kOEX44dI:TS07aRUxB6o:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/unitstep?i=8E-kOEX44dI:TS07aRUxB6o:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=8E-kOEX44dI:TS07aRUxB6o:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/unitstep?i=8E-kOEX44dI:TS07aRUxB6o:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=8E-kOEX44dI:TS07aRUxB6o:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/unitstep?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=8E-kOEX44dI:TS07aRUxB6o:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/unitstep?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/unitstep/~4/8E-kOEX44dI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2013/04/07/spring-mvc-request-parameter-conversion-with-minimal-configuration/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://unitstep.net/blog/2013/04/07/spring-mvc-request-parameter-conversion-with-minimal-configuration/</feedburner:origLink></item>
		<item>
		<title>Java: final, finally and finalize</title>
		<link>http://feedproxy.google.com/~r/unitstep/~3/wtKijUT0iX8/</link>
		<comments>http://unitstep.net/blog/2013/02/16/java-final-finally-and-finalize/#comments</comments>
		<pubDate>Sat, 16 Feb 2013 18:46:02 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[guides]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[final]]></category>
		<category><![CDATA[finalize]]></category>
		<category><![CDATA[finally]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=1380</guid>
		<description><![CDATA[One of the most popular Java interview &#8220;screener&#8221; questions is often, &#8220;What is the difference between final, finally and finalize?&#8221; In fact, it occurs so much that one should probably have the answer memorized. But knowing when to use these features is better than just knowing what they mean. The final keyword &#8211; classes and [...]]]></description>
			<content:encoded><![CDATA[<p>One of the most popular Java interview &#8220;screener&#8221; questions is often, <em>&#8220;What is the difference between <strong>final</strong>, <strong>finally</strong> and <strong>finalize</strong>?&#8221;</em> In fact, it occurs so much that one should probably have the answer memorized.  But knowing when to use these features is better than just knowing what they mean.</p>
<h2>The <code>final</code> keyword &#8211; classes and methods</h2>
<p>When used on a class, <code>final</code> prevents the class from being extended.  Similarly, when <code>final</code> is used on a method, that method cannot be overridden in any subclass.  </p>
<p>This is mainly done for reasons of security and consistency: If you have a class whose methods you count on to provide predictable results, you may want to prevent that class from being extended so that someone cannot substitute a subclass that behaves differently to a consumer that expects your original class.  The same may go for certain methods on a class.</p>
<p>But generally, you should not be marking classes/methods as <code>final</code> unless you have a compelling argument for it.  The reason is that using <code>final</code> may unnecessarily constrain the design and hamper future developers who may have a legitimate reason for wanting to extend your class.  Though I prefer composition over inheritance, it&#8217;s not a choice I would want to force on everyone else, nor do I believe it&#8217;s always the right choice.</p>
<p>In particular, you should not be marking classes/methods as <code>final</code> <a href="http://www.ibm.com/developerworks/java/library/j-jtp1029/index.html">just for some perceived performance<a/> benefit. In many cases you won&#8217;t gain a thing performance wise, but will be unnecessarily be constraining your design.</p>
<p>One reason you <em>shouldn&#8217;t</em> refrain from marking a method as <code>final</code> is for mockability; mocking frameworks like <a href="http://code.google.com/p/jmockit/">JMockit</a> allow you to easily mock out <em>final</em> methods, so don&#8217;t let that affect your design decisions.</p>
<h2>The <code>final</code> keyword &#8211; variables</h2>
<p>When used on variables, <code>final</code> essentially means that the variable can only be assigned once.  For class/static members, this is when the class is loaded; for instance members, this is when an instance of the class is created; for local variables, it is usually when the variable is declared.  Method parameters can also be declared as <code>final</code>.</p>
<p>As opposed to the use of <code>final</code> on classes/methods, I usually like using <code>final</code> for most variables, as it can decrease the complexity of code by decreasing the chances for state changes. Once you know that a local variable is <code>final</code>, if it&#8217;s primitive, you can be sure its value won&#8217;t change; if it&#8217;s an object, you can be sure you&#8217;ll always be dealing with the same object.</p>
<p>Furthermore, the use of <code>final</code> on member variables ensures that you know they&#8217;ll be assigned once and only once: At object creation. </p>
<p>Some people may think that the use of final variables is superfluous, but I think it&#8217;s a good defensive programming technique. <a href="http://jaxenter.com/community-post-the-final-keyword-in-java-46036.html">This article</a> sums up my viewpoints nicely.</p>
<h2>finally</h2>
<p>As opposed to the <code>final</code> keyword, which is completely optional and not strictly necessary to use, you should almost always be using the <code>finally</code> keyword in Java when dealing with closeable resources. (This is true before Java 7, as Java 7 introduces some nice syntactic sugar that can remove the need to use <code>finally</code>)</p>
<p>Here is a contrived example:</p>
<pre><code>InputStream inputStream = null;
try {
  inputStream = new FileInputStream(new File("TEST.XML"));
  final int read = inputStream.read();
  // Do other stuff with the stream...
} finally {
  if (null != inputStream) {
    inputStream.close();
  }
}</code></pre>
<p>In this example, we initialize the <code>inputStream</code> within a <code>try</code> block.  If anything goes wrong with reading from the stream, an exception will be thrown (which we don&#8217;t handle here, for brevity) but before it is allowed to propagate, the code within the <code>finally</code> block will be executed, ensuring that if the stream has been opened, it will be closed.  This will prevent a resource leak from happening.</p>
<p>Here is how that code could also look in Java 7:</p>
<pre><code>try (final InputStream inputStream = new FileInputStream(new File("TEST.XML"))) {
  final int read = inputStream.read();
  // Do other stuff with the stream...
}</code></pre>
<p>As you can see, the amount of &#8220;boilerplate&#8221; is reduced as we don&#8217;t need to have an explicit <code>finally</code> block anymore.  This is known as a<a href="http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html"> &#8220;try-with-resources&#8221; statement</a>, where an object that implements <code>Closeable/AutoCloseable</code> is declared and initialized with the <code>try</code> statement and automatically closed no matter what the outcome of the statements within the <code>try</code> block.  I would suggest using this unless your code needs to be JDK 6 compatible. </p>
<h2>finalize()</h2>
<p>As opposed to <code>final</code>, which you may use and <code>finally</code>, which you will certainly have to use in JDK 6 and below, you will almost never need to implement or override <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#finalize()"><code>Object.finalize()</code></a>.</p>
<p>The <code>finalize()</code> method is called by the garbage collector (GC) determines that there is no longer anyway for the object to accessed; this means the object is eligible for finalization, which means the GC can begin the process of making the object finalizable, finalized and then reclaimed.  Generally any Object <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/ref/package-summary.html">that does not have a Strong reference</a> is eligible. </p>
<p>There is generally no need to override the default <code>finalize()</code> method; if your class opens resources then it should be responsible for properly closing/releasing them by using <code>try-catch-finally</code> as outlined above, or you should make your class implement <code>Closeable</code> so that clients/callers of your class can ensure its proper closure.</p>
<p>You could, in theory, use <code>finalize()</code> as a &#8220;safety net&#8221; of sorts to mitigate the effects of bad clients/callers not calling <code>close()</code> on your class by ensuring that internal resources are closed/released in <code>finalize()</code> but you should <strong>never rely on this</strong>.</p>
<p>Additionally, if you are overriding <code>finalize()</code> you must take care to ensure that you don&#8217;t &#8220;leak&#8221; a reference to the object to the &#8220;outside world&#8221;, or else this may prevent the object from being garbage collected, resulting in a potential memory leak! (i.e. don&#8217;t pass a reference to <code>this</code> to any external objects during <code>finalize()</code>)</p>
<p>In general, if you are going to implement/override <code>finalize()</code>, you should have a very specific reason and be very careful in how you do so.</p>
<h2>The final word</h2>
<p>I hope you enjoyed this summary of final, finally and finalize(). Learning these concepts is pretty fundamental to having a good understanding of Java as a whole.</p>
<hr/>Copyright &copy; 2013 <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><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/unitstep?a=wtKijUT0iX8:ClQdGh9gFbk:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/unitstep?i=wtKijUT0iX8:ClQdGh9gFbk:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=wtKijUT0iX8:ClQdGh9gFbk:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/unitstep?i=wtKijUT0iX8:ClQdGh9gFbk:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=wtKijUT0iX8:ClQdGh9gFbk:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/unitstep?i=wtKijUT0iX8:ClQdGh9gFbk:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=wtKijUT0iX8:ClQdGh9gFbk:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/unitstep?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=wtKijUT0iX8:ClQdGh9gFbk:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/unitstep?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/unitstep/~4/wtKijUT0iX8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2013/02/16/java-final-finally-and-finalize/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://unitstep.net/blog/2013/02/16/java-final-finally-and-finalize/</feedburner:origLink></item>
		<item>
		<title>JAX-RS/Jersey needs an @Required annotation for parameters</title>
		<link>http://feedproxy.google.com/~r/unitstep/~3/E11p0mHBS84/</link>
		<comments>http://unitstep.net/blog/2012/05/27/jax-rsjersey-needs-an-required-annotation-for-parameters/#comments</comments>
		<pubDate>Sun, 27 May 2012 20:51:58 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[development]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jax-rs]]></category>
		<category><![CDATA[jersey]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[jersey jsr-311 java jax-rs]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=1372</guid>
		<description><![CDATA[I&#8217;ve been using Jersey as a JAX-RS implementation for a little while now, and one thing that it could benefit from is the addition of an @Required annotation for resource method parameters. Right now, when parameters are not provided by the client/request, they are simply set to null, creating the need for duplicated null-checking in [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been using Jersey as a JAX-RS implementation for a little while now, and one thing that it could benefit from is the addition of an <code>@Required</code> annotation for resource method parameters.  Right now, when parameters are not provided by the client/request, they are simply set to <code>null</code>, creating the need for duplicated null-checking in resource methods. An <code>@Required</code> annotation would solve this issue and reduce code duplication.</p>
<p>This isn&#8217;t so much of an issue for <code>@PathParam</code> parameters, (since you won&#8217;t even get to the proper resource method without a matching URI) but it does affect <code>@HeaderParam</code> and <code>@QueryParam</code> (among others) since they aren&#8217;t needed for Jersey to determine which resource method to invoke. By that definition, they are implicitly optional. There should be a way to make them required.</p>
<p>The behaviour of such a required annotation might be as follows:</p>
<ul>
<li>If the request does not have the parameter, then by default a <code>Response</code> with <code>Status.BAD_REQUEST</code> (<acronym class="uttInitialism" title="HyperText Transfer Protocol">HTTP</acronym> 400) would be returned to the client.</li>
<li>Some way of customizing the <acronym class="uttInitialism" title="HyperText Transfer Protocol">HTTP</acronym> response code and message should also be provided.</li>
</ul>
<p>Right now, there&#8217;s not really an elegant way to make something like a <code>@HeaderParam</code> required. Here are some solutions I&#8217;ve tried.</p>
<h3>Attempt #1: Parameter classes</h3>
<p><a href="http://codahale.com/what-makes-jersey-interesting-parameter-classes/">Parameter classes</a> can be useful for transforming the single input of a parameter into a single output, and also for verifying that the input parameter value is valid.  This can be useful for ensuring that an input parameter can be converted into a specific object, or that it matches a specific format. </p>
<p>As an example, consider the <code>CsvListParam</code> class. This class takes a comma-separated list as a parameter, and returns a <code>List&lt;String&gt;</code> comprising each entry in the list. It does an additional check to ensure that the input is not blank, according to <a href="http://commons.apache.org/lang/api-3.0/org/apache/commons/lang3/StringUtils.html#isBlank(java.lang.CharSequence)">StringUtils.isBlank()</a>.  If it is blank, a 400 Bad Request response is returned to the client via the <code>WebApplicationException</code> thrown. </p>
<p>Note: The following examples use the <code>AbstractParam</code> class from <a href="http://codahale.com/what-makes-jersey-interesting-parameter-classes/">Coda Hale&#8217;s article</a>.</p>
<pre><code>public class CsvListParam extends AbstractParam&lt;List&lt;String&gt;&gt; {

  public CsvListParam(String param) throws WebApplicationException {
    super(param);
  }

  @Override
  protected List&lt;String&gt; parse(final String suppliedStringValue) throws Throwable {
    if (StringUtils.isBlank(suppliedStringValue)) {
      throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).build());
    }
    return Arrays.asList(StringUtils.split(suppliedStringValue, ","));
  }
}

@GET
@Path("test")
public Response test(@HeaderParam("X-TEST") final CsvListParam param) {
  final String output;
  if (null != param) {
    output = param.getValue().toString();
  } else {
    output = "param was null";
  }
  return Response.ok(output).build();
}</code></pre>
<p>However, if the parameter is not present at all &#8211; for example, if this was obtained via the <code>@HeaderParam</code> annotation and the header was not present &#8211; then the code in the parameter class <strong>will not even be invoked by Jersey</strong>. Instead, the value will simply be <code>null</code>.  If we require this parameter, it results in nasty if-else null-checking code in each of our resource methods that requires the parameter.</p>
<p>We need something that gets rid of the necessary null-checking in each resource method.</p>
<h3>Attempt #2: Injection Providers</h3>
<p>Coda Hale provides another brilliant example how to use <a href="http://codahale.com/what-makes-jersey-interesting-injection-providers/">Injection Providers</a> in Jersey. Basically, with Injection Providers, you can do everything that you could do with Parameter classes, and more.</p>
<p>While Parameter classes are useful only for single-input to single-output mapping, Injection Providers can map multiple inputs to single or multiple outputs. This could allow you to take multiple values in the <acronym class="uttInitialism" title="HyperText Transfer Protocol">HTTP</acronym> request and use them populate a single Bean, or use them to form some more complex single value.  It also allows you to do validation, as throwing a <code>WebApplicationException</code> from an Injection Provider will cause the contained <code>Response</code> or status to be properly returned to the client.</p>
<p>So, we can achieve a similar effect using an Injection Provider. A first attempt at resolving the issue yields the CsvListProvider class:</p>
<pre><code>@Provider
public class CsvListProvider extends AbstractInjectableProvider&lt;CsvListParam&gt; {
  public CsvListProvider() {
    super(CsvListParam.class);
  }

  @Override
  public CsvListParam getValue(final HttpContext httpContext) {
    final String suppliedStringValue = httpContext.getRequest().getHeaderValue("X-TEST");
    return new CsvListParam(suppliedStringValue);
  }
}

@GET
@Path("test")
public Response test(@Context final CsvListParam param) {
  final String output = param.getValue().toString();
  return Response.ok(output).build();
}</code></pre>
<p>However, while this works as expected, it has the unfortunate side effect that the source of the parameter (an <acronym class="uttInitialism" title="HyperText Transfer Protocol">HTTP</acronym> header of &#8220;X-TEST&#8221;) has to be specified in the Provider class rather than on the annotation. This isn&#8217;t ideal since we have to create a new Injection Provider class for each <acronym class="uttInitialism" title="HyperText Transfer Protocol">HTTP</acronym> header we want to make required.</p>
<h3>Further attempts</h3>
<p>I have been trying to figure out a solution to this. One possible way might be to change the AbstractInjectableProvider to the following declaration:</p>
<pre><code>public abstract class AbstractInjectableProvider&lt;E, A extends Annotation&gt; extends AbstractHttpContextInjectable&lt;E&gt; implements InjectableProvider&lt;A, Type&gt;</code></pre>
<p>We could then define a custom annotation type to take the place of <code>A</code> instead of always using <code>@Context</code>.  However, this doesn&#8217;t work, as we have no way of then obtaining any of the annotation&#8217;s values in the concrete Provider class.  A solution like this would require changes in the core of Jersey to make it work, thus reducing the solution essentially the same as having an <code>@Required</code> annotation as proposed above.</p>
<h3>Conclusion</h3>
<p>It seems like we need a proper solution to this via a change in Jersey. Evidently, others have come to the <a href="http://jersey.576304.n2.nabble.com/Required-parameters-on-a-Resource-td3446928.html">same conclusion</a>, as there are at least <a href="http://java.net/jira/browse/JERSEY-351">two</a> <a href="http://java.net/jira/browse/JERSEY-399">issues</a> open for Jersey related to this.</p>
<hr/>Copyright &copy; 2013 <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><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/unitstep?a=E11p0mHBS84:E_Ov3R0XZcw:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/unitstep?i=E11p0mHBS84:E_Ov3R0XZcw:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=E11p0mHBS84:E_Ov3R0XZcw:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/unitstep?i=E11p0mHBS84:E_Ov3R0XZcw:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=E11p0mHBS84:E_Ov3R0XZcw:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/unitstep?i=E11p0mHBS84:E_Ov3R0XZcw:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=E11p0mHBS84:E_Ov3R0XZcw:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/unitstep?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=E11p0mHBS84:E_Ov3R0XZcw:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/unitstep?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/unitstep/~4/E11p0mHBS84" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2012/05/27/jax-rsjersey-needs-an-required-annotation-for-parameters/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://unitstep.net/blog/2012/05/27/jax-rsjersey-needs-an-required-annotation-for-parameters/</feedburner:origLink></item>
		<item>
		<title>Java’s Pattern class and regular expressions</title>
		<link>http://feedproxy.google.com/~r/unitstep/~3/ta9aursG3oM/</link>
		<comments>http://unitstep.net/blog/2012/03/18/javas-pattern-class-and-regular-expressions/#comments</comments>
		<pubDate>Mon, 19 Mar 2012 01:47:20 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[regex]]></category>
		<category><![CDATA[tutorials]]></category>
		<category><![CDATA[java regex tutorial]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=1366</guid>
		<description><![CDATA[One of the easiest things to get tripped up on is the syntax for creating regular expressions (regex) in Java using the Pattern class. The tl;dr version of how to do things is that you must use double-backslashes in the regular expression Strings you use to create a Pattern object; so something like \b would [...]]]></description>
			<content:encoded><![CDATA[<p>One of the easiest things to get tripped up on is the syntax for creating regular expressions (regex) in Java using the <a href="http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html">Pattern</a> class. The <em>tl;dr</em> version of how to do things is that <strong>you must use double-backslashes in the regular expression Strings you use to create a Pattern object</strong>; so something like <code>\b</code> would have to be written as <code>"\\b"</code>.  Read on for a more thorough explanation.</p>
<h2>Double trouble</h2>
<p>The key point to understanding the tricky syntax is to realize that when you&#8217;re creating a String literal in Java, backslashes are used to form escape sequences as well. Most people are familiar with this concept, when, for example, constructing a String that spans multiple lines:</p>
<pre><code>final String multiline = "A String...\nOn two lines";</code></pre>
<p>When calling <code>Pattern.compile</code>, you pass in a String literal that is the regular expression. However, regular expressions also use the backslash character to begin escape sequences. So, to ensure that the regular expression engine in Pattern gets the correct syntax, you must replace every backslash in your regular expression with two backslashes. This is to prevent Java from interpreting the single backslash as just a String escape sequence.</p>
<p>Or, put another way, if you wanted a String with the contents <code>"\n"</code>, that is a String with a backslash followed by the letter &#8216;n&#8217;, you&#8217;d have to define it as:</p>
<pre><code>final String newLineEscapeSequence = "\\n";</code></pre>
<p>This is the gist of it; we need to pass in the preserved backslashes into the Pattern regular expression engine, so you have to create a literal backslash by using a double-backslash in your String literal. This information is in the <a href="http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html">Pattern Javadoc</a>, but it&#8217;s sort of buried beneath loads of regular expression syntax. </p>
<p>Keep this in mind when constructing your regular expressions outside of Java in a tool like <a href="http://gskinner.com/RegExr/">RegExr</a>.  These principles also apply when using other classes/methods that use <code>Pattern</code>, such as <code><a href="http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29">String.split()</a></code> or <code><a href="http://docs.oracle.com/javase/6/docs/api/java/util/Scanner.html#useDelimiter%28java.util.regex.Pattern%29">Scanner.useDelimiter()</a></code></p>
<h2>An example</h2>
<p>Here&#8217;s a simple example where we try to find the word &#8220;The&#8221; at the beginning of a String, delimited by a word boundary matcher.</p>
<pre><code>public class PatternExample {
  private static final Logger LOGGER =
      Logger.getLogger(PatternExample.class);
  private static final String TEST_STRING =
      "The quick brown fox jumps over the lazy dog";

  public static void main(final String[] args) {
    System.out.println(TEST_STRING);

    final Pattern wordBoundaryWrong = Pattern.compile("^The\b.*");
    Matcher matcher = wordBoundaryWrong.matcher(TEST_STRING);
    LOGGER.debug(matcher.matches()); // false.

    final Pattern wordBoundaryCorrect = Pattern.compile("^The\\b.*");
    matcher = wordBoundaryCorrect.matcher(TEST_STRING);
    LOGGER.debug(matcher.matches()); // true.
  }
}</code></pre>
<p>The key point here is that the word boundary matcher (<code>\b</code>) must be passed in as a String literal of <code>"\\b"</code> so that the backslash is properly interpreted. In the incorrect Pattern, <code>"\b"</code> maps to a <a href="http://docstore.mik.ua/orelly/java-ent/jenut/ch10_05.htm">backspace character literal</a>.</p>
<p>I think the reason this concept is somewhat tricky is that you have to deal with two levels of escaping &#8211; the Java String literal syntax and the Regular Expression syntax.</p>
<hr/>Copyright &copy; 2013 <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><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/unitstep?a=ta9aursG3oM:wkkSNgSf91E:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/unitstep?i=ta9aursG3oM:wkkSNgSf91E:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=ta9aursG3oM:wkkSNgSf91E:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/unitstep?i=ta9aursG3oM:wkkSNgSf91E:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=ta9aursG3oM:wkkSNgSf91E:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/unitstep?i=ta9aursG3oM:wkkSNgSf91E:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=ta9aursG3oM:wkkSNgSf91E:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/unitstep?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=ta9aursG3oM:wkkSNgSf91E:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/unitstep?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/unitstep/~4/ta9aursG3oM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2012/03/18/javas-pattern-class-and-regular-expressions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://unitstep.net/blog/2012/03/18/javas-pattern-class-and-regular-expressions/</feedburner:origLink></item>
		<item>
		<title>The Game of Life and emergence</title>
		<link>http://feedproxy.google.com/~r/unitstep/~3/zu0mcE6FRBc/</link>
		<comments>http://unitstep.net/blog/2012/02/12/the-game-of-life-and-emergence/#comments</comments>
		<pubDate>Mon, 13 Feb 2012 01:37:54 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[asides]]></category>
		<category><![CDATA[Life]]></category>
		<category><![CDATA[emergence]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=1326</guid>
		<description><![CDATA[I have had a side interest in emergent behaviour ever since reading about various forms in nature, so when a co-worker sent me a link to Conway&#8217;s Game of Life, I was immediately intrigued. Long story short, I just had to implement it (albeit a simple version) in JavaScript. The result is available on my [...]]]></description>
			<content:encoded><![CDATA[<p>I have had a side interest in emergent behaviour ever since reading about various forms in nature, so when a co-worker sent me a link to <a href="http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life">Conway&#8217;s Game of Life</a>, I was immediately intrigued.</p>
<p>Long story short, I just had to implement it (albeit a simple version) in JavaScript. The <a href="http://unitstep.net/projects/game-of-life/">result is available</a> on my website and I suggest you give it a try; a good pattern to start out with is the <a href="http://en.wikipedia.org/wiki/File:Game_of_life_fpento.svg">F-pentomino</a>.</p>
<p>The reason I find emergence so interesting is that it provides a possible framework or explanation for the complexity and order seen in our universe, based on a fairly simple or rudimentary set of rules.</p>
<h2>One to rule them all</h2>
<p>The interactions seen in <em>Conway&#8217;s Game of Life</em> can be fairly complex and are not straightforward to predict. However, they all result from a simple set of rules:</p>
<ul>
<li>Each square is labeled as a cell, and has eight neighbours.</li>
<li>A cell can either be &#8220;dead&#8221; or &#8220;alive&#8221;.</li>
<li>A dead cell turns alive on the next turn if it has exactly three alive neighbours.</li>
<li>A live cell continues to live on the next turn if it has 2 or 3 alive neighbours.</li>
</ul>
<p>Thus, during each iteration, the state of a cell (alive or dead) is determined from the state of its neighbours on the previous turn.</p>
<h2>Complexity from simplicity</h2>
<p>Despite this limited ruleset, complex behaviour can be seen in the interaction between cells. In fact, quite a lot of study has been put into understanding the interactions and categorizing the various &#8220;structures&#8221; that have emerged in game. </p>
<p>Simulating the game on a large scale can take a lot of CPU power, so some interesting dynamic programming techniques have been utilized to increase the iteration speed. One of them is <a href="http://en.wikipedia.org/wiki/Hashlife">Hashlife</a>, which exploits the repeatability and determinism in the game.</p>
<p>For example, if a pattern shows up an in an early stage of the simulation, it&#8217;s &#8220;evolution&#8221; can be tracked and stored so that if the same pattern ever shows up again, it&#8217;s long(er) term fate will already be known, since it was already computed earlier. This prevents unnecessary iterations in the simulation. This sort of technique is called <em>memoization</em>.</p>
<h2>In Real Life</h2>
<p>Obviously, our universe is probably more complex than the <em>Game of Life</em>. (It would likely have to be, since the simulation exists within our universe) But it&#8217;s also likely that all the complex interactions and structures observed in our universe boil down to some set of rudimentary rules.  The point of science, in many respects, is connecting the dots that allow us to understand how these higher-level properties emerged from lower-level interactions. I&#8217;m not saying that it will provide all the answers or explain things like self-awareness, but to me, that sort of emergence is the real beauty of our universe. </p>
<hr/>Copyright &copy; 2013 <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><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/unitstep?a=zu0mcE6FRBc:Y-ysxpcLFSI:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/unitstep?i=zu0mcE6FRBc:Y-ysxpcLFSI:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=zu0mcE6FRBc:Y-ysxpcLFSI:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/unitstep?i=zu0mcE6FRBc:Y-ysxpcLFSI:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=zu0mcE6FRBc:Y-ysxpcLFSI:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/unitstep?i=zu0mcE6FRBc:Y-ysxpcLFSI:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=zu0mcE6FRBc:Y-ysxpcLFSI:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/unitstep?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=zu0mcE6FRBc:Y-ysxpcLFSI:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/unitstep?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/unitstep/~4/zu0mcE6FRBc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2012/02/12/the-game-of-life-and-emergence/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://unitstep.net/blog/2012/02/12/the-game-of-life-and-emergence/</feedburner:origLink></item>
		<item>
		<title>Shuffle sort and other fallacies of randomization</title>
		<link>http://feedproxy.google.com/~r/unitstep/~3/teJdn-7Xcgg/</link>
		<comments>http://unitstep.net/blog/2012/02/05/shuffle-sort-and-other-fallacies-of-randomization/#comments</comments>
		<pubDate>Mon, 06 Feb 2012 01:23:17 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[algorithms]]></category>
		<category><![CDATA[randomization]]></category>
		<category><![CDATA[randomization microsoft browser eu probability]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=1098</guid>
		<description><![CDATA[Quick, how do you write code that shuffles a collection of objects? In the real world, it&#8217;s fairly easy to see how a deck of cards is shuffled &#8211; but how would you do that in code? Obviously, you would have to use some sort of random number generator, but beyond that it&#8217;s not straightforward. [...]]]></description>
			<content:encoded><![CDATA[<p>Quick, how do you write code that shuffles a collection of objects? In the real world, it&#8217;s fairly easy to see how a deck of cards is shuffled &#8211; but how would you do that in code? Obviously, you would have to use some sort of random number generator, but beyond that it&#8217;s not straightforward. Furthermore, how do you ensure that the shuffling is <em>fair</em>; that is, all permutations appear with equal probability?</p>
<p>The astute among you will know that one way is by implementing the <a href="http://bost.ocks.org/mike/shuffle/">Fisher-Yates shuffle algorithm</a>. But, let&#8217;s investigate what happens when other, seemingly adequate solutions, are used instead.</p>
<h2>Shuffler&#8217;s dilemma</h2>
<p>One example that highlights the implications of using <em>seemingly</em> random and unbiased &#8220;shuffling&#8221; involves the <a href="http://arstechnica.com/microsoft/news/2010/03/coding-error-leads-to-uneven-eu-browser-ballot-distribution.ars">Windows EU Browser Ballot</a>.</p>
<p>The purpose of the Browser Ballot was so that <a href="http://arstechnica.com/microsoft/news/2010/02/microsofts-eu-browser-ballot-approved-arrives-march-1.ars">Microsoft could comply with an EU directive</a> that ordered them to provide users with a clear choice of which browser to use with Windows. The ballot was supposed to have been carefully designed; the first section contained the five most common browsers (Chrome, Firefox, Internet Explorer, Opera and Safari) with the second section containing seven lesser-used browsers.</p>
<p>Since it is generally considered an advantage to be placed first in a ballot (because users who don&#8217;t care one way or another might just pick the first option), the EU directed Microsoft to randomize the order in which the browsers appeared on the ballot in each of the sections. Thus, when users visited the ballot page, they were supposed to get a random ordering of the top five browsers followed by a random ordered of the lesser seven.</p>
<h2>Looking into the cards</h2>
<p>The team in charge of the ballot design came up with a solution to use a sorting function with a randomized comparator. In this way, they hoped to apply a randomized sort to the list of browsers, producing a random ordering that met the rules of the EU.  While this did produce a random ordering, (and thus technically was in compliance with the EU directive), it did not produce unbiased results, as the ordering of some browsers came up more often than others. This lead to allegations that Microsoft was trying yet again to stifle its competition to unscrupulous practices.</p>
<p>However, this probably wasn&#8217;t the case, and was likely an instance of a seemingly adequate solution being used without proper testing/analysis.</p>
<p>To understand the problem, we first have to understand sorting algorithms, specifically those that use comparisons as their basis. (i.e. <em>comparison sorts</em>) An example of a comparison sort is <em><a href="http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/Sorting/insertionSort.htm">Insertion sort</a></em>. Through each step of the sorting process, the sorted portion of the list increases by one as we take the next element from the unsorted portion and position it properly within the sorted portion. This is done by <em>comparing</em> the element to be inserted with each element in the sorted portion until we find the correct position.</p>
<p>A <em>comparator</em> is simply a function that compares two objects, and tells us which one is greater than the other, or whether they are equal. In Java, the general structure of a <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html">Comparator</a> would be:</p>
<pre><code>new Comparator&lt;T&gt;() {
  @Override
  public int compare(final T o1, final T o2) {
    // If o1 is "less than" o2, return a negative integer.
    // If o1 is "equal to" o2, return 0.
    // If o1 is "greater than" o2, return a positive integer.
  }
};</code></pre>
<p>In this way, the exact semantics of comparisons can be tailored to meet the needs of the application.  In the case of the Browser Ballot, the team implemented something akin to the following: (Though the language was JavaScript, not Java, as the Browser Ballot was a website)</p>
<pre><code>new Comparator&lt;T&gt;() {
  @Override
  public int compare(final T o1, final T o2) {
    return Math.random() &lt; 0.5 ? 1 : -1;
  }
};</code></pre>
<p>In this comparator, the objects being compared are not even considered; instead the either <code>-1</code> or <code>1</code> is returned with equal probability. Using this sort of &#8220;comparison&#8221; with a sorting algorithm might <em>seem</em> to provide random, unbiased results &#8211; but in reality, such &#8220;common sense&#8221; did not make so much sense after further analysis.</p>
<h2>Looking deeper</h2>
<p>To look at the problem a bit more in-depth, I decided to write an example in Java that would test the results of a &#8220;random sort&#8221; on a set of four objects, using the following sorting algorithms: A modified Merge sort (provided by Java&#8217;s <code><a href="http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List,%20java.util.Comparator%29">Collections.sort()</a></code>), Quicksort, Insertion sort and Selection sort. These results would then be compared to using the proper method, a Fisher-Yates shuffle.</p>
<p>Some more details:</p>
<ul>
<li>The list to be shuffled started off with the ordering of <code>[1, 2, 3, 4]</code></li>
<li>I used my own implementation of Quicksort that just selected the pivot from the middle of the list.</li>
<li>Bubble sort was not considered, since with a randomized comparator, the algorithm may never terminate!</li>
</ul>
<p>Here are the results:</p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2012/02/shuffle-permutation-results.png"><img src="http://unitstep.net/wordpress/wp-content/uploads/2012/02/shuffle-permutation-results-300x298.png" alt="" title="shuffle-permutation-results" width="300" height="298" class="alignnone size-medium wp-image-1361" /></a></p>
<p>As you can see, the Fisher-Yates shuffling algorithm produces the expected near-uniform distribution, represented by the almost-straight line. The &#8220;randomized&#8221; sorting algorithms most definitely did not produce a uniform distribution.  Interestingly, the modified merge sort used by <code>Collections.sort()</code> produced the same distribution as Insertion sort; This may mean that this specific implementation of merge sort uses an insertion sort when the collection size is sufficiently low.</p>
<p>Of the sorting algorithms tested, Quicksort had the least difference between the &#8220;peaks&#8221; and &#8220;troughs&#8221;, though the bias was still very evident. I&#8217;ve heard that Quicksort <em>may</em> produce a near-uniform distribution when used with a randomized comparator, but I&#8217;m guessing that would depend greatly on the choice of pivot.</p>
<h2>Conclusion</h2>
<p>Randomization is never an easy thing; one must fully consider the effects of a specific algorithm before jumping to conclusions as &#8220;common sense&#8221; doesn&#8217;t really make much sense in this area. Come to think of it, &#8220;common sense&#8221; is rarely sensible. </p>
<p>Careful analysis is always needed whenever dealing with distribution of random variables. In general, for a random variable <em>A</em> that has a certain distribution, <em>f(A)</em> is not guaranteed to have the same distribution. This is the point that was missed when designing the ballot. </p>
<p>Analysis of the Fisher-Yates algorithm is fairly easy: The reason why it works is that at each step of selecting an element from the collection, each remaining element has an equally-likely probability of being selected. Analysis of each of the randomized sorting algorithms to understand why each distribution was produced is more difficult, and is left as an exercise to the reader. <img src='http://unitstep.net/wordpress/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p>It&#8217;s also worthwhile to note that the correct shuffling algorithm (Fisher-Yates) runs in <em>O(n)</em> time, while all of the randomized sorting algorithms have a longer asymptotic run time.</p>
<hr/>Copyright &copy; 2013 <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><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/unitstep?a=teJdn-7Xcgg:rVcu-BzMV9o:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/unitstep?i=teJdn-7Xcgg:rVcu-BzMV9o:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=teJdn-7Xcgg:rVcu-BzMV9o:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/unitstep?i=teJdn-7Xcgg:rVcu-BzMV9o:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=teJdn-7Xcgg:rVcu-BzMV9o:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/unitstep?i=teJdn-7Xcgg:rVcu-BzMV9o:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=teJdn-7Xcgg:rVcu-BzMV9o:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/unitstep?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=teJdn-7Xcgg:rVcu-BzMV9o:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/unitstep?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/unitstep/~4/teJdn-7Xcgg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2012/02/05/shuffle-sort-and-other-fallacies-of-randomization/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://unitstep.net/blog/2012/02/05/shuffle-sort-and-other-fallacies-of-randomization/</feedburner:origLink></item>
		<item>
		<title>The Flyweight Pattern: (Mis|ab)used at times.</title>
		<link>http://feedproxy.google.com/~r/unitstep/~3/9-cyD9wUWfk/</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; 2013 <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><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/unitstep?a=9-cyD9wUWfk:w_DbXRwYXzc:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/unitstep?i=9-cyD9wUWfk:w_DbXRwYXzc:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=9-cyD9wUWfk:w_DbXRwYXzc:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/unitstep?i=9-cyD9wUWfk:w_DbXRwYXzc:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=9-cyD9wUWfk:w_DbXRwYXzc:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/unitstep?i=9-cyD9wUWfk:w_DbXRwYXzc:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=9-cyD9wUWfk:w_DbXRwYXzc:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/unitstep?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=9-cyD9wUWfk:w_DbXRwYXzc:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/unitstep?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/unitstep/~4/9-cyD9wUWfk" height="1" width="1"/>]]></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>
		<feedburner:origLink>http://unitstep.net/blog/2012/01/08/the-flyweight-pattern-misabused-at-times/</feedburner:origLink></item>
		<item>
		<title>Goodbye, old friend…</title>
		<link>http://feedproxy.google.com/~r/unitstep/~3/5uLoqdDPQZw/</link>
		<comments>http://unitstep.net/blog/2011/12/15/goodbye-old-friend/#comments</comments>
		<pubDate>Thu, 15 Dec 2011 23:25:09 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[asides]]></category>
		<category><![CDATA[Life]]></category>
		<category><![CDATA[glasses]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=1304</guid>
		<description><![CDATA[I&#8217;ve had the same pair of prescription glasses since about 2004, having changed the lens more than once. I just got so used to them that whenever the opportunity arose to replace them, I couldn&#8217;t find a pair that felt or looked right. So, I just continued with the same old dependable pair. They&#8217;ve fallen [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve had the same pair of prescription glasses since about 2004, having changed the lens more than once. I just got so used to them that whenever the opportunity arose to replace them, I couldn&#8217;t find a pair that felt or looked right. So, I just continued with the same old dependable pair.</p>
<p>They&#8217;ve fallen off of my face more than once, have tumbled many times to the hardwood floor from my nightstand while I fumbled for them in the dark, been lost in my bed covers and rolled onto during numerous occasions, and of course I&#8217;ve fallen asleep with them on more times than I can remember. Despite all of this, they not only held together, but retained much of the original lustre and remain in excellent condition.</p>
<p>Only one of the earpieces is starting to look worn, the nose pads are looking a little old and one of the lens screws had to be replaced when it fell out and got lost, but other than that, they&#8217;re as good as new. This was the first &#8220;thin&#8221; pair of glasses I had ever worn and I initially had some reservations about durability, so I&#8217;m more than pleased with how well they&#8217;ve held up. (I think the frames are made up of some titanium, but I can&#8217;t remember)</p>
<p>But this past weekend, I decided it was time to finally replace them. </p>
<p class="image">
<a href="http://unitstep.net/wordpress/wp-content/uploads/2011/12/eyeglasses.jpg"><img src="http://unitstep.net/wordpress/wp-content/uploads/2011/12/eyeglasses-300x225.jpg" alt="" title="Old eyeglasses" width="300" height="225" class="alignnone size-medium wp-image-1318" /></a>
</p>
<p>We&#8217;ve had a good run, old friend, but I&#8217;m afraid it&#8217;s time to part ways.</p>
<p>I went down to the local Pearle Vision since it was close and seemed to have a decent selection of frames. In fact, I found there was just too many options. Many of them were easily ruled out, but I still ended up spending over an hour trying on frames with fingerprints and smudges all over the lenses in an effort to find the right pair. Or, rather, the right <em>pairs</em>, since they had this screwed up pricing that basically forced you to buy two pairs at once since you hardly saved anything by buying a single pair.</p>
<p>The problem with selecting glasses (besides my indecisiveness, aggravated by the multitude of options) is that it&#8217;s hard to know how well they&#8217;ll do or look over the long run. Durability is important to me, and certainly some frames &#8220;felt&#8221; more durable than others, but that&#8217;s not really a sound way of assessing things. I guess I&#8217;m just expecting these new frames to last as long as the previous ones did, because I find it hard to change &#8220;styles&#8221;.</p>
<p>The other problem is that it&#8217;s hard to tell what you look like in them if you don&#8217;t wear contacts &#8211; thankfully this isn&#8217;t a problem for me; I&#8217;d be nearly blind without corrective vision.</p>
<p>Eventually, if you try on enough frames and stay in the store for long enough, almost all glasses start to look acceptable. This is because style and attractiveness are both subjective and tend to be swayed one way or another by overexposure. It&#8217;s almost as if your subconscious is overriding your critical thinking in an effort to get you out of the store and on your way. </p>
<p>You need to know when this effect is taking a hold of you, so I suggest the following: Within five minutes of entering the store, identify and try on a pair of frames that look utterly ridiculous on you. Then, put these back; don&#8217;t worry, you definitely won&#8217;t be getting these. After you&#8217;ve been in the store for an hour or so, and you&#8217;re noticing that most frames you&#8217;re trying on are looking good, go back and try on the hideous pair.</p>
<p>If the hideous pair now look attractive or even slightly better than before, your judgment has already been compromised. Either leave and come back another day or take your chances with a pair that you found attractive <em>early on</em> during your search. This is what I did.</p>
<p>I should be getting the new frames within a few days. Hopefully I wasn&#8217;t judgment-impaired when I made my choice.</p>
<hr/>Copyright &copy; 2013 <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><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/unitstep?a=5uLoqdDPQZw:6yeDnBQ32Vo:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/unitstep?i=5uLoqdDPQZw:6yeDnBQ32Vo:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=5uLoqdDPQZw:6yeDnBQ32Vo:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/unitstep?i=5uLoqdDPQZw:6yeDnBQ32Vo:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=5uLoqdDPQZw:6yeDnBQ32Vo:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/unitstep?i=5uLoqdDPQZw:6yeDnBQ32Vo:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=5uLoqdDPQZw:6yeDnBQ32Vo:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/unitstep?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=5uLoqdDPQZw:6yeDnBQ32Vo:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/unitstep?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/unitstep/~4/5uLoqdDPQZw" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2011/12/15/goodbye-old-friend/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://unitstep.net/blog/2011/12/15/goodbye-old-friend/</feedburner:origLink></item>
		<item>
		<title>Boston reflection and updates</title>
		<link>http://feedproxy.google.com/~r/unitstep/~3/AyFyEMp795o/</link>
		<comments>http://unitstep.net/blog/2011/06/19/boston-reflection-and-updates/#comments</comments>
		<pubDate>Sun, 19 Jun 2011 18:05:00 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[asides]]></category>
		<category><![CDATA[Life]]></category>
		<category><![CDATA[marathon]]></category>
		<category><![CDATA[running]]></category>
		<category><![CDATA[boston marathon]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=1280</guid>
		<description><![CDATA[It&#8217;s been two months since the 2011 Boston Marathon, which was my first attempt at this historic race. As some of you may know, it had been one of the focal points of my life for the past several months, ever since I qualified by 13 seconds back in September of 2010. I took a [...]]]></description>
			<content:encoded><![CDATA[<p>It&#8217;s been two months since the <a href="http://www.baa.org/races/boston-marathon.aspx">2011 Boston Marathon</a>, which was my first attempt at this historic race. As some of you may know, it had been one of the focal points of my life for the past several months, <a href="/blog/2010/10/09/qualified-for-the-boston-marathon/">ever since I qualified by 13 seconds</a> back in September of 2010.</p>
<p>I took a <a href="/blog/2011/01/16/what-ive-been-up-to/">new approach to training</a> and really dedicated myself to it. There were many mid-week 4 AM mornings, followed by 1.5-2 hour runs in the dark, snow/rain and wind. I arrived at the starting line being as prepared for any race as I&#8217;d ever been.</p>
<p>However, I failed to meet my goal time of a sub-3:03 marathon, finishing in only 3:07:20. I made several mistakes early on and fell behind the pace within the first 10 km. However, I was most disappointed in myself for not pushing harder. I felt that I had mentally &#8220;checked out&#8221; after the first half, and consciously or not, believed that meeting my goal was now impossible due to the early mistakes. Because of that, I felt that I didn&#8217;t try as hard as I could and that I did not give 100% for fear of failure. It was almost as if I had sabotaged myself into thinking, &#8220;If I don&#8217;t give 100% and miss my goal, well at least then I will have an excuse.&#8221;</p>
<p>I fell into a pretty big slump after Boston and didn&#8217;t/couldn&#8217;t run for almost a week after. Even when I did start again, things just weren&#8217;t the same &#8211; my confidence had been shattered. I knew I had to break out of this slump, so I signed up for the <a href="http://www.mississaugamarathon.com/default.shtml">Mississauga Half Marathon</a>, which was about a month after Boston, to give me something to shoot for.</p>
<p>Why the half? Simply put, I didn&#8217;t think I&#8217;d be ready for another full so soon &#8211; not just physically, but mentally as well. If I were to run the full, I would have wanted to aim for a sub-3:05, in order to get in on the <a href="http://www.baa.org/races/boston-marathon/participant-information/register.aspx">first week of registration for 2012</a>. However, I didn&#8217;t feel that I would have the mental toughness required to meet that time and couldn&#8217;t deal with the heartbreak of another missed goal. So, I decided on the half, a distance I felt comfortable with.</p>
<p>Things turned out great &#8211; though the conditions were looking windy/rainy, things actually were not that bad, and I was able to pull of a huge PR, finishing in a time of 1:24:02 in the Mississauga Half Marathon, well ahead of any goal I&#8217;d had. This was good enough for 4th in my age group. Suffice to say, this was a huge confidence booster, something I sorely needed. </p>
<h2>Edmonton Marathon</h2>
<p>Coming off my performance at the Mississauga Half, I felt elated and immediately signed up for the Edmonton Marathon, which takes place on August 21st of this year. This would give me two weeks of downtime before I would have to start a 12-week training schedule for it. 12 weeks might seem a little short, but I actually think it&#8217;s pretty close to optimal considering my present situation. I felt that the 18-week program I used for Boston was perhaps a little long, and something between 14-16 weeks would have been better. </p>
<p>Given that I&#8217;m coming off a good base established by my Boston training (though not reflected in my performance there, but instead at the Mississauga Half), I feel that 12 weeks is more than enough to be ready for Edmonton, provided I stick to the plan, rest/recovery well and not over do things.</p>
<p>Edmonton will be my last chance to qualify for Boston 2012, since registration starts in early September. Technically, I&#8217;m already &#8220;qualified&#8221; for Boston 2012, but I don&#8217;t believe my time will be fast enough to actually allow my entry accepted. Complicated story aside, most runners I&#8217;ve talked to have thought that you&#8217;ll need to have at least BQ-5 (that is, your Boston Qualification time minus 5 minutes) in order to have a chance to get in, so I&#8217;ll be aiming for a sub-3:05 finish.</p>
<p>Running a marathon is no easy task. You train for months and basically have once chance to prove yourself. I don&#8217;t deal well with pressure, and I choked at Boston this year. I&#8217;m trying to avoid that this time in Edmonton.</p>
<p>Edmonton has the advantage of being a flat course, and the climate is not known for its hot summers. When I ran it back in 2009, the starting line temperature was only around 8C with a finishing temperature of 16C. This is pretty close to ideal. However, there are only so many things one can control.</p>
<p>Training doesn&#8217;t guarantee any performance; it can only increase the chances of reaching your desired goal. I have accepted the fact that I may give 100% this time and again fail to meet my goal &#8211; that is just part of the game. You can&#8217;t be afraid to fail if you want to achieve something.</p>
<h2>Site updates</h2>
<p>Yet again, I&#8217;ve fallen behind with keeping this site up to date with articles and guides. It&#8217;s not that I don&#8217;t have any ideas, it&#8217;s just that I&#8217;ve been lazy to make the time to put them together. A combination of work, training and life has yet again provided me with the excuse to not further this site with articles that may be of importance to readers. </p>
<p>Writing tutorials and other informational articles is as much a help to me as it is to those who read them, so I will be putting more effort towards this. I hope that you have enjoyed the few that I have written this year.</p>
<hr/>Copyright &copy; 2013 <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><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/unitstep?a=AyFyEMp795o:dA99KSdoU94:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/unitstep?i=AyFyEMp795o:dA99KSdoU94:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=AyFyEMp795o:dA99KSdoU94:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/unitstep?i=AyFyEMp795o:dA99KSdoU94:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=AyFyEMp795o:dA99KSdoU94:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/unitstep?i=AyFyEMp795o:dA99KSdoU94:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=AyFyEMp795o:dA99KSdoU94:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/unitstep?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=AyFyEMp795o:dA99KSdoU94:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/unitstep?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/unitstep/~4/AyFyEMp795o" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2011/06/19/boston-reflection-and-updates/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		<feedburner:origLink>http://unitstep.net/blog/2011/06/19/boston-reflection-and-updates/</feedburner:origLink></item>
		<item>
		<title>Excess packaging</title>
		<link>http://feedproxy.google.com/~r/unitstep/~3/eVR-VlJub6Q/</link>
		<comments>http://unitstep.net/blog/2011/05/28/excess-packaging/#comments</comments>
		<pubDate>Sat, 28 May 2011 14:12:49 +0000</pubDate>
		<dc:creator>Peter Chng</dc:creator>
				<category><![CDATA[asides]]></category>
		<category><![CDATA[batteries]]></category>
		<category><![CDATA[dell]]></category>
		<category><![CDATA[packaging]]></category>

		<guid isPermaLink="false">http://unitstep.net/?p=1270</guid>
		<description><![CDATA[I recently ordered some extra Sanyo eneloop batteries when they were on sale at Dell. They&#8217;re great rechargeables, but I don&#8217;t know why most packages always come with a charger &#8211; I now have three of them from previous purchases. However, when I received the package from Dell, I was surprised at the size. It [...]]]></description>
			<content:encoded><![CDATA[<p>I recently ordered some extra Sanyo eneloop batteries when they were on sale at Dell. They&#8217;re great rechargeables, but I don&#8217;t know why most packages always come with a charger &#8211; I now have three of them from previous purchases.</p>
<p>However, when I received the package from Dell, I was surprised at the size. It came in a huge 18&#8243;x13&#8243; bubble envelope:</p>
<p class="image">
<a href="http://www.zooomr.com/photos/stygiansonic/9947217/" title="Photo Sharing"><img src="http://static.zooomr.com/images/9947217_eefd83418b_m.jpg" width="240" height="180" alt="Dell packaging" /></a></p>
<p>I thought it was just excess shipping packaging, but opening the enveloped made it clear that the packaging was only just big enough to hold the actual item:</p>
<p class="image"><a href="http://www.zooomr.com/photos/stygiansonic/9947222/" title="Photo Sharing"><img src="http://static.zooomr.com/images/9947222_75aaefa95e_m.jpg" width="240" height="180" alt="Huge eneloop package" /></a></p>
<p class="image"><a href="http://www.zooomr.com/photos/stygiansonic/9947226/" title="Photo Sharing"><img src="http://static.zooomr.com/images/9947226_b2fa56a4f3_m.jpg" width="240" height="180" alt="Green packaging?" /></a></p>
<p>For batteries with packaging that seems to imply they&#8217;re good for the environment, you think they would have made the packaging a little less excessive. The packaging is still 100% recyclable, but it still costs energy to make it.</p>
<p>At least Dell didn&#8217;t put the already-large item in a huge shipping box.</p>
<hr/>Copyright &copy; 2013 <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><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/unitstep?a=eVR-VlJub6Q:38ZiQA26-w0:D7DqB2pKExk"><img src="http://feeds.feedburner.com/~ff/unitstep?i=eVR-VlJub6Q:38ZiQA26-w0:D7DqB2pKExk" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=eVR-VlJub6Q:38ZiQA26-w0:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/unitstep?i=eVR-VlJub6Q:38ZiQA26-w0:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=eVR-VlJub6Q:38ZiQA26-w0:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/unitstep?i=eVR-VlJub6Q:38ZiQA26-w0:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=eVR-VlJub6Q:38ZiQA26-w0:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/unitstep?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/unitstep?a=eVR-VlJub6Q:38ZiQA26-w0:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/unitstep?d=yIl2AUoC8zA" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/unitstep/~4/eVR-VlJub6Q" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://unitstep.net/blog/2011/05/28/excess-packaging/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://unitstep.net/blog/2011/05/28/excess-packaging/</feedburner:origLink></item>
	</channel>
</rss>
