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

<channel>
	<title>Generation 5 &#187; Tools</title>
	<atom:link href="http://gen5.info/q/category/tools/feed/" rel="self" type="application/rss+xml" />
	<link>http://gen5.info/q</link>
	<description>Towards Intelligent Systems</description>
	<lastBuildDate>Fri, 20 Aug 2010 19:43:56 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>First-Class Functions and Logical Negation in C#</title>
		<link>http://gen5.info/q/2009/03/09/first-class-functions-and-logical-negation-in-c/</link>
		<comments>http://gen5.info/q/2009/03/09/first-class-functions-and-logical-negation-in-c/#comments</comments>
		<pubDate>Mon, 09 Mar 2009 13:50:39 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[Dot Net]]></category>
		<category><![CDATA[Functional Programming]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://gen5.info/q/?p=253</guid>
		<description><![CDATA[Introduction Languages such as LISP,  ML,  oCaml F# and Scala have supported first-class functions for a long time.  Functional programming features are gradually diffusing into mainstream languages such as C#,  Javascript and PHP.   In particular,  Lambda expressions,  implicit typing,  and delegate autoboxing have made  C# 3.0 an much more expressive language than it&#8217;s predecssors. In [...]]]></description>
			<content:encoded><![CDATA[<p><img style="margin-right:20px; margin-bottom:20px;" title="negation" src="http://gen5.info/q/wp-content/uploads/2009/03/negation.png" alt="negation" width="99" height="90" align="right" /></p>
<h2>Introduction</h2>
<p>Languages such as LISP,  ML,  oCaml F# and Scala have supported first-class functions for a long time.  Functional programming features are gradually diffusing into mainstream languages such as C#,  Javascript and PHP.   In particular,  Lambda expressions,  implicit typing,  and delegate autoboxing have made  C# 3.0 an much more expressive language than it&#8217;s predecssors.</p>
<p>In this article,  I develop a simple function that acts on functions:  given a boolean function<em> f</em>,  <em>F.Not(f)</em> returns a new boolean function which is the logical negation of <em>f</em>.  (That is,  <em>F.Not(f(x)) == !f(x)</em>).   Although the end function is simple to use,  I had to learn a bit about the details of C# to ge tthe behavior  I wanted &#8212; this article records that experience.<br />
<span id="more-253"></span></p>
<h2>Why?</h2>
<p>I was debugging an application that uses Linq-to-Objects the other day,  and ran into a bit of a pickle.  I had written an expression that would return true if all of the values in a List&lt;String&gt; were valid phone numbers:</p>
<pre>[01] dataColumn.All(Validator.IsValidPhoneNumber);</pre>
<p>I was expecting the list to validate successfully,  but the function was returning false.  Obviously at least one of the values in the function was not validating &#8212; but which one?  I tried using a lambda expression in the immediate window (which lets you type in expression while debugging) to reverse the order of matching:</p>
<pre>[02] dataColumn.Where(s =&gt; !ValidatorIsValidPhoneNumber(x));</pre>
<p>but that gave me the following error message:</p>
<pre>[03] Expression cannot contain lambda expressions</pre>
<p>(The expression compiler used in the immediate window doesn&#8217;t support all of the language features supported by the full C# compiler.)  I was able to answer find the non matching elements using the set difference operator</p>
<pre>[04] dataColumn.Except(dataColumn.Where(Validator.IsValidPhoneNumber).ToList()</pre>
<p>but I wanted an easier and more efficient way &#8212; with a logical negation function,  I could just write</p>
<pre>[05] dataColumn.Except(F.Not(Validator.IsValidPhoneNumber).ToList();</pre>
<h2>Try 1: Extension Method</h2>
<p>I wanted to make the syntax for negation as simple as possible.  I didn&#8217;t want to even have to name a class eliminate the need to name a class,  so I tried the following extension method:</p>
<pre>[06] static class FuncExtensions {
[07]    public static Func&lt;Boolean&gt; Not(this Func&lt;Boolean&gt; innerFunction) {
[08]       return ()  =&gt; innerFunction();
[09]    }
[10]    ...
[11]   }</pre>
<p>I was hoping that,  given a function like</p>
<pre>[12] public static boolean AlwaysTrue() { return true };</pre>
<p>that I could negate the function by writing</p>
<pre>[13] AlwaysTrue.Not()</pre>
<p>Unfortunately,  it doesn&#8217;t work that way:  the extension method can only be called on a delegate of type Func&lt;Boolean&gt;.  Although the compiler will &#8220;autobox&#8221; function references to delegates in many situations,  it doesn&#8217;t do it when you reference an extension method.  I could write</p>
<pre>[14] (Func&lt;Boolean&gt; AlwaysTrue).Not()</pre>
<p>but that&#8217;s not a pretty syntax.   At that point,  I tried another tack.</p>
<h2>Try 2: Static Method</h2>
<p>Next,  I defined a set of negation functions as static methods on a static class:</p>
<pre>[15] public static class F {
[16]    public static Func&lt;Boolean&gt; Not(Func&lt;Boolean&gt; innerFunction) {
[17]       return () =&gt; !innerFunction();
[18]    }
[19]
[20]    public static Func&lt;T1,Boolean&gt; Not&lt;T1&gt;(
[21]       Func&lt;T1,Boolean&gt; innerFunction) {
[22]          return x =&gt;!innerFunction(x);
[23]    }
[24]
[25]    public static Func&lt;T1, T2,Boolean&gt; Not&lt;T1,T2&gt;(
[26]       Func&lt;T1, T2,Boolean&gt; innerFunction) {
[27]          return (x,y) =&gt; !innerFunction(x,y);
[28]    }
[29]
[30]    public static Func&lt;T1, T2, T3, Boolean&gt; Not&lt;T1,T2,T3&gt;(
[31]       Func&lt;T1, T2, T3, Boolean&gt; innerFunction) {
[32]           return (x, y, z) =&gt; !innerFunction(x, y, z);
[33]    }
[34]
[35]    public static Func&lt;T1, T2, T3, T4, Boolean&gt; Not&lt;T1, T2, T3, T4&gt;(
[36]       Func&lt;T1, T2, T3, T4,Boolean&gt; innerFunction) {
[37]          return (x, y, z, a) =&gt; !innerFunction(x, y, z, a);
[38]    }
[39] }</pre>
<p>Now I can write</p>
<pre>[40] F.Not(AlwaysTrue)() // always == false</pre>
<p>or</p>
<pre>[41] Func&lt;int,int,int,int,Boolean&gt; testFunction = (a,b,c,d) =&gt; (a+b)&gt;(c+d)
[42] F.Not(testFunction)(1,2,3,4)</pre>
<p>which is sweet &#8212; the C# compiler now automatically autoboxes the argument to <em>F.Not</em> on line [40].  Note two details of how type inference works here:</p>
<ol>
<li>The compiler automatically infers the type parameters of <em>F.Not()</em> by looking at the arguments of the <em>innerFunction</em>.  If it didn&#8217;t do that,  you&#8217;d need to write
<pre>F.Not&lt;int,int,int,int&gt;(testFunction)(1,2,3,4)</pre>
<p>which would be a lot less fun.</li>
<li>On line [40],  note that the compiler derives the types of the parameters <em>a</em>,<em>b</em>,<em>c</em>, and <em>d</em> using the type declaration on the right hand side (RHS)
<pre>Func&lt;int,int,int,int,Boolean&gt;</pre>
<p>you can&#8217;t write <em>var</em> on the RHS in this situation because that doesn&#8217;t give the compiler information about the parameters and return values of the lambda.</li>
</ol>
<p>Although good things are happening behind the scenes,  there are also two bits of ugliness:</p>
<ol>
<li>I need to implement <em>F.Not()</em> 5 times to support functions with 0 to 4 parameters:  once I&#8217;ve done that,  however,  the compiler automatically resolves the overloading and picks the right version of the function.</li>
<li>The generic <em>Func&lt;&gt;</em> and <em>Action&lt;&gt;</em> delegates support at most 4 parameters.  Although it&#8217;s certainly true that functions with a large number of parameters can be difficult to use and maintain (and should be discouraged),  this is a real limitation.</li>
</ol>
<h2>Extending IEnumerable&lt;T&gt;</h2>
<p>One of the nice things about Linq is that you can extend it by adding new extension methods to IEnumerable.  Not everbody agrees,  but I&#8217;ve always liked the <em>unless()</em> satement in Perl,  which is equivalent to if(!test):</p>
<pre>[42] unless(everything_is_ok()) {
[43]   abort_operation;
[44] }</pre>
<p>A replacement for the <em>Where(predicate)</em> method that negates the <em>predicate</em> function would be convenient my debugging problem:</p>
<p>I built an<em> Unless()</em> extension method that combines <em>Where()</em> with<em> F.Not()</em>:</p>
<pre>[45] public static IEnumerable&lt;T&gt; Unless&lt;T&gt;(
[46]    this IEnumerable&lt;T&gt; input, Func&lt;T, Boolean&gt; fn) {
[47]       return input.Where(F.Not(fn));
[48]     }</pre>
<p>Now I can write</p>
<pre>[49] var list = new List&lt;int&gt;() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
[50] var filtered = list.Unless(i =&gt; i &gt; 3).ToList();</pre>
<p>and get the result</p>
<pre>[51] filtered = { 1,2,3 }</pre>
<h2>Conclusion</h2>
<p>New features in C# 3.0 make it an expressive language for functional programming.  Although the syntax of C# isn&#8217;t quite as sweet as F# or Scala,  a programmer who works with the implicit typing and autoboxing rules of the compiler can create functions that act on functions that are easy to use &#8212; in this article we develop a set of functions that negate boolean functions and apply this to add a new restriction method to IEnumerable&lt;T&gt;.</p>
<p>
<a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fgen5.info%2fq%2f2009%2f03%2f09%2ffirst-class-functions-and-logical-negati"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fgen5.info%2fq%2f2009%2f03%2f09%2ffirst-class-functions-and-logical-negati" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2009/03/09/first-class-functions-and-logical-negation-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Putting Freebase in a Star Schema</title>
		<link>http://gen5.info/q/2009/02/25/putting-freebase-in-a-star-schema/</link>
		<comments>http://gen5.info/q/2009/02/25/putting-freebase-in-a-star-schema/#comments</comments>
		<pubDate>Wed, 25 Feb 2009 14:33:36 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[Freebase]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[Semantic Web]]></category>

		<guid isPermaLink="false">http://gen5.info/q/?p=223</guid>
		<description><![CDATA[What&#8217;s Freebase? Freebase is a open database of things that exist in the world:  things like people,  places,  songs and television shows.   As of the January 2009 dump,  Freebase contained about 241 million facts,  and it&#8217;s growing all the time.  You can browse it via the web and even edit it,  much like Wikipedia.  [...]]]></description>
			<content:encoded><![CDATA[<h2>What&#8217;s Freebase?</h2>
<p><img style="margin-left: 10px" title="cyclopedia" src="http://gen5.info/q/wp-content/uploads/2009/02/cyclopedia.jpg" alt="cyclopedia" width="240" height="161" align="right" /><br />
<a href="http://www.freebase.com/">Freebase</a> is a open database of things that exist in the world:  things like people,  places,  songs and television shows.   As of the January 2009 dump,  Freebase contained about 241 million facts,  and it&#8217;s growing all the time.  You can browse it via the web and even edit it,  much like Wikipedia.  Freebase also has an API that lets programs add data and make queries using a language called <a href="http://mql.freebaseapps.com/">MQL</a>.  Freebase is complementary to <a href="http://dbpedia.org/About">DBpedia</a> and other sources of information.  Although it takes a different approach to the semantic web than systems based on RDF standards,  it interoperates with them via <a href="http://www.semanticfocus.com/blog/entry/title/freebase-officially-linked-data-with-release-of-rdf-service/"> linked data</a>.</p>
<p>The January 2009 Freebase dump is about 500 MB in size.  Inside a bzip-compressed files,  you&#8217;ll find something that&#8217;s similar in spirit to a Turtle RDF file,  but is in a simpler format and represents facts as a collection of four values rather than just three.</p>
<h2>Your Own Personal Freebase</h2>
<p>To start exploring and extracting from Freebase,  I wanted to load the database into a star schema in a mysql database &#8212; an architecture similar to some RDF stores,  such as <a href="http://arc.semsol.org/">ARC</a>.  The project took about a week of time on a modern x86 server with 4 cores and 4 GB of RAM and resulted in a 18 GB collection of database files and indexes.</p>
<p>This is sufficient for my immediate purposes,  but future versions of Freebase promise to be much larger:  this article examines the means that could be used to improve performance and scalability using parallelism as well as improved data structures and algorithms.<span id="more-223"></span></p>
<p>I&#8217;m interested in using generic databases such as Freebase and Dbpedia as a data source for building web sites.  It&#8217;s possible to access generic databases through  APIs,  but there are advantages to having your own copy:  you don&#8217;t need to worry about API limits and network latency,  and you can ask questions that cover the entire universe of discourse.</p>
<p>Many RDF stores use variations of a format known as a Star Schema for representing RDF triples;  the Star Schema is commonly used in data warehousing application because it can efficiently represent repetitive data.   Freebase is similar to,  but not quite an RDF system.  Although there are multiple ways of thinking about Freebase,  the quarterly dump files provided by Metaweb are presented as quads:  groups of four related terms in tab-delimited terms.  To have a platform for exploring freebase,  I began a project of loading Freebase into a Star Schema in a relational database.</p>
<h2>A Disclaimer</h2>
<p>Timings reported in this article are approximate.  This work was done on a server that was doing other things; little effort was made to control sources of variation such as foreign workload,  software configuration and hardware characteristics.  I think it&#8217;s orders of magnitude that matter here:  with much larger data sets becoming available,  we need tools that can handle databases 10-100 times as big,  and quibbling about 20% here or there isn&#8217;t so important.  I&#8217;ve gotten similar results with the ARC triple store.  Some products do about an order of magnitude better:  the <a href="http://virtuoso.openlinksw.com/wiki/main/Main/VOSRDF">Virtuoso</a> server can load DBpedia,  a larger database,  <a href="http://esw.w3.org/topic/SweoIG/TaskForces/CommunityProjects/LinkingOpenData"> in about 16 to 22 hours on a 16 GB computer</a>:  several papers on RDF store performance are available [<a href="http://www4.wiwiss.fu-berlin.de/bizer/BerlinSPARQLBenchmark/">1</a>] [<a href="http://www4.wiwiss.fu-berlin.de/benchmarks-200801/">2</a>] [<a href="http://esw.w3.org/topic/RdfStoreBenchmarking">3</a>].  Although the system described in this paper isn&#8217;t quite an RDF store,  it&#8217;s performance is comprable to a relatively untuned RDF store.</p>
<p>It took about a week of calendar time to load the 241 million quads in the January 2009 Freebase into a Star Schema using a modern 4-core web server with 4GB of RAM;  this time could certainly be improved with microoptimizations,  but it&#8217;s in the same range that people are observing that it takes to load 10^8 triples into other RDF stores.  (One product is claimed to load DBPedia,  which contains about 100 million triples,  in about <a href="http://esw.w3.org/topic/SweoIG/TaskForces/CommunityProjects/LinkingOpenData">16 hours with &#8220;heavy-duty hardware&#8221;</a>.)   Data sets exceeding 10^9 triples are becoming rapidly available &#8212; these will soon exceed what can be handled with simple hardware and software and will require new techniques:  both the use of parallel computers and optimized data structures.</p>
<h2>The Star Schema</h2>
<p>In a star schema,  data is represented in separate fact and dimension tables,</p>
<p><img class="aligncenter size-full wp-image-229" title="300px-star-schema" src="http://gen5.info/q/wp-content/uploads/2009/02/300px-star-schema.png" alt="300px-star-schema" width="300" height="188" /></p>
<p>all of the rows in the fact table (<em>quad</em>) contain integer keys &#8212; the values associated with the keys are defined in dimension tables (<em>cN_value</em>).  This efficiently compresses the data and indexes for the fact table,  particularly when the values are highly repetitive.</p>
<p>I loaded data into the following schema:</p>
<pre>create table c1_value (
   id             integer primary key auto_increment,
   value          text,
   key(value(255))
) type=myisam;

... identical c2_value, c3_value and c4_value tables ...

create table quad (
   id             integer primary key auto_increment,
   c1             integer not null,
   c2             integer not null,
   c3             integer not null,
   c4             integer not null
) type=myisam;</pre>
<p>Although I later created indexes on<em> c1, c2, c3,</em> and <em>c4</em> in the quad table,  I left unnecessary indexes off of the tables during the loading process because it&#8217;s more efficient to create indexes after loading data in a table.  The keys on the value fields of the dimension tables are important,  because the loading process does frequent queries to see if values already exist in the dimension table.  The sequentially assigned <em>id</em> in the <em>quad</em> field isn&#8217;t necessary for many applications,  but it gives each a fact a unique identity and makes the system aware of the order of facts in the dump file.</p>
<h2>The Loading Process</h2>
<p>The loading script was written in PHP and used a naive method to build the index incrementally.  In pseudo code it looked something like this:</p>
<pre>function insert_quad($q1,$q2,$q3,$q4) {
    $c1=get_dimension_key(1,$q1);
    $c2=get_dimension_key(2,$q2);
    $c3=get_dimension_key(3,$q3);
    $c4=get_dimension_key(4,$q4);
    $conn-&gt;insert_row("quad",null,$c1,$c2,$c3,$c4)
}

function get_dimension_key($index,$value) {
    $cached_value=check_cache($value);
    if ($cached_value)
        return $cached_value;

    $table="$c{$index}_value";
    $row=$conn-&gt;fetch_row_by_value($table,$value);
    if ($row)
        return $row-&gt;id;
    $conn-&gt;insert_row($table,$value);
    return $conn-&gt;last_insert_id
};</pre>
<p>Caching frequently used dimension values improves performance by a factor of five or so,  at least in the early stages of loading.  A simple cache management algorithm,  clearing the cache every 500,000 facts,  controls memory use.  Timing data shows that a larger cache or better replacement algorithm would make at most an increment improvement in performance.  (Unless a complete dimension table index can be held in RAM,  in which case all read queries can be eliminated.)</p>
<p>I performed two steps after the initial load:</p>
<ol>
<li>Created indexes on<em> quad(c1), quad(c2), quad(c3) </em>and <em>quad(c4)</em></li>
<li>Used myisam table compression to reduce database size and improve performance</li>
</ol>
<h2>Loading Performance</h2>
<p>It took about 140 hours (nearly 6 days) to do the initial load.  Here&#8217;s a graph of facts loaded vs elapsed time:</p>
<p><img class="alignnone size-full wp-image-225" title="quad_time" src="http://gen5.info/q/wp-content/uploads/2009/02/quad_time.png" alt="quad_time" width="604" height="427" /></p>
<p>The important thing Iabout this graph is that it&#8217;s convex upward:  the loading process slows down as the number of facts increases.  The first 50 quads are loaded at a rate of about 6 million per hour;  the last 50 are loaded at a rate of about 1 million per hour.  An explanation of the details of the curve would be complex,  but<em> log N </em>search performance of B-tree indexes and the ability of the database to answer queries out of the computer&#8217;s RAM cache would be significant.  Generically,  all databases will perform the same way,  becoming progressively slower as the size of the database increases:  you&#8217;ll eventually reach a database size where the time to load the database becomes unacceptable.</p>
<p>The process of constructing b-tree indexes on the mysql tables took most of a day.  On average it took about four hours to construct a b-tree index on one column of <em>quad</em>:</p>
<pre>mysql&gt; create index quad_c4 on quad(c4);
Query OK, 243098077 rows affected (3 hours 40 min 50.03 sec)
Records: 243098077  Duplicates: 0  Warnings: 0</pre>
<p>It took about an hour to compress the tables and rebuild indexes,  at which point the data directory looks like:</p>
<pre>-rw-r----- 1 mysql root        8588 Feb 22 18:42 c1_value.frm
-rw-r----- 1 mysql root   713598307 Feb 22 18:48 c1_value.MYD
-rw-r----- 1 mysql root   557990912 Feb 24 10:48 c1_value.MYI
-rw-r----- 1 mysql root        8588 Feb 22 18:56 c2_value.frm
-rw-r----- 1 mysql root      485254 Feb 22 18:46 c2_value.MYD
-rw-r----- 1 mysql root      961536 Feb 24 10:48 c2_value.MYI
-rw-r----- 1 mysql root        8588 Feb 22 18:56 c3_value.frm
-rw-r----- 1 mysql root   472636380 Feb 22 18:51 c3_value.MYD
-rw-r----- 1 mysql root   370497536 Feb 24 10:51 c3_value.MYI
-rw-r----- 1 mysql root        8588 Feb 22 18:56 c4_value.frm
-rw-r----- 1 mysql root  1365899624 Feb 22 18:44 c4_value.MYD
-rw-r----- 1 mysql root  1849223168 Feb 24 11:01 c4_value.MYI
-rw-r----- 1 mysql root          65 Feb 22 18:42 db.opt
-rw-rw---- 1 mysql mysql       8660 Feb 23 17:16 quad.frm
-rw-rw---- 1 mysql mysql 3378855902 Feb 23 20:08 quad.MYD
-rw-rw---- 1 mysql mysql 9927788544 Feb 24 11:42 quad.MYI</pre>
<p>At this point it&#8217;s clear that the indexes are larger than the actual databases:  note that <em>c2_value</em> is much smaller than the other tables because it holds a relatively small number of predicate types:</p>
<pre>mysql&gt; select count(*) from c2_value;
+----------+
| count(*) |
+----------+
|    14771 |
+----------+
1 row in set (0.04 sec)

mysql&gt; select * from c2_value limit 10;
+----+-------------------------------------------------------+
| id | value                                                 |
+----+-------------------------------------------------------+
|  1 | /type/type/expected_by                                |
|  2 | reverse_of:/community/discussion_thread/topic         |
|  3 | reverse_of:/freebase/user_profile/watched_discussions |
|  4 | reverse_of:/freebase/type_hints/included_types        |
|  5 | /type/object/name                                     |
|  6 | /freebase/documented_object/tip                       |
|  7 | /type/type/default_property                           |
|  8 | /type/type/extends                                    |
|  9 | /type/type/domain                                     |
| 10 | /type/object/type                                     |
+----+-------------------------------------------------------+
10 rows in set (0.00 sec)</pre>
<p>The total size of the mysql tablespace comes to about 18GB,  anexpansion of about 40 times relative to the bzip2 compressed dump file.</p>
<h2>Query Performance</h2>
<p>After all of this trouble,  how does it perform?  Not too bad if we&#8217;re asking a simple question,  such as pulling up the facts associated with a particular object</p>
<pre>mysql&gt; select * from quad where c1=34493;
+---------+-------+------+---------+--------+
| id      | c1    | c2   | c3      | c4     |
+---------+-------+------+---------+--------+
| 2125876 | 34493 |   11 |      69 | 148106 |
| 2125877 | 34493 |   12 | 1821399 |      1 |
| 2125878 | 34493 |   13 | 1176303 | 148107 |
| 2125879 | 34493 | 1577 |      69 | 148108 |
| 2125880 | 34493 |   13 | 1176301 | 148109 |
| 2125881 | 34493 |   10 | 1713782 |      1 |
| 2125882 | 34493 |    5 | 1174826 | 148110 |
| 2125883 | 34493 | 1369 | 1826183 |      1 |
| 2125884 | 34493 | 1578 | 1826184 |      1 |
| 2125885 | 34493 |    5 |      66 | 148110 |
| 2125886 | 34493 | 1579 | 1826185 |      1 |
+---------+-------+------+---------+--------+
11 rows in set (0.05 sec)</pre>
<p>Certain sorts of aggregate queries are reasonably efficient,  if you don&#8217;t need to do them too often:  we can look up the most common 20 predicates in about a minute:</p>
<pre>select
   (select value from c2_value as v where v.id=q.c2) as predicate,count(*)
   from quad as q
     group by c2
     order by count(*) desc
     limit 20;</pre>
<pre>+-----------------------------------------+----------+
| predicate                               | count(*) |
+-----------------------------------------+----------+
| /type/object/type                       | 27911090 |
| /type/type/instance                     | 27911090 |
| /type/object/key                        | 23540311 |
| /type/object/timestamp                  | 19462011 |
| /type/object/creator                    | 19462011 |
| /type/permission/controls               | 19462010 |
| /type/object/name                       | 14200072 |
| master:9202a8c04000641f800000000000012e |  5541319 |
| master:9202a8c04000641f800000000000012b |  4732113 |
| /music/release/track                    |  4260825 |
| reverse_of:/music/release/track         |  4260825 |
| /music/track/length                     |  4104120 |
| /music/album/track                      |  4056938 |
| /music/track/album                      |  4056938 |
| /common/document/source_uri             |  3411482 |
| /common/topic/article                   |  3369110 |
| reverse_of:/common/topic/article        |  3369110 |
| /type/content/blob_id                   |  1174046 |
| /type/content/media_type                |  1174044 |
| reverse_of:/type/content/media_type     |  1174044 |
+-----------------------------------------+----------+
20 rows in set (43.47 sec)</pre>
<p>You&#8217;ve got to be careful how you write your queries:  the above query with the subselect is efficient,  but I found it took 5 hours to run when I joined <em>c2_value</em> with quad and grouped on <em>value</em>.  A person who wishes to do frequent aggregate queries would find it most efficient to create a materialized views of the aggregates.</p>
<h2>Faster And Large</h2>
<p>It&#8217;s obvious that the Jan 2009 Freebase is pretty big to handle with the techniques I&#8217;m using.  One thing I&#8217;m sure of is that that Freebase will be much bigger next quarter &#8212; I&#8217;m not going to do it the same way again.  What can I do to speed the process up?</p>
<h3>Don&#8217;t Screw Up</h3>
<p>This kind of process involves a number of lengthy steps.  Mistakes,  particularly if repeated,  can waste days or weeks.  Although services such as EC2 are a good way to provision servers to do this kind of work,  the use of automation and careful procedures is key to saving time and money.</p>
<h3>Partition it</h3>
<p>Remember how the loading rate of a data set decreases as the size of the set increase?  If I could split the data set into 5 partitions of 50 M quads each,  I could increase the loading rate by a factor of 3 or so.  If I can build those 5 partitions in parallel (which is trivial),  I can reduce wallclock time by a factor of 15.</p>
<h3>Eliminate Random Access I/O</h3>
<p>This loading process is slow because of the involvement of random access disk I/O.  All of Freebase canbe loaded into mysql with the following statement,</p>
<p>LOAD DATA INFILE &#8216;/tmp/freebase.dat&#8217; INTO TABLE q FIELDS TERMINATED  BY &#8216;\t&#8217;;</p>
<p>which took me about 40 minutes to run.   Processes that do a &#8220;full table scan&#8221; on the raw Freebase table with a <em>grep</em> or <em>awk</em>-type pipeline take about 20-30 minutes to complete.  Dimension tables can be built quickly if they can be indexed by a RAM  hasthable.   The process that builds the dimension table can emit a list of key values for the associated quads:  this output can be sequentially merged to produce the fact table.</p>
<h3>Bottle It</h3>
<p>Once a data source has been loaded into a database,  a physical copy of the database can be made and copied to another machine.  Copies can be made in the fraction of the time that it takes to construct the database.  A good example is the<a href="http://virtuoso.openlinksw.com/wiki/main/Main/VirtInstallationEC2"> Amazon EC2 AMI</a> that contains a preinstalled and preloaded <a href="http://virtuoso.openlinksw.com/">Virtuoso database</a> loaded with billions of triples from DBPedia,  MusicBrainz,  NeuroCommons and a number of other databases.  Although the process of creating the image is complex,  a new instance can be provisioned in 1.5 hours at the click of a button.</p>
<h3>Compress Data Values</h3>
<p>Unique object identifiers in freebase are coded in an inefficient ASCII representation:</p>
<pre>mysql&gt; select * from c1_value limit 10;
+----+----------------------------------------+
| id | value                                  |
+----+----------------------------------------+
|  1 | /guid/9202a8c04000641f800000000000003b |
|  2 | /guid/9202a8c04000641f80000000000000ba |
|  3 | /guid/9202a8c04000641f8000000000000528 |
|  4 | /guid/9202a8c04000641f8000000000000836 |
|  5 | /guid/9202a8c04000641f8000000000000df3 |
|  6 | /guid/9202a8c04000641f800000000000116f |
|  7 | /guid/9202a8c04000641f8000000000001207 |
|  8 | /guid/9202a8c04000641f80000000000015f0 |
|  9 | /guid/9202a8c04000641f80000000000017dc |
| 10 | /guid/9202a8c04000641f80000000000018a2 |
+----+----------------------------------------+
10 rows in set (0.00 sec)</pre>
<p>These are 38 bytes apiece.  The hexadecimal part of the guid could be represented in 16 bytes in a binary format,  and it appears that about half of the guid is a constant prefix that could be further excised.</p>
<p>A similar efficiency can be gained in the construction of in-memory dimension tables: md5 or sha1 hashes could be used as proxies for values.</p>
<p>The freebase dump is littered with &#8220;reverse_of:&#8221; properties which are superfluous if the correct index structures exist to do forward and backward searches.</p>
<h3>Parallelize it</h3>
<p>Loading can be parallelized in many ways:  for instance,  the four dimension tables can be built in parallel.  Dimension tables can also be built by a sorting process that can be performed on a computer cluster using map/reduce techniques.  A cluster of computers can also store a knowledge base in RAM,  trading sequential disk I/O for communication costs.  Since the availability of data is going to grow faster than the speed of storage systems,  parallelism is going to become essential for handling large knowledge bases &#8212; an issue identified by Japanese AI workers in the early 1980&#8242;s.</p>
<h3>Cube it?</h3>
<p>Some queries  benefit from indexes built on combinations of tables,  such as</p>
<p>CREATE INDEX quad_c1_c2 ON quad(c1,c2);</p>
<p>there are 40 combinations of columns on which an index could be useful &#8212; however,  the cost in time and storage involved in creating those indexes would be excessively expensive.  If such indexes were indeed necessary, a <a href="http://www.design-ireland.net/index.php?http%3A//www.design-ireland.net/alpha/controller/view_article.php%3Foid%3D00000000036">Multidimensional database</a> can create a cube index that is less expensive than a complete set of B-tree indexes.</p>
<h3>Break it up into separate tables?</h3>
<p>It might be anathema to many semweb enthusiasts,  but I think that Freebase (and parts of Freebase) could be efficiently mapped to conventional relational tables.  That&#8217;s because facts in Freebase are associated with types,  see,  for instance,  <a href="http://www.freebase.com/type/schema/music/composer">Composer</a> from the <a href="http://www.freebase.com/view/music">Music Commons</a>.  It seems reasonable to map types to relational tables and to create satellite tables to represent many-to-many relationships between types.  This scheme would automatically partition Freebase in a reasonable way and provide an efficient representation where many obvious questions (ex. &#8220;Find Female Composers Born In 1963 Who Are More Than 65 inches tall&#8221;) can be answered with a minimum number of joins.</p>
<h2>Conclusion</h2>
<p>Large knowledge bases are becoming available that cover large areas of human concern:  we&#8217;re finding many applications for them.  It&#8217;s possible to to handle databases such as Freebase and DBpedia on a single computer of moderate size,  however,  the size of generic databases and the hardware to store them on are going to grow larger than the ability of a singler computer to process them.  Fact stores that (i) use efficient data structures,  (ii) take advantage of parallelism,  and (iii) can be tuned to the requirements of particular applications,  are going to be essential for further progress in the Semantic Web.</p>
<h2>Credits</h2>
<ul>
<li>Metaweb Technologies, <a href="http://download.freebase.com/datadumps/">Freebase Data Dumps</a>, January 13, 2009</li>
<li><a href="http://www.openlinksw.com/blog/~kidehen">Kingsley Idehen</a>,  for several links about RDF store performance.</li>
<li><a href="http://www.flickr.com/photos/stewart/">Stewart Butterfield</a> for<a href="http://www.flickr.com/photos/stewart/461099066/"> encyclopedia photo</a>.</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2009/02/25/putting-freebase-in-a-star-schema/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Using Linq To Tell if the Elements of an IEnumerable Are Distinct</title>
		<link>http://gen5.info/q/2009/02/13/using-linq-to-tell-if-the-elements-of-an-ienumerable-are-distinct/</link>
		<comments>http://gen5.info/q/2009/02/13/using-linq-to-tell-if-the-elements-of-an-ienumerable-are-distinct/#comments</comments>
		<pubDate>Fri, 13 Feb 2009 21:15:38 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[Dot Net]]></category>
		<category><![CDATA[Linq]]></category>

		<guid isPermaLink="false">http://gen5.info/q/?p=213</guid>
		<description><![CDATA[The Problem I&#8217;ve got an IEnumerable&#60;T&#62; that contains a list of values:  I want to know if all of the values in that field are distinct.  The function should be easy to use a LINQ extension method and,  for bonus points,  simply expressed in LINQ itself One Solution First,  define an extension method 01   public [...]]]></description>
			<content:encoded><![CDATA[<h2><a href="http://gen5.info/q/wp-content/uploads/2009/02/ducks.jpg"><img class="title=&quot;ducks&quot;" src="http://gen5.info/q/wp-content/uploads/2009/02/ducks-300x195.jpg" alt="" width="300" height="195" align="right" /></a>The Problem</h2>
<p>I&#8217;ve got an <em>IEnumerable&lt;T&gt;</em> that contains a list of values:  I want to know if all of the values in that field are distinct.  The function should be easy to use a LINQ extension method and,  for bonus points,  simply expressed in LINQ itself</p>
<h2>One Solution</h2>
<p>First,  define an extension method</p>
<pre>01   public static class IEnumerableExtensions {
02        public static bool AllDistinct&lt;T&gt;(this IEnumerable&lt;T&gt; input) {
03            var count = input.Count();
04            return count == input.Distinct().Count();
05        }
06    }</pre>
<p>When you want to test an <em>IEnumerable&lt;T&gt;</em>,  just write</p>
<pre>07 var isAPotentialPrimaryKey=CandidateColumn.AllDistinct();</pre>
<h2><span id="more-213"></span>Analysis</h2>
<p>This solution is simple and probably scales as well as any solution in the worst case.  However,  it enumerates the <em>IEnumerable&lt;T&gt;</em> twice and does a full scan of the IEnumerable even if non-distinct elements are discovered early in the enumeration.  I could certainly make an implementation that aborts early using a <em>Dictionary&lt;T,bool&gt;</em> to store elements we&#8217;ve seen and a foreach loop,  but I wonder if anyone out there can think of a better pure-Linq solution.</p>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2009/02/13/using-linq-to-tell-if-the-elements-of-an-ienumerable-are-distinct/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Subverting XAML: How To Inherit From Silverlight User Controls</title>
		<link>http://gen5.info/q/2009/02/10/subverting-xaml-how-to-inherit-from-silverlight-user-controls/</link>
		<comments>http://gen5.info/q/2009/02/10/subverting-xaml-how-to-inherit-from-silverlight-user-controls/#comments</comments>
		<pubDate>Tue, 10 Feb 2009 20:31:21 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[Dot Net]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://gen5.info/q/?p=188</guid>
		<description><![CDATA[The Problem Many Silverlighters use XAML to design the visual appearance of their applications.  A UserControl defined with XAML is a DependencyObject that has a complex lifecycle:  there&#8217;s typically a .xaml file,  a .xaml.cs file,  and a .xaml.g.cs file that is generated by visual studio. The .xaml.g.cs file is generated by Visual Studio,  and ensures [...]]]></description>
			<content:encoded><![CDATA[<h2><a href="http://gen5.info/q/wp-content/uploads/2009/02/noxamlinheritance.png"><img style="float: right;" title="noxamlinheritance" src="http://gen5.info/q/wp-content/uploads/2009/02/noxamlinheritance.png" alt="" width="343" height="254" /></a>The Problem</h2>
<p>Many Silverlighters use XAML to design the visual appearance of their applications.  A UserControl defined with XAML is a <em>DependencyObject</em> that has a complex lifecycle:  there&#8217;s typically a .xaml file,  a .xaml.cs file,  and a .xaml.g.cs file that is generated by visual studio. The .xaml.g.cs file is generated by Visual Studio,  and ensures that objects defined in the XAML file correspond to fields in the object (so they are seen in intellisense and available to your c# code.)  The XAML file is re-read at runtime,  and drives a process that instantiates the actual objects defined in the XAML file &#8212; a program can compile just fine,  but fail during initialization if the XAML file is invalid or if you break any of the assumptions of the system.</p>
<p>XAML is a pretty neat system because it&#8217;s not tied to WPF or WPF/E.  It can be used to initialize any kind of object:  for instance,  it can be used to design workflows in asynchronous server applications based on Windows Workflow Foundation.</p>
<p>One problem with XAML,  however,  is that you cannot write controls that inherit from a UserControl that defined in XAML.  Visual Studio might compile the classes for you,  but they will fail to initialize at at runtime.  This is serious because it makes it impossible to create subclasses that let you make small changes to the appearance or behavior of a control.</p>
<p><span id="more-188"></span></p>
<h2>Should We Just Give Up?</h2>
<p>One approach is to give up on XAML.  Although Visual Studio encourages you to create UserControls with XAML,  there&#8217;s nothing to stop you from creating a new class file and writing something like</p>
<pre>class MyUserControl:UserControl {
      public MyUserControl {
      var innerPanel=new StackPanel();
      Content=innerPanel;
      innerPanel.Children.Add(new MyFirstVisualElement());
      innerPanel.Children.Add(new MySecondVisualElement());
      ...
}</pre>
<p>UserControls defined like this have no (fundamental) problems with inheritance,  since you&#8217;ve got complete control of the initialization process.  If it were up to me,  I&#8217;d write a lot of controls like this,  but I work on a team with people who design controls in XAML,  so I needed a better solution.</p>
<h2>Or Should We Just Cheat?</h2>
<p>If we still want to use XAML to define the appearance of a control,  we&#8217;ve got another option.  We can move the XAML into a control that is outside the inheritance hierarchy:  the XAML control is then contained inside another control which doesn&#8217;t have restrictions as to how it is used:</p>
<p><a href="http://gen5.info/q/wp-content/uploads/2009/02/cheatingxaml.png"><img class="aligncenter size-full wp-image-192" title="cheatingxaml" src="http://gen5.info/q/wp-content/uploads/2009/02/cheatingxaml.png" alt="" /></a></p>
<p>The <em>XamlPanelInnards.xaml.cs</em> code-behind is almost completely empty:  it contains only the constructor created by Visual Studio&#8217;s XAML designer.  <em>XamlPanel.cs</em> contains a protected member called <em>InnerControl</em> which is of type <em>XamlPanelInnards</em>.  <em>InnerControl</em> is initialized in the constructor of <em>XamlPanel</em>,  and is also assigned to the <em>Content</em> property of the <em>XamlPanel</em>,  to make it visible.  Everything that you&#8217;d ordinarily put in the code-behind <em>XamlPanelInnards.xaml.cs</em> goes into XamlPanel.cs,  which uses the <em>InnerControl</em> member to get access to the <em>internal</em> members defined by the XAML designer.</p>
<h2>Step-by-Step Refactoring</h2>
<p>Let&#8217;s imagine that we&#8217;ve got an existing <em>UserControl</em> implemented in XAML called the <em>XamlPanel</em>.  We&#8217;d like to subclass the <em>XamlPanel </em>so we can use it for multiple purposes.  We can do this by:</p>
<ol>
<li>Renaming <em>XamlPanel</em> to <em>OldXamlPanel</em>;  this renames both the *.xaml and *.xaml.cs files so we can have them to look at</li>
<li>Use Visual Studio to create a new &#8220;Silverlight User Control&#8221; called <em>XamlPanelInnards</em>.  This will have both a *.xaml and *.xaml.xs file</li>
<li>Copy the contents of OldXamlPanel.xaml to XamlPanelInnards.cs.  Edit the x:Class attribute of the &lt;UserControl&gt; element to reflect the new class name,  &#8220;XamlPanelInnards&#8221;</li>
<li>Use Visual Studio to create a new <strong>class</strong>,  called XamlPanel.cs.  Do not create a XamlPanel.xaml.cs file!</li>
<li>Copy the constructor,  methods,  fields and properties from the OldXamlPanel.xaml.cs file to the XamlPanel.cs file.</li>
<li>Create a new private field in XamlPanel.cs like
<pre>private XamlPanelInnards InnerControl;</pre>
</li>
<li>Now we modify the constructor,  so that it does something like this:
<pre>public XamlPanel() {
   InnerControl = new XamlPanelInnards();
   Content = InnerControl;
   ... remainder of the constructor ...
}</pre>
</li>
<li>Most likely you&#8217;ll have compilation errors in the XamlPanel.cs file because there are a lot of references to public fields that are now in the InnerControl.  You need to track these down,  and replace code that looks like
<pre>TitleTextBlock.Text="Some Title";</pre>
<p>with</p>
<pre>InnerControl.TitleTextBlock.Text="SomeTitle";</pre>
</li>
<li>Any event handler attachments done from the XAML file will fail to work (they&#8217;ll trigger an error when you load the application.)  You&#8217;ll need to convert
<pre>&lt;Button x:PressMe ... Click="PressMe_OnClick"&gt;</pre>
<p>in the XAML file to</p>
<pre>InnerControl.PressMe.Click += PressMe_OnClick</pre>
<p>in the constructor of XamlPanel.</li>
<li style="text-align: left;">UI Elements that are defined in XAML are public,  so there&#8217;s a good chance that other classes might expect UI Elements inside the XamlPanel to be accessable.  You&#8217;ve got some choices:  (a) make the InnerControl public and point those references to the InnerControl (yuck!),  (b) selectively add properties to XamlPanel to let outside classes access the elements that they need to access,  or (c) rethink the encapsulation so that other class don&#8217;t need direct access to the members of XamlPanelInnards.</li>
<li>There are a few special methods that are defined in DependencyObject and FrameworkElement that you&#8217;ll need to pay attention to.  For instance,  if your class uses FindName to look up elements dynamically,  you need to replace
<pre>FindName("Control"+controlNumber);</pre>
<p>with</p>
<pre>InnerControl.FindName("Control"+controlNumber);</pre>
</li>
</ol>
<p>So far this is a refactoring operation:  we&#8217;re left with a program that does what it already did,  but is organized differently.  Where can we go from here?</p>
<h2>Extending The XamlPanel</h2>
<p>At this point,  the XamlPanel is an ordinary UserControl class.  It&#8217;s initialization logic is self-sufficient,  so it can inherit (it doesn&#8217;t necessarily have to derive from UserControl) and be inherited from quite freely.</p>
<p>If we want to change the behavior of the XamlPanel,  for instance,  we could declare it abstract and leave certain methods (such as event handlers) abstract.  Alternately,  methods could be declared as virtual.</p>
<p>A number of methods exist to customize the appearance of XamlPanel:  since XamlPanel can see the objects inside XamlPanelInnards,  it can change colors,  image sources and text contents.  If you&#8217;re interested in adding additional graphical element to the Innards,  the innards can contain an empty StackPanel &#8212; children of XamlPanel can Add() something to the StackPanel in their constructors.</p>
<p>Note that you can still include a child XamlPanel inside a control defined in XAML by writing something like</p>
<pre>&lt;OURNAMESPACE:SecondXamlPanel x:Name="MyInstance"&gt;</pre>
<p>you&#8217;re free to make XamlPanel and it&#8217;s children configurable via the DependencyObject mechanisms.  The one thing that you lose is public access to the graphical element inside the StackPanelInnards:  many developers would think that this increase in encapsulation is a good thing,  but it may involve a change in the way you do things.</p>
<h2>Related articles</h2>
<p>The community at <a href="http://silverlight.net/">silverlight.net</a> has pointed me to a few other articles about XAML,  inheritance and configuring Custom XAML controls.</p>
<p>In a lavishly illustrated blog entry,  Amyo Kabir explains <a href="http://amyotech.spaces.live.com/blog/cns!4B03AA8222DC3C5E!226.entry">how to make a XAML-defined control inherit from a user-defined base class</a>.  It&#8217;s the converse of what I&#8217;m doing in this article,  but it&#8217;s also a powerful technique:  I&#8217;m using it right now to implement a number of Steps in a Wizard.</p>
<p>Note that Silverlight has mechanisms for creating <a href="http://www.silverlightshow.net/items/Creating-a-Silverlight-Custom-Control-The-Basics.aspx">Custom Controls</a>:  these are controls that use the DependencyObject mechanism to be configurable via XAML files that include them.  If you&#8217;re interested in customizing individual controls rather than customizing subclasses,  this is an option worth exploring.</p>
<h2>Conclusion</h2>
<p>XAML is a great system for configuring complex objects,  but you can&#8217;t inherit from a Silverlight class defined in XAML.  By using a containment relation instead of an inheritance relation,  we can push the XAML-configured class outside of our inheritance hierarchy,  allowing the container class to participate as we desire.  This way we can have both visual UI generation and the software engineering benefits of inheritance.</p>
<div class="zemanta-pixie" style="margin-top: 10px; height: 15px;"><a class="zemanta-pixie-a" title="Zemified by Zemanta" href="http://reblog.zemanta.com/zemified/1309efe8-1c65-4657-8a29-aea199856afb/"><img class="zemanta-pixie-img" style="border: medium none ; float: right;" src="http://img.zemanta.com/reblog_e.png?x-id=1309efe8-1c65-4657-8a29-aea199856afb" alt="Reblog this post [with Zemanta]" /></a></div>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2009/02/10/subverting-xaml-how-to-inherit-from-silverlight-user-controls/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Manipulate HTML Forms With Silverlight 2</title>
		<link>http://gen5.info/q/2009/01/21/manipulate-html-forms-with-silverlight-2/</link>
		<comments>http://gen5.info/q/2009/01/21/manipulate-html-forms-with-silverlight-2/#comments</comments>
		<pubDate>Wed, 21 Jan 2009 22:17:30 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://gen5.info/q/?p=164</guid>
		<description><![CDATA[Introduction Lately I&#8217;ve been working on a web application based on Silverlight 2.  The application uses a traditional web login system based on a cryptographically signed cookie.  In early development,  users logged in on an HTML page,  which would load a Silverlight application on successful login.  Users who didn&#8217;t have Silverlight installed would be asked [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.flickr.com/photos/skippy/11865024/"><img class="size-full wp-image-161" style="float: right; margin: 5px" title="11865024_af61ae2358_m" src="http://gen5.info/q/wp-content/uploads/2009/01/11865024_af61ae2358_m.jpg" border="0" alt="Remote Control" width="180" height="240" /></a></p>
<h2>Introduction</h2>
<p>Lately I&#8217;ve been working on a web application based on Silverlight 2.  The application uses a traditional web login system based on a <a href="http://www.google.com/url?sa=t&amp;source=web&amp;ct=res&amp;cd=1&amp;url=http%3A%2F%2Fpdos.csail.mit.edu%2Fpapers%2Fwebauth%3Asec10.pdf&amp;ei=a493SdXUCuPetgfhhPmgBg&amp;usg=AFQjCNFt9lqlfx_ALls4BBI9IPax51wBpw&amp;sig2=QsCk70fmt9nJASYWb4Dp0g">cryptographically signed cookie</a>.  In early development,  users logged in on an HTML page,  which would load a Silverlight application on successful login.  Users who didn&#8217;t have Silverlight installed would be asked to install it after logging in,  rather than before.</p>
<p>Although it&#8217;s (sometimes) possible to determine what plug-ins a user has installed using Javascript,  the methods are dependent on the specific browser and the plug-ins.  We went for a simple and effective method:  make the login form a Silverlight application,  so that users would be prompted to install Silverlight before logging in.</p>
<p>Our solutionn  was to make the Silverlight application a drop-in replacement for the original HTML form.  The Silverlight application controls a hidden HTML form:  when a user hits the &#8220;Log In&#8221; buttonin the Silverlight application,  the application inserts the appropriate information into the HTML form and submits it.  This article describes the technique in detail.<span id="more-164"></span></p>
<h2>The HTML Form</h2>
<p>The HTML form is straightforward &#8212; the main thing that&#8217;s funky about it is that all of the controls are invisible,  since we don&#8217;t want users to see them or interact with them directly:</p>
<pre>[01] &lt;form id="loginForm" method="post" action=""&gt;
[02]     &lt;div class="loginError" id="loginError"&gt;
[03]        &lt;%= Server.HtmlEncode(errorCondition) %&gt;
[04]     &lt;/div&gt;
[05]     &lt;input type="hidden" name="username" id="usernameField"
[06]        value="&lt;%= Server.HtmlEncode(username) %&gt;" /&gt;
[07]     &lt;input type="hidden" name="password" id="passwordField"  /&gt;
[08] &lt;/form&gt;</pre>
<p>The CSS file for the form contains the following directive:</p>
<pre>[09] .loginError { display:none }</pre>
<p>to prevent the error message from being visible on the HTML page.</p>
<h2>Executing Javascript In Silverlight 2</h2>
<p>A Silverlight 2 application can execute Javascript using the <em>HtmlPage.Window.Eval() </em>method;  HtmlPage.Window is static,  so you can use it anywhere,  so long as you&#8217;re running in the UI thread.  Our simple application doesn&#8217;t do communication and doesn&#8217;t launch new threads,  so we don&#8217;t need to worry about threads.  We add a simple wrapper method to help the rest of the code flow off the tips of our fingers</p>
<pre>[10] using System.Windows.Browser
[11] ...
[12] namespace MyApplication {
[13] public partial class Page : UserControl {
[14]      ...
[15]        Object JsEval(string jsCode) {
[16]            return HtmlPage.Window.Eval(jsCode);
[17]        }</pre>
<p>Note that Visual Studio doesn&#8217;t put the <em>using</em> in by default,  so you&#8217;ll need to add it.  The application is really simple,   with just two event handlers and a little XAML to define the interface,  so it&#8217;s all in a single class,  the Page.xaml and Page.xaml.cs files created when I made the project in VIsual Studio.</p>
<p>Note that JsEval returns an Object,  so you can look at the return value of a javascript evaluation.  Numbers are returned as doubles and strings are returned as strings,  which can be quite useful.  References to HTML elements are returned as instances of the HtmlElement class.  HtmlElement has some useful methods,  such as GetAttribute() and SetAttribute(),  but I&#8217;ve found that I get more reliable results by writing snippets of Javascript code.</p>
<h2>Finding HTML Elements</h2>
<p>One practical is problem is how to find the HTML Elements on the page that you&#8217;d like to work with.  I&#8217;ve been spoiled by the $() function in Prototype and JQuery,  so I like to access HTML elements by id.  There isn&#8217;t a standard method to do this in all browser,  so I slipped the following snippet of Javascript into the document:</p>
<pre>[18]    function returnObjById(id) {
[19]        if (document.getElementById)
[20]            var returnVar = document.getElementById(id);
[21]        else if (document.all)
[22]            var returnVar = document.all[id];
[23]        else if (document.layers)
[24]            var returnVar = document.layers[id];
[25]        return returnVar;
[26]    }</pre>
<p>(code snippet courtesy of <a href="http://www.netlobo.com/javascript_get_element_id.html">NetLobo</a>)</p>
<p>I wrote a few convenience methods in C# inside my Page class:</p>
<pre>[27]   String IdFetchScript(string elementId) {
[28]        return String.Format("returnObjById('{0}')", elementId);
[29]   }
[30]
[31]   HtmlElement FetchHtmlElement(string elementId) {
[32]        return (HtmlElement)JsEval(IdFetchScript(elementId));
[33]   }</pre>
<h2>Manipulating HTML Elements</h2>
<p>At this point you can do anything that can be done in Javascript.  That said,  all I need is a few methods to get information in and out of the form:</p>
<pre>[34]       string GetTextInElement(string elementId) {
[35]           HtmlElement e = FetchHtmlElement(elementId);
[36]           if (e == null)
[37]               return "";
[38]
[39]           return (string)JsEval(IdFetchScript(elementId) + ".innerHTML");
[40]       }
[41]
[42]       void Set(string fieldId, string value) {
[43]            HtmlElement e = FetchHtmlElement(fieldId);
[44]            e.SetAttribute("value", value);
[45]       }
[46]
[47]       string GetFormFieldValue(string fieldId) {
[48]            return (string) JsEval(IdFetchScript(fieldId)+".value");
[49]       }
[50]
[51]       void SubmitForm(string formId) {
[52]            JsEval(IdFetchScript(formId) + ".submit()");
[53]       }</pre>
<p>Isolating the Javascript into a set of helper methods helps make the code maintainable:  these methods are usable by a C#er who isn&#8217;t a Javascript expert &#8212; if we discover problems with cross-browser compatibility,  we can fix them in a single place.</p>
<h2>Putting it all together</h2>
<p>A little bit of code in the constructor loads form information into the application:</p>
<pre>[54]        public Page() {
[55]            ...
[56]            LoginButton.Click += LoginButton_Click;
[57]            UsernameInput.Text = GetFormFieldValue("usernameField");
[58]            ErrorMessage.Text = GetTextInElement("loginError");
[59]         }</pre>
<p>The LoginButton_Click event handler populates the invisible HTML form and submits it:</p>
<pre>[60]      void LoginButton_Click(object sender, RoutedEventArgs e) {
[61]           SetFormFieldValue("usernameField", UsernameInput.Text);
[62]           SetFormFieldValue("passwordField", PasswordInput.Password);
[63]           SubmitForm("loginForm");</pre>
<pre>[64]       }</pre>
<h2>Conclusion</h2>
<p>Although Silverlight 2 is capable of direct http communication with a web server,  sometimes it&#8217;s convenient for a Silverlight application to directly manipulate HTML forms.   This article presents sample source code that simplifies that task.</p>
<p><strong>P.S.</strong> A commenter on the Silverlight.net forums pointed me to <a href="http://timheuer.com/blog/archive/2008/03/09/calling-javascript-functions-from-silverlight-2.aspx">another article by Tim Heuer</a> that describes alternate methods for manipulating the DOM and calling Javascript functions.</p>
<p><small>(Thanks <a href="http://www.flickr.com/photos/skippy/">skippy</a> for the <a href="http://www.flickr.com/photos/skippy/11865024/">remote control image.</a>)</small></p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fgen5.info%2fq%2f2009%2f01%2f21%2fmanipulate-html-forms-with-silverlight-2%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fgen5.info%2fq%2f2009%2f01%2f21%2fmanipulate-html-forms-with-silverlight-2%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2009/01/21/manipulate-html-forms-with-silverlight-2/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>require(),  require_once() and Dynamic Autoloading in PHP</title>
		<link>http://gen5.info/q/2009/01/09/an-awesome-autoloader-for-php/</link>
		<comments>http://gen5.info/q/2009/01/09/an-awesome-autoloader-for-php/#comments</comments>
		<pubDate>Fri, 09 Jan 2009 21:19:16 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[r]]></category>

		<guid isPermaLink="false">http://gen5.info/q/?p=137</guid>
		<description><![CDATA[Introduction I program in PHP a lot,  but I&#8217;ve avoided using autoloaders,  except when I&#8217;ve been working in frameworks,  such as symfony,   that include an autoloader.  Last month I started working on a system that&#8217;s designed to be part of a software product line:  many scripts,  for instance,  are going to need to deserialize objects [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>I program in PHP a lot,  but I&#8217;ve avoided using autoloaders,  except when I&#8217;ve been working in frameworks,  such as symfony,   that include an autoloader.  Last month I started working on a system that&#8217;s designed to be part of a software product line:  many scripts,  for instance,  are going to need to deserialize objects that didn&#8217;t exist when the script was written:  autoloading went from a convenience to a necessity.</p>
<p>The majority of autoloaders use a fixed mapping between class names and PHP file names.  Although that&#8217;s fine if you obey a strict &#8220;one class,  one file&#8221; policy,  that&#8217;s a policy that I don&#8217;t follow 100% of the time.  An additional problem is that today&#8217;s PHP applications often reuse code from multiple frameworks and libraries that use different naming conventions:  often applications end up registering multiple autoloaders.  I was looking for an autoloader that &#8220;just works&#8221; with a minimum of convention and configuration &#8212; and I found that in a <a href="http://ajbrown.org/blog/2008/12/02/an-auto-loader-using-php-tokenizer.html">recent autoloader developed by A.J. Brown</a>.<span id="more-137"></span></p>
<p>After presenting the way that I integrated Brown&#8217;s autoloader into my in-house frameowrk,  this article considering the growing controversy over require(),  require_once() and autoloading performance:  to make a long story short,  people are experiencing very different results in different environments,  and the growing popularity of autoloading is going to lead to changes in PHP and the ecosystem around it.</p>
<h2>History:  PHP 4 And The Bad Old Days</h2>
<p>In the past,  PHP programmers have included class definitions in their programs with the following four built-in functions:</p>
<ul>
<li><em>include</em></li>
<li><em>require</em></li>
<li><em>include_once</em></li>
<li><em>require_once</em></li>
</ul>
<p>The difference between the <em>include</em> and <em>require</em> functions is that execution of a program will continue if a call to <em>include</em> fails and will result in an error if a call to <em>require</em> fails.  <em>require_</em> and <em>require_once</em> are reccomended for general use,  since you&#8217;d probably rather have an application fail if libraries are missing rather than barrel on with unpredictable results.  (Particularly if the missing library is responsible for authentication.)</p>
<p>If you write</p>
<pre>01 require "filename.php";</pre>
<p>PHP will scan the PHP include_path for a directory that contains a file called &#8220;filename.php&#8221;;  it then executes the content of &#8220;filename.php&#8221; right where the function is called.  You can do some pretty funky things this way,  for instance,  you can write</p>
<pre>02 for (int i=0;i&lt;10;$i++) {
03    require "template-$i.php";
04 }</pre>
<p>to cause the sequential execution of a  namset of PHP files named &#8220;template-0.php&#8221; through &#8220;template-9.php.&#8221;  A <em>required</em> file has access to local variables in the scope that require is called,  so require is particularly useful for web templating and situations that require dynamic dispatch (when you compute the filename.)  A cool,  but slightly obscure feature,  is that an included file can return a value.  If an source file,  say &#8220;compute-value.php&#8221; uses the return statement,</p>
<pre>05 return $some_value;</pre>
<p>the value $some_value will be return by require:</p>
<pre>06 $value=require "compute-value.php";</pre>
<p>These features can be used to create an MVC-like framework where views and controllers are implemented as source files rather than objects.</p>
<p>require isn&#8217;t so appropriate,  however,  when you&#8217;re requiring a file that contains class definitions.  Imagine we have a hiearchy of classes like Entity -&gt; Picture -&gt; PictureOfACar,PictureOfAnAnimal.  It&#8217;s quite tempting for PictureofACar.php and PictureofAnAnimal.php to both</p>
<pre>07 require "Picture.php";</pre>
<p>this works fine if an application only uses PictureOfACar.php and requires it once by writing</p>
<pre>08 require "PictureOfACar.php";</pre>
<p>It fails,  however,  if an application requires both PictureOfACar and PictureOfAnAnimal since PHP only allows a class to be defined once.</p>
<p><em>require_once</em> neatly solves this problem by keeping a list of files that have been required and doing nothing if a file has already been required.  You can use require_once in any place where you&#8217;d like to guarantee that a class is available,  and expect that things &#8220;just work&#8221;</p>
<h2>__autoload</h2>
<p>Well,  things don&#8217;t always &#8220;just work&#8221;.  Although large PHP applications can be maintained with require_once,  it becomes an increasing burden to keep track of require files as applications get larger.  require_once also breaks down once frameworks start to dynamically instantiate classes that are specified in configuration files.  The developers of PHP found a creative solution in the __autoload function,  a &#8220;magic&#8221; function that you can define.  __autoload($class_name) gets called whenever a PHP references an undefined class.  A very simple __autoload implementation can work well:  for instance,  the PHP manual page for __autoload has the following code snippet:</p>
<pre>09 function _autoload($class_name) {
10    require_once $class_name . '.php';
11 }</pre>
<p>If you write</p>
<pre>12 $instance=new MyUndefinedClass();</pre>
<p>this autoloader will search the PHP include path for &#8220;MyUndefinedClass.php.&#8221;  (A real autoloader should be a little more complex than this:  the above autoloader could be persuaded to load from an unsafe filename if user input is used to instantiate a class dynamically,  i.e.</p>
<pre>13 $instance=new $derived_class_name();</pre>
<h2>Static autoloading and autoloader proliferation</h2>
<p>Unlike Java,  PHP does not have a standard to relate source file names with class names.  Some PHP developers imitate the Java convention to define one file per class and name their files something like</p>
<p>ClassName.php,  or<br />
ClassName.class.php</p>
<p>A typical project that uses code from several sources will probably have sections that are written with different conventions  For instance,  the Zend framework turns &#8220;_&#8221; into &#8220;/&#8221; when it creates paths,  so the definition of &#8220;Zend_Loader&#8221; would be found underneath &#8220;Zend/Loader.php.&#8221;</p>
<p>A single autoloader could try a few different conventions,  but the answer that&#8217;s become most widespread is for each PHP framework or library to contain it&#8217;s own autoloader.  PHP 5.2 introduced the spl_register_autoload() function to replace __autoload().  spl_register_autoload() allows us to register multiple autoloaders,  instead of just one.  This is ugly,  but it works.</p>
<h2>One Class Per File?</h2>
<p>A final critique of static autoloading is that it&#8217;s not universally held that &#8220;one class one file&#8221; is the best practice for PHP development.  One of the advantages of OO scripting languages such as PHP and Python is that you can start with a simple procedural script and gradually evolve it into an OO program by gradual refactoring.  A convention that requires to developers to create a new file for each class tends to:</p>
<ol>
<li>Discourage developers from creating classes</li>
<li>Discourage developers from renaming classes</li>
<li>Discourage developers from deleting classes</li>
</ol>
<p>These can cumulatively lead programmers to make decisions based on what&#8217;s convenient to do with their development tools,  not based on what&#8217;s good for the software in the long term.  These considerations need to be balanced against:</p>
<ol>
<li>The ease of finding classes when they are organized &#8220;once class per file&#8221;,</li>
<li>The difficulty of navigating huge source code files that contain a large number of classes,  and</li>
<li>Toolset simplification and support.</li>
</ol>
<p>The last of these is particularly important when we compare PHP with Java.  Since the Java compiler enforces a particular convention,  that convention is supported by Java IDE&#8217;s.  The problems that I mention above are greatly reduced if you use an IDE such as Eclipse,  which is smart enough to rename files when you rename a class.  PHP developers don&#8217;t benefit from IDEs that are so advanced &#8212; it&#8217;s much more difficult for IDE&#8217;s to understand a dynamic language.  Java also supports inner classes,  which allow captive classes (that are only accessed from within an enclosing class) to be defined inside the same file as the enclosing class.  Forcing captive classes to be defined in separate files can cause a bewildering number of files to appear,  which,  in turn,  can discourage developers from using captive classes &#8212; and that can lead to big mistakes.</p>
<h2>Dynamic Autoloading</h2>
<p><a href="http://ajbrown.org/blog/">A. J. Brown</a> has developed an <a href="http://ajbrown.org/blog/2008/12/02/an-auto-loader-using-php-tokenizer.html">autoloader</a> that uses PHP&#8217;s tokenizer() to search a directory full of PHP files,  search the files for classes,  and create a mapping from class names to php source files.  <em>tokenizer() </em>is a remarkable metaprogramming facility that makes it easy to write PHP programs that interpret PHP source.  In 298 lines of code,  Brown defines three classes.  To make his autoloader fit into my in-house framework,  I copied his classes into two files:</p>
<ul>
<li>lib/nails_core/autoloader.php: ClassFileMap, ClassFileMapAutoloader</li>
<li>lib/nails_core/autoloader_initialize.php: ClassFileMapFactory</li>
</ul>
<p>I&#8217;m concerned about the overhead of repeatedly traversing PHP library directories and parsing the files,  so I run the following program to create the <em>ClassFileMap</em>,  serialize it,  and store it in a file:</p>
<pre><span style="text-decoration: underline;"><strong>bin/create_class_map.php:</strong></span>
14 &lt;?php
15
16 $SUPRESS_AUTOLOAD=true;
17 require_once(dirname(__FILE__)."/../_config.php");
18 require_once "nails_core/autoloader_initialize.php";
19 $lib_class_map = ClassFileMapFactory::generate($APP_BASE."/lib");
20 $_autoloader = new ClassFileMapAutoloader();
21 $_autoloader-&gt;addClassFileMap($lib_class_map);
22 $data=serialize($_autoloader);
23 file_put_contents("$APP_BASE/var/classmap.ser",$data);</pre>
<p>Note that I&#8217;m serializing the <em>ClassFileMapAutoloader </em>rather than the <em>ClassFileMap</em>,  since I&#8217;d like to have the option of specifying more than one search directory.  To follow the &#8220;convention over configuration&#8221; philosophy,  a future version will probable traverse all of the directories in the <em>php_include_path</em>.</p>
<p>All of the PHP pages,  controllers and command-line scripts in my framework have the line</p>
<pre>24 require_once(dirname(__FILE__)."/../_config.php");</pre>
<p>which includes a file that is responsible for configuring the application and the PHP environment.   I added a bit of code to the _config.php to support the autoloader:</p>
<pre><span style="text-decoration: underline;"><strong>_config.php:</strong></span>
25 &lt;?php
26 $APP_BASE = "/where/app/is/in/the/filesystem";
   ...
27 if (!isset($SUPPRESS_AUTOLOADER)) {
28    require_once "nails_core/autoloader.php";
29    $_autoloader=unserialize(file_get_contents($APP_BASE."/var/classmap.ser"));
30    $_autoloader-&gt;registerAutoload();
31 };</pre>
<p>Pretty simple.</p>
<h2>Autoloading And Performance</h2>
<p>Although there&#8217;s plenty of controversy about issues of software maintainability,  I&#8217;ve learned the hard way that it&#8217;s hard to make blanket statements about performance &#8212; results can differ based on your workload and the exact environment you&#8217;re working in.  Although Brown makes the statement that &#8220;We do add a slight overhead to the application,&#8221;  many programmers are discovering that autoloading improves performance over require_once:</p>
<p><a href="http://framework.zend.com/wiki/display/ZFDEV/Performance+-+Requiring+the+Autoloader">Zend_Loader Performance Analysis</a><br />
<a href="http://www.mikebrittain.com/blog/2008/03/27/autoloading-php-classes-to-reduce-cpu-usage/">Autoloading Classes To Reduce CPU Usage</a></p>
<p>There seem to be two issues here:  first of all,  most systems that use require_once are going to err on the side of including more files than they need rather than fewer &#8212; it&#8217;s better to make a system slower and bloated than to make it incorrect.  A system that uses autoloading will spend less time loading classes,  and,  just as important,  less memory storing them.  Second,  PHP programmers appear to be experience variable results with require() and require_once():</p>
<p><a href="http://www.techyouruniverse.com/software/php-performance-tip-require-versus-require_once">Wikia Developer Finds require_once() Slower Than require()</a><br />
<a href="http://arin.me/php/php-require-vs-include-vs-require_once-vs-include_once-performance-test">Another Developer Finds Little Difference</a><br />
<a href="http://article.gmane.org/gmane.comp.php.pear.devel/43593">Yet Another Developer Finds It Depends On His Cache Configuration</a><br />
<a href="http://www.nabble.com/require_once-performance-issue-in-ZF-td19218102.html">Rumor has it,  PHP 5.3 improves require_once() performance</a></p>
<p>One major issues is that require_once() calls the realpath() C function,  which in turn calls the lstat() system call.  The cost of system calls can vary quite radically on different operating systems and even different filesystems.  The use of an opcode cache such as XCache or APC can also change the situation.</p>
<p>It appears that current opcode caches (as of Jan 2008) don&#8217;t efficiently support autoloading:<br />
<a href="http://blog.digitalstruct.com/2007/12/23/zend-framework-performance-zend_loader/"><br />
Mike Willbanks Experience Slowdown With Zend_Loader</a><br />
<a href="http://pooteeweet.org/blog/538/">APC Developer States That Autoloading is Incompatible With Cacheing</a><br />
<a href="http://forum.lighttpd.net/topic/17500">Rambling Discussion of the state of autoloading with XCache<br />
</a></p>
<p>the issue is that they don&#8217;t,  at compile time,  know what files are going be required by the application.  Opcode caches also reduce the overhead of loading superfluous classes,  so they don&#8217;t get the benefits experienced with plain PHP.</p>
<p>It all reminds me of the situation with <em>synchronized</em> in Java.  In early implementations of Java,  <em>synchronized</em> method calls had an execution time nearly ten times longer than ordinary message calls.  Many developers designed systems (such as the Swing windowing toolkit) around this performance problem.  Modern VM&#8217;s have greatly accelerated the synchronization mechanism and can often optimize superfluous synchronizations away &#8212; so the performance advice of a decade ago is bunk.</p>
<p>Language such as Java are able to treat individual classes as compilation units:  and I&#8217;d imagine that,  with certain restrictions,  a PHP bytecode cache should be able to do just that.  This may involve some changes in the implementation of PHP.</p>
<h2>Conclusion</h2>
<p>Autoloading is an increasingly popular practice among PHP developers.  Autoloading improves development productivity in two ways:</p>
<ol>
<li>It frees developers from thinking about loading the source files needed by an application,  and</li>
<li>It enables dynamic dispatch,  situations where a script doesn&#8217;t know about all the classes it will interact with when it&#8217;s written</li>
</ol>
<p>Since PHP allows developers to create their own autoloaders,  a number of autoloaders exist.  Many frameworks,  such as the Zend Framework,  symfony,  and CodeIgniter,  come with autoloaders &#8212; as a result,  some PHP applications might contain more than one autoloader.  Most autoloaders require that classes be stored in files with specific names,  but Brown&#8217;s autoloader can scan directory trees to automatically  locate PHP classes and map them to filenames.  Eliminating the need for both convention and configuration,  I think it&#8217;s a significant advance:  in many cases I think it could replace the proliferation of autoloaders that we&#8217;re seeing today.</p>
<p>You&#8217;ll hear very different stories about the performance of autoload,  require_once() and other class loading mechanisms from different people.  The precise workload,  operating system,  PHP version,  and the use of an opcode cache appear to be important factors.  Widespread use of autoloading will probably result in optimization of autoloading throughout the PHP ecosystem.</p>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2009/01/09/an-awesome-autoloader-for-php/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>What do you do when you&#8217;ve caught an exception?</title>
		<link>http://gen5.info/q/2008/08/27/what-do-you-do-when-youve-caught-an-exception/</link>
		<comments>http://gen5.info/q/2008/08/27/what-do-you-do-when-youve-caught-an-exception/#comments</comments>
		<pubDate>Wed, 27 Aug 2008 15:19:03 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[Dot Net]]></category>
		<category><![CDATA[Exceptions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://gen5.info/q/?p=80</guid>
		<description><![CDATA[Abort, Retry, Ignore This article is a follow up to &#8220;Don&#8217;t Catch Exceptions&#8220;, which advocates that exceptions should (in general) be passed up to a &#8220;unit of work&#8221;, that is, a fairly coarse-grained activity which can reasonably be failed, retried or ignored. A unit of work could be: an entire program, for a command-line script, [...]]]></description>
			<content:encoded><![CDATA[<h2>Abort, Retry, Ignore</h2>
<p>This article is a follow up to &#8220;<a href="http://gen5.info/q/2008/07/31/stop-catching-exceptions/">Don&#8217;t Catch Exceptions</a>&#8220;, which advocates that exceptions should (in general) be passed up to a &#8220;unit of work&#8221;, that is, a fairly coarse-grained activity which can reasonably be failed, retried or ignored. A unit of work could be:</p>
<ul>
<li>an entire program,  for a command-line script,</li>
<li>a single web request in a web application,</li>
<li>the delivery of an e-mail message</li>
<li>the handling of a single input record in a batch loading application,</li>
<li>rendering a single frame in a media player or a video game,  or</li>
<li>an event handler in a GUI program</li>
</ul>
<p>The code around the unit of work may look something like</p>
<pre>[01] try {
[02]   DoUnitOfWork()
[03] } catch(Exception e) {
[04]    ... examine exception and decide what to do ...
[05] }</pre>
<p>For the most part,  the code inside <em>DoUnitOfWork()</em> and the functions it calls tries to <a href="http://gen5.info/q/2008/07/31/stop-catching-exceptions/">throw exceptions upward rather than catch them.</a></p>
<p>To handle errors correctly,  you need to answer a few questions,  such as</p>
<ul>
<li>Was this error caused by a corrupted application state?</li>
<li>Did this error cause the application state to be corrupted?</li>
<li>Was this error caused by invalid input?</li>
<li>What do we tell the user,  the developers and the system administrator?</li>
<li>Could this operation succeed if it was retried?</li>
<li>Is there something else we could do?</li>
</ul>
<p>Although it&#8217;s good to depend on existing exception hierarchies (at least you won&#8217;t introduce new problems), the way that exceptions are defined and thrown inside the work unit should help the code on line [04] make a decision about what to do &#8212; such practices are the subject of a future article, which subscribers to our <a href="http://feeds.feedburner.com/Generation5">RSS feed</a> will be the first to read.</p>
<p><span id="more-80"></span></p>
<h2>The cause and effect of errors</h2>
<p>There are a certain range of error conditions that are predictable,  where it&#8217;s possible to detect the error and implement the correct response.  As an application becomes more complex,  the number of possible errors explodes,  and it becomes impossible or unacceptably expensive to implement explicit handling of every condition.</p>
<p>What do do about unanticipated errors is a controversial topic.  Two extreme positions are: (i) an unexpected error could be a sign that the application is corrupted, so that the <a href="http://blogs.msdn.com/larryosterman/archive/2008/05/01/resilience-is-not-necessarily-a-good-thing.aspx">application should be shut down</a>, and (ii) systems should <a href="http://blogs.msdn.com/eric_brechner/archive/2008/05/01/crash-dummies-resilience.aspx">bend but not break</a>: we should be optimistic and hope for the best.  Ultimately, there&#8217;s a contradiction between <em>integrity</em> and <em>availability</em>, and different systems make different choices.  The ecosystem around Microsoft Windows,  where people predominantly develop desktop applications,   is inclined to give up the ghost when things go wrong &#8212; better to show a &#8220;blue screen of death&#8221; than to let the unpredictable happen.  In the Unix ecosystem,  more centered around server applications and custom scripts,  the tendency is to soldier on in the face of adversity.</p>
<p>What&#8217;s at stake?</p>
<p>Desktop applications tend to fail when unexpected errors happen:  users learn to save frequently.  Some of the best applications,  such as GNU emacs and Microsoft Word,  keep a running log of changes to minimize work lost to application and system crashes.  Users accept the situation.</p>
<p>On the other hand,   it&#8217;s unreasonable for a server application that serves hundreds or millions of users to shut down on account of a cosmic ray.  Embedded systems,  in particular,  function in a world where failure is frequent and the effects must be minimized.   As we&#8217;ll see later,  it would be a real bummer if the Engine Control Unit in your car left you stranded home because your oxygen sensor quit working.</p>
<p>The following diagram illustrates the environment of a work unit in a typical application:  (although this application accesses network resources,  we&#8217;re not thinking of it as a distributed application.  We&#8217;re responsible for the correct behavior of the application running in a single address space,  not about the correct behavior of a process swarm.)</p>
<p><a href="http://gen5.info/q/wp-content/uploads/2008/08/datadomains1.png"><img class="alignnone size-full wp-image-85" title="datadomains1" src="http://gen5.info/q/wp-content/uploads/2008/08/datadomains1.png" alt="" /></a></p>
<p>The Input to the work unit is a potential source of trouble.  The input could be invalid,  or it could trigger a bug in the work unit or elsewhere in the system (the &#8220;system&#8221; encompasses everything in the diagram)   Even if the input is valid,  it could contain a reference to a corrupted resource,  elsewhere in the system.  A corrupted resource could be a damaged data structure (such as a colored box in a database),  or an otherwise malfunctioning part of the system (a crashed server or router on the network.)</p>
<p>Data structures in the work unit itself are the least problematic,  for purposes of error handling,  because they don&#8217;t outlive the work unit and don&#8217;t have any impact on future work units.</p>
<p>Static application data,  on the other hand,  persists after the work unit ends,  and this has two possible consequences:</p>
<ol>
<li>The current work unit can fail because a previous work unit caused a resource to be corrupted, and</li>
<li>The current work unit can corrupt a resource,  causing a future work unit to fail</li>
</ol>
<p>Osterman&#8217;s argument that <a href="http://blogs.msdn.com/larryosterman/archive/2008/05/01/resilience-is-not-necessarily-a-good-thing.aspx">applications should crash on errors</a> is based on this reality:  an unanticipated failure is a sign that the application is in an unknown (and possibly bad) state,  and can&#8217;t be trusted to be reliable in the future.  Stopping the application and restarting it clears out the static state,  eliminating resource corruption.</p>
<p>Rebooting the application,  however,  might not free up corrupted resources inside the operating system.  Both desktop and server applications suffer from operating system errors from time to time,  and often can get immediate relief by rebooting the whole computer.</p>
<p>The &#8220;reboot&#8221; strategy runs out of steam when we cross the line from in-RAM state to persistent state,  state that&#8217;s stored on disks,  or stored elsewhere on the network.  Once resources in the persistent world are corrupted,  they need to be (i) lived with,  or repaired by (ii) manual or (iii) automatic action.</p>
<p>In either world,  a corrupted resource can have either a narrow (blue) or wide (orange) effect on the application.  For instance,  the user account record of an individual user could be damaged,  which prevents that user from logging in.  That&#8217;s bad,  but it would hardly be catastrophic for a system that has 100,000 users.   It&#8217;s best to &#8216;ignore&#8217; this error,  because a system-wide &#8216;abort&#8217; would deny service to 99,999 other users;  the problem can be corrected when the user complains,  or when the problem is otherwise detected by the system administrator.</p>
<p>If,  on the other hand,  the cryptographic signing key that controls the authentication process were lost,  <strong>nobody</strong> would be able to log in:  that&#8217;s quite a problem.  It&#8217;s kind of the problem that will be noticed,  however,  so aborting at the work unit level (authenticated request) is enough to protect the integrity of the system while the administrators repair the problem.</p>
<p>Problems can happen at an intermediate scope as well.  For instance,  if the system has damage to a message file for Italian users,  people who use the system in the Italian language could be locked out.  If Italian speakers are 10% of the users,  it&#8217;s best to keep the system running for others while you correct the problem.</p>
<h2>Repair</h2>
<p>There are several tools for dealing with corruption in persistent data stores. In a one-of-a-kind business system, a DBA may need to intervene occasionally to repair corruption. More common events can be handled by running scripts which detect and repair corruption, much like the <em>fsck</em> command in Unix or the <em>chkdsk</em> command in Windows. Corruption in the metadata of a filesystem can, potentially, cause a sequence of events which leads to massive data loss, so UNIX systems have historically run the <em>fsck</em> command on filesystems whenever the filesystem is in a questionable state (such as after a system crash or power failure.) The time do do an fsck has become an increasing burden as disks have gotten larger, so modern UNIX systems use journaling filesystems that protect  filesystem metadata with <em>transactional semantics</em>.</p>
<h2>Release and Rollback</h2>
<p>One role of an exception handler for a unit of work is to take steps to prevent corruption. This involves the release of resources, putting data in a safe state, and, when possible, the rollback of transactions.</p>
<p>Although many kinds of persistent store support transactions, and many in-memory data structures can support transactions, the most common transactional store that people use is the relational database. Although transactions don&#8217;t protect the database from all programming errors, they can ensure that neither expected or unexpected exceptions will cause partially-completed work to remain in the database.</p>
<p>A classic example in pseudo code is the following:</p>
<pre>[06] function TransferMoney(fromAccount,toAccount,amount) {
[07]   try {
[08]      BeginTransaction();
[09]      ChangeBalance(toAccount,amount);
[10]      ... something throws exception here ...
[11]      ChangeBalance(fromAccount,-amount);
[12]      CommitTransaction();
[13]   } catch(Exception e) {
[14]      RollbackTransaction();
[15]   }
[16] }</pre>
<p>In this (simplified) example, we&#8217;re transferring money from one bank account to another. Potentially an exception thrown at line [05] could be serious, since it would cause money to appear in <em>toAccount</em> without it being removed from <em>fromAccount</em>. It&#8217;s bad enough if this happens by accident, but a clever cracker who finds a way to cause an exception at line [05] has discovered a way to steal money from the bank.</p>
<p>Fortunately we&#8217;re doing this <span style="text-decoration: underline;">financial</span> transaction inside a <span style="text-decoration: underline;">database</span> transaction.  Everything done after <em>BeginTransaction()</em> is provisional:  it doesn&#8217;t actually appear in the database until <em>CommitTransaction()</em> is called.  When an exception happens,  we call <em>RollbackTransaction()</em>,  which makes it as if the first <em>ChangeBalance()</em> had never been called.</p>
<p>As mentioned in the &#8220;<a href="http://gen5.info/q/2008/07/31/stop-catching-exceptions/">Don&#8217;t Catch Exceptions</a>&#8221; article, it often makes sense to do release, rollback and repairing operations in a <em>finally</em> clause rather than the unit-of-work <em>catch</em> clause because it lets an individual subsystem take care of itself &#8212; this promotes encapsulation. However, in applications that use databases transactionally, it often makes sense to push transaction management out the the work unit.</p>
<p>Why? Complex database operations are often composed out of simpler database operations that, themselves, should be done transactionally. To take an example, imagine that somebody is opening a new account and funding it from an existing account:</p>
<pre>[17] function OpenAndFundNewAccount(accountInformation,oldAccount,amount) {
[18]    if (amount&lt;MinimumAmount) {
[19]       throw new InvalidInputException(
[20]          "Attempted To Create Account With Balance Below Minimum"
[21]       );
[22]    }
[23]    newAccount=CreateNewAccountRecords(accountInformation);
[24]    TransferMoney(oldAccount,newAccount,amount);|
[25] }</pre>
<p>It&#8217;s important that the <em>TransferMoney</em> operation be done transactionally,  but it&#8217;s also important that the whole <em>OpenAndFundNewAccount</em> operation be done transactionally too,  because we don&#8217;t want an account in the system to start with a zero balance.</p>
<p>A straightforward answer to this problem is to always do banking operations inside a unit of work, and to begin, commit and roll back transactions at the work unit level:</p>
<pre>[26] AtmOutput ProcessAtmRequest(AtmInput in) {
[27]    try {
[28]       BeginTransaction();
[29]       BankingOperation op=AtmInput.ParseOperation();
[30]       var out=op.Execute();
[31]       var atmOut=AtmOutput.Encode(out);
[32]       CommitTransaction();
[33]       return atmOut;
[34]    }
[35]    catch(Exception e) {
[36]       RollbackTransaction();
[37]       ... Complete Error Handling ...
[38]    }</pre>
<p>In this case, there might be a large number of functions that are used to manipulate the database internally, but these are only accessable to customers and bank tellers through a limited set of BankingOperations that are always executed in a transaction.</p>
<h2>Notification</h2>
<p>There are several parties that could be notified when something goes wrong with an application,  most commonly:</p>
<ol>
<li>the end user,</li>
<li>the system administrator,  and</li>
<li>the developers.</li>
</ol>
<p>Sometimes, as in the case of a public-facing web application, #2 and #3 may overlap. In desktop applications, #2 might not exist.</p>
<p>Let&#8217;s consider the end user first. The end user really needs to know (i) that something went wrong, and (ii) what they can do about it. Often errors are caused by user input: hopefully these errors are expected, so the system can tell the user specifically what went wrong: for instance,</p>
<pre>[39] try {
[40]   ... process form information ...
[41]
[42]    if (!IsWellFormedSSN(ssn))
[43]       throw new InvalidInputException("You must supply a valid social security number");
[44]
[45]    ... process form some more ...
[46] } catch(InvalidInputException e) {
[47]    DisplayError(e.Message);
[48] }</pre>
<p>other times, errors happen that are unexpected. Consider a common (and bad) practice that we see in database applications: programs that write queries without correctly escaping strings:</p>
<pre>[49] dbConn.Execute("
[50]   INSERT INTO people (first_name,last_name)
[51]      VALUES ('"+firstName+"','+lastName+"');
[52] ");</pre>
<p>this code is straightforward, but dangerous,  because a single quote in the <em>firstName</em> or <em>lastName</em> variable ends the string literal in the VALUES clause,  and enables an SQL injection attack.  (I&#8217;d hope that <em>you</em> know better than than to do this, but large projects worked on by large teams inevitably have problems of this order.) This code might even hold up well in testing, failing only in production when a person registers with</p>
<pre>[53] lastName="O'Reilly";</pre>
<p>Now,  the dbConn is going to throw something like a <em>SqlException</em> with the following message:</p>
<pre>[54] SqlException.Message="Invalid SQL Statement:
[55]   INSERT INTO people (first_name,last_name)
[56]      VALUES ('Baba','O'Reilly');"</pre>
<p>we could show that message to the end user, but that message is worthless to most people. Worse than that, it&#8217;s harmful if the end user is a cracker who could take advantage of the error &#8212; it tells them the name of the affected table, the names of the columns, and the exact SQL code that they can inject something into. You might be better off showing users something like:</p>
<p><a href="http://gen5.info/q/wp-content/uploads/2008/08/twitter-whale.png"><img class="alignnone size-full wp-image-92" title="twitter-whale" src="http://gen5.info/q/wp-content/uploads/2008/08/twitter-whale.png" alt="" width="400" height="300" /></a></p>
<p>and telling them that they&#8217;ve experienced an &#8220;Internal Server Error.&#8221;  Even so,  the discovery that a single quote can cause an &#8220;Internal Server Error&#8221; can be enough  for a good cracker to sniff out the fault and develop an attack in the blind.. What can we do? Warn the system administrators. The error handling system for a server application should log exceptions, stack trace and all. It doesn&#8217;t matter if you use the UNIX <em>syslog</em> mechanism,  the logging service in Windows NT,   or something that&#8217;s built into your server,  like Apache&#8217;s <em>error_log</em>.  Although logging systems are built into both Java and .Net,  many developers find that <a href="http://logging.apache.org/log4j/1.2/index.html">Log4J</a> and <a href="http://logging.apache.org/log4net/index.html">Log4N</a> are especially effective.</p>
<p>There really are two ways to use logs:</p>
<ol>
<li>Detailed logging information is useful for debugging problems after the fact. For instance, if a user reports a problem, you can look in the logs to understand the origin of the problem, making it easy to debug problems that occur rarely: this can save hours of time trying to understand the exact problem a user is experiencing.</li>
<li>A second approach to logs is proactive: to regularly look a logs to detect problems before they get reported. In the example above, the <em>SqlException</em> would probably first be thrown by an innocent person who has an apostrophe in his or her name &#8212; if the error was detected that day and quickly fixed, a potential security hole could be fixed long before it would be exploited.  Organizaitons that investigate all exceptions thrown by production web applications run the most secure and reliable applications.</li>
</ol>
<p>In the last decade it&#8217;s become quite common for desktop applications to send stack traces back to the developers after a crash: usually they pop up a dialog box that asks for permission first. Although developers of desktop applications can&#8217;t be as proactive as maintainers of server applications, this is a useful tool for discovering errors that escape testing, and to discover how commonly they occur in the field.</p>
<h2>Retry I: Do it again!</h2>
<p>Some errors are transient: that is, if you try to do the same operation later, the operation may succeed. Here are a few common cases:</p>
<ul>
<li>An attempt to write to a DVD-R could fail because the disk is missing from the drive</li>
<li>A database transaction could fail when you commit it because of a conflict with another transaction: an attempt to do the transaction again could succeed</li>
<li>An attempt to deliver a mail message could fail because of problems with the network or destination mail server</li>
<li>A web crawler that crawls thousands (or millions) of sites will find that many of them are down at any given time: it needs to deal with this reasonably, rather than drop your site from it&#8217;s index because it happened to be down for a few hours</li>
</ul>
<p>Transient errors are commonly associated with the internet and with remote servers; errors are frequent because of the complexity of the internet, but they&#8217;re transitory because problems are repaired by both automatic and human intervention. For instance, if a hardware failure causes a remote web or email server to go down, it&#8217;s likely that somebody is going to notice the problem and fix it in a few hours or days.</p>
<p>One strategy for dealing with transient errors is to punt it back to the user: in a case like this, we display an error message that tells the user that the problem might clear up if they retry the operation. This is implicit in how web browsers work: sometimes you try to visit a web page, you get an error message, then you hit reload and it&#8217;s all OK. This strategy is particularly effective when the user could be aware that there&#8217;s a problem with their internet connection and could do something about it: for instance, they might discover that they&#8217;ve moved their laptop out of Wi-Fi range, or that the DSL connection at their house has gone down for the weekend.</p>
<p>SMTP, the internet protocol for email, is one of the best examples of automated retry. Compliant e-mail servers store outgoing mail in a queue: if an attempt to send mail to a destination server fails, mail will stay in the queue for several days before reporting failure to the user. Section 4.5.4 of <a href="http://www.ietf.org/rfc/rfc2821.txt">RFC 2821</a> states:</p>
<pre>   The sender MUST delay retrying a particular destination after one
   attempt has failed.  In general, the retry interval SHOULD be at
   least 30 minutes; however, more sophisticated and variable strategies
   will be beneficial when the SMTP client can determine the reason for
   non-delivery.

   Retries continue until the message is transmitted or the sender gives
   up; the give-up time generally needs to be at least 4-5 days.  The
   parameters to the retry algorithm MUST be configurable.

   A client SHOULD keep a list of hosts it cannot reach and
   corresponding connection timeouts, rather than just retrying queued
   mail items.

   Experience suggests that failures are typically transient (the target
   system or its connection has crashed), favoring a policy of two
   connection attempts in the first hour the message is in the queue,
   and then backing off to one every two or three hours.</pre>
<p>Practical mail servers use <em>fsync()</em> and other mechanisms to implement transactional semantics on the queue: the needs of reliability make it expensive to run an SMTP-compliant server, so e-mail spammers often use non-compliant servers that don&#8217;t correctly retry (if they&#8217;re going to send you 20 copies of the message anyway, who cares if only 15 get through?) <a href="http://en.wikipedia.org/wiki/Greylisting">Greylisting</a> is a highly effective filtering strategy that tests the compliance of SMTP senders by forcing a retry.</p>
<h2>Retry II: If first you don&#8217;t succeed&#8230;</h2>
<p>An alternate form of retry is to try something different. For instance, many programs in the UNIX environment will look in many different places for a configuration file: if the file isn&#8217;t in the first place tried, it will try the second place and so forth.</p>
<p>The online e-print server at <a href="http://www.cs.cornell.edu/Courses/cs501/2005sp/concepts/arxiv.html">arXiv.org</a> has a system called <a href="http://www.cs.cornell.edu/Courses/cs501/2005sp/concepts/arxiv.html">AutoTex</a> which automatically converts documents written in several dialects of <a href="http://en.wikipedia.org/wiki/TeX">TeX</a> and <a href="http://en.wikipedia.org/wiki/LaTeX">LaTeX</a> into Postscript and PDF files.  AutoTex unpacks the files in a submission into a directory and uses <em>chroot</em> to run the document processing tools in a protected sandbox. It tries about of ten different configurations until it finds one that successfully compiles the document.</p>
<p>In embedded applications,  where availability is important,  it&#8217;s common to fall back to a &#8220;safe mode&#8221; when normal operation is impossible.  The Engine Control Unit in a modern car is a good example:</p>
<p><a href="http://www.vehicle-lab.net/ecu.html"><img class="alignnone size-full wp-image-94" title="ecu" src="http://gen5.info/q/wp-content/uploads/2008/08/ecu.jpg" alt="" width="416" height="267" /></a></p>
<p>Since the 1970&#8242;s,   regulations in the United States have reduced emissions of hydrocarbons and nitrogen oxides from passenger automobiles by more than a hundred fold.  The technology has many aspects,  but the core of the system in an Engine Control Unit that uses a collection of sensors to monitor the state of the engine and uses this information to adjust engine parameters (such as the quantity of fuel injected) to balance performance and fuel economy with environmental compliance.</p>
<p>As the condition of the engine,  driving conditions and composition of fuel change over the time,  the ECU normally operates in a &#8220;closed-loop&#8221; mode that continually optimizes performance.   When part of the system fails (for instance,  the oxygen sensor) the ECU switches to an &#8220;open-loop&#8221; mode.  Rather than leaving you stranded,  it lights the &#8220;check engine&#8221; indicator and operates the engine with conservative assumptions that will get you home and to a repair shop.</p>
<h2>Ignore?</h2>
<p>One strength of exceptions,  compared to the older return-value method of error handling is that the default behavior of an exception is to abort,  not to ignore.  In general,  that&#8217;s good,  but there are a few cases where &#8220;ignore&#8221; is the best option.  Ignoring an error makes sense when:</p>
<ol>
<li>Security is not at stake,  and</li>
<li>there&#8217;s no alternative action available,  and</li>
<li>the consequences of an abort are worse than the consequences of avoiding an error</li>
</ol>
<p>The first rule is important,  because crackers will take advantage of system faults to attack a system.  Imagine,  for instance,  a &#8220;smart card&#8221; chip embedded in a payment card.  People have successfully extracted information from smart cards by fault injection:  this could be anything from a power dropout to a bright flash of light on an exposed silicon surface.  If you&#8217;re concerned that a system will be abused,  it&#8217;s probably best to shut down when abnormal conditions are detected.</p>
<p>On the other hand,  some operations are vestigial to an application.  Imagine,  for instance,  a dialog box that pops when an application crashes that offers the user the choice of sending a stack trace to the vendor.  If the attempt to send the stack trace fails,  it&#8217;s best to ignore the failure &#8212; there&#8217;s no point in subjecting the user to an endless series of dialog boxes.</p>
<p>&#8220;Ignoring&#8221; often makes sense in the applications that matter the most and those that matter the least.</p>
<p>For instance,  media players and video games operate in a hostile environment where disks,  the network, sound and controller hardware are uncooperative.  The &#8220;unit of work&#8221; could be the rendering of an individual frame:  it&#8217;s appropriate for entertainment devices to soldier on despite hardware defects,  unplugged game controllers,  network dropouts and corrupted inputs,  since the consequences of failure are no worse than shutting the system down.</p>
<p>In the opposite case,  high-value systems and high-risk should continue functioning no matter what happen.  The software for a space probe,  for instance,  should never give up.  Much like an automotive ECU,  space probes default to a &#8220;safe mode&#8221; when contact with the earth is lost:  frequently this strategy involves one or more reboots,  but the goal is to always regain contact with controllers so that the mission has a chance at success.</p>
<h2>Conclusion</h2>
<p>It&#8217;s most practical to catch exceptions at the boundaries of relatively coarse &#8220;units of work.&#8221; Although the handling of errors usually involves some amount of rollback (restoring system state) and notification of affected people, the ultimate choices are still what they were in the days of DOS: abort, retry, or ignore.</p>
<p>Correct handling of an error requires some thought about the cause of an error: was it caused by bad input, corrupted application state, or a transient network failure? It&#8217;s also important to understand the impact the error has on the application state and to try to reduce it using mechanisms such as database transactions.</p>
<p>&#8220;Abort&#8221; is a logical choice when an error is likely to have caused corruption of the application state, or if an error was probably caused by a corrupted state. Applications that depend on network communications sometimes must &#8220;Retry&#8221; operations when they are interrupted by network failures. Another form of &#8220;Retry&#8221; is to try a different approach to an operation when the first approach fails. Finally, &#8220;Ignore&#8221; is appropriate when &#8220;Retry&#8221; isn&#8217;t available and the cost of &#8220;Abort&#8221; is worse than soldiering on.</p>
<p>This article is one of a <a href="http://gen5.info/q/category/exceptions/">series on error handling</a>.  The next article in this series will describe practices for defining and throwing exceptions that gives exception handlers good information for making decisions.  Subscribers to our <a href="http://feeds.feedburner.com/Generation5">RSS Feed</a> will be the first to read it.</p>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2008/08/27/what-do-you-do-when-youve-caught-an-exception/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Converting A Synchronous Program Into An Asynchronous Program</title>
		<link>http://gen5.info/q/2008/08/13/converting-a-synchronous-program-into-an-asynchronous-program/</link>
		<comments>http://gen5.info/q/2008/08/13/converting-a-synchronous-program-into-an-asynchronous-program/#comments</comments>
		<pubDate>Wed, 13 Aug 2008 17:58:48 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[Asynchronous Communications]]></category>
		<category><![CDATA[GWT]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://gen5.info/q/?p=49</guid>
		<description><![CDATA[Introduction One of the challenges in writing programs in today&#8217;s RIA environments  (Javascript, Flex, Silverlight and GWT)  is expressing the flow of control between multiple asynchronous XHR calls.  A &#8220;one-click-one-XHR&#8221; policy is often best,  but you don&#8217;t always have control over your client-server protocols.  A program that&#8217;s simple to read as a synchronous program can [...]]]></description>
			<content:encoded><![CDATA[<h2 style="text-align: left;">Introduction</h2>
<p style="text-align: left;">One of the challenges in writing programs in today&#8217;s RIA environments  (Javascript, Flex, Silverlight and GWT)  is expressing the flow of control between multiple asynchronous XHR calls.  A &#8220;<a href="http://gen5.info/q/2008/03/27/managing-concurrency-with-asynchronous-http-requests/">one-click-one-XHR</a>&#8221; policy is often best,  but you don&#8217;t always have control over your client-server protocols.  A program that&#8217;s simple to read as a synchronous program can become a tangle of subroutines when it&#8217;s broken up into a number of callback functions.  One answer is <em>program translation</em>:  to manually or automatically convert a synchronous program into an asynchronous program:  starting from the theoretical foundation,  this article talks about a few ways of doing that.</p>
<p style="text-align: left;"><a href="http://www.thibaudlopez.net/">Thibaud Lopez Schneider</a> sent me a link to an interesting paper he wrote,  titled &#8220;<a href="http://www.thibaudlopez.net/xhr/Writing%20effective%20asynchronous%20XmlHttpRequests.pdf">Writing Effective Asynchronous XmlHttpRequests</a>.&#8221;  He presents an informal proof that you can take a program that uses synchronous function calls and common control structures such as <em>if-else</em> and <em>do-while</em>,  and transform it a program that calls the functions asynchronously.  In simple language,  it gives a blueprint for implementing arbitrary control flow in code that uses asynchronous XmlHttpRequests.</p>
<p style="text-align: left;">In this article,  I work a simple example from Thibaud&#8217;s paper and talk about four software tools that automated the conversion of conventional control flows to asynchronous programming.  One tool,  the <a href="http://en.wikipedia.org/wiki/Windows_Workflow_Foundation">Windows Workflow Foundation,</a> lets us compose long-running applications out of a collection of asynchronous <em>Activity</em> objects.  Another two tools are<em> </em><a href="http://chumsley.org/jwacs/">jwacs</a> and <a href="http://www.neilmix.com/narrativejs/doc/">Narrative Javascript</a>,  open-source   translators that translated pseudo-blocking programs in a modified dialect of JavaScript into an asynchronous program in ordinary JavaScript that runs in your browser.</p>
<p style="text-align: left;"><span id="more-49"></span></p>
<p style="text-align: left;">
<h2 style="text-align: left;">A simple example: Sequential Execution</h2>
<p style="text-align: left;">I&#8217;m going to lift a simple example from <a href="http://www.thibaudlopez.net/xhr/Writing%20effective%20asynchronous%20XmlHttpRequests.pdf">Thibaud&#8217;s paper</a>,  the case of sequential execution.  Imagine that we want to write a function <em>f()</em>,  that follows the following logic</p>
<pre style="text-align: left;">[01] function f() {
[02]    ... pre-processing ...
[03]    result1=MakeRequest1(argument1);
[04]    ... think about result1 ...
[05]    result2=MakeRequest2(argument2);
[06]    ... think about result2 ...
[07]    result3=MakeRequest3(argument3);
[08]    ... think about result3 ...
[09]    return finalResult;
[10] }</pre>
<p style="text-align: left;">where functions of the form <em>MakeRequestN</em> are ordinary synchronous functions.  If,  however,  we were working in an environment like JavaScript,  GWT,  Flex,  or Silverlight,  server requests are asynchronous,  so we&#8217;ve only got functions like:</p>
<pre>[11] function BeginMakeRequestN(argument1, callbackFunction);</pre>
<p style="text-align: left;">It&#8217;s no longer possible to express a sequence of related requests as a single function,  instead we need to transform f() into a series of functions,  like so</p>
<pre style="text-align: left;">[12] function f(callbackFunction) {
[13]   ... pre-processing ...
[14]   BeginMakeRequest1(argument,f1);
[15] }
[16]
[17] function f1(result1) {
[18]    ... think about result1 ...
[19]    BeginMakeRequest2(argument2,f2);
[20] }
[21]
[22] function f2(result2) {
[23]    ... think about result2 ...
[24]    BeginMakeRequest3(argument3,f3);
[25] }
[26]
[27] function f3(result3) {
[28]   ... think about result 3 ...
[29]   callbackFunction(finalResult);
[30] }</pre>
<p style="text-align: left;">My example differs from the example of on page 19 of <a href="http://www.thibaudlopez.net/xhr/Writing%20effective%20asynchronous%20XmlHttpRequests.pdf">Thibaud&#8217;s paper</a> in a few ways&#8230;  In particular,  I&#8217;ve added the <em>callbackFunction</em> that <em>f()</em> uses to &#8220;return&#8221; a result to the program that calls it.  Here the <em>callbackFunction</em> lives in a scope that&#8217;s shared by all of the <em>fN</em> functions,  so it&#8217;s available in <em>f3</em>.  I&#8217;ve found that when you&#8217;re applying Thibuad&#8217;s kind of thinking,  it&#8217;s useful for <em>f()</em> to correspond to an object,   of which the <em>fN()</em> functions are methods. [<a href="http://gen5.info/q/2008/06/02/keeping-track-of-state-in-asynchronous-callbacks/">1</a>] [<a href="http://gen5.info/q/2008/04/18/asynchronous-functions/">2</a>] [<a href="http://gen5.info/q/2008/04/11/the-asynchronous-command-pattern/">3</a>]</p>
<p style="text-align: left;">Thibaud also works the implementation of <em>if-then-else</em>,  <em>switch</em>,  <em>for</em>,  <em>do-while</em>,  <em>parallel-do</em> and other common patterns &#8212; <a href="http://www.thibaudlopez.net/xhr/Writing%20effective%20asynchronous%20XmlHttpRequests.pdf">read his paper</a>!</p>
<h2 style="text-align: left;">What next?</h2>
<p>There are things missing from Thibaud&#8217;s current draft:  for instance,  he doesn&#8217;t consider how to implement exception handling in asynchronous applications,  although it&#8217;s <a href="http://gen5.info/q/2008/04/18/asynchronous-functions/">quite possible to do</a>.</p>
<p>Thinking about things systematically helps you do things by hand,  but it really comes into it&#8217;s own when we use systematic thinking to develop tools.  I can imagine two kinds of tools based on Thibaud&#8217;s ideas:</p>
<ol>
<li>Specialized languages for expressing asynchronous flows,  and</li>
<li>Compilers that transform synchronous programs to asynchronous programs</li>
</ol>
<h2>Windows Workflow Foundation</h2>
<p>Windows Workflow Foundation is an example of the first approach.</p>
<p>Although it&#8217;s not designed for use in asynchronous RIA&#8217;s,  Microsoft&#8217;s <a href="http://joeon.net/post/2008/02/Windows-Workflow-Foundation-Tutorial-Series.aspx">Windows Workflow Foundation </a>is an new approach to writing reactive programs.   Unfortunately,  like a lot of enterprise technologies,  WWF is surrounded by a lot of hype that obscures a number of worthwhile ideas:  the book <a href="http://www.amazon.com/gp/product/0321399838/103-7142849-0321425?ie=UTF8&amp;tag=honeymediasys-20&amp;linkCode=xm2&amp;camp=1789&amp;creativeASIN=0321399838">Essential Windows Workflow Foundation</a> by Shukla and Schmidt is a lucid explanation of the principles behind it.  It&#8217;s good reading even if you hate Microsoft and would never use a Microsoft product,  because it could inspire you to implement something similar in your favorite environment.  (I know someone who&#8217;s writing a webcrawler in PHP based on a similar approach)</p>
<p>What does it do?</p>
<p>In WWF,  you create an asynchronous program by composing a set of asynchronous <em>Activities</em>.  Ultimately your program is a tree of <em>Activity</em> objects that you can assemble any way you like,  but typically you&#8217;d build them with a XAML (XML) file that might look like</p>
<pre>[31] &lt;Interleave x:Name="i1"&gt;
[32]    &lt;Sequence x:Name="s1"&gt;
[33]       &lt;ReadLine x:Name="r1" /&gt;
[34]       &lt;WriteLine x:Name="w1"
[35]          Text="{wf:ActivityBind r1,path=Text}" /&gt;
[36]       &lt;ReadLine x:Name="r2" /&gt;
[37]       &lt;WriteLine x:Name="w2"
[38]          Text="{wf:ActivityBind r2,path=Text}" /&gt;
[39]    &lt;/Sequence&gt;
[40]    &lt;Sequence x:Name="s2"&gt;
[41]       &lt;ReadLine x:Name="r3" /&gt;
[42]       &lt;WriteLine x:Name="w3"
[43]          Text="{wf:ActivityBind r3,path=Text}" /&gt;
[44]       &lt;ReadLine x:Name="r4" /&gt;
[45]       &lt;WriteLine x:Name="w4"
[46]          Text="{wf:ActivityBind r4,path=Text}" /&gt;
[47]    &lt;/Sequence&gt;
[48] &lt;/Interleave&gt;</pre>
<p>(The above example is based on Listing 3.18 on Page 98 of Shukla and Schmidt,  with some namespace declarations removed for clarity)</p>
<p>This defines a flow of execution that looks like:</p>
<p><a href="http://gen5.info/q/wp-content/uploads/2008/08/wwfdiagram.png"><img class="alignnone size-full wp-image-60" title="wwfdiagram" src="http://gen5.info/q/wp-content/uploads/2008/08/wwfdiagram.png" alt="" width="485" height="244" /></a></p>
<p>The <em>&lt;Interleave&gt;</em> activity causes two <em>&lt;Sequence&gt;</em> activities to run simultaneously.  Each <em>&lt;Sequence&gt;</em>,  in turn,  sequentially executes two alternating pairs of <em>&lt;ReadLine&gt;</em> and <em>&lt;WriteLine&gt;</em> activities.  Note that the attribute values that look like <em>{wf: ActivityBind r3,path=Text}</em> wire out the output of a <em>&lt;ReadLine&gt;</em> activity to the input of a <em>&lt;WriteLine&gt;</em> activity.</p>
<p>Note that <em>&lt;Interleave&gt;</em>,  <em>&lt;Sequence&gt;</em>,  <em>&lt;ReadLine&gt;</em> and <em>&lt;WriteLine&gt;</em> are all asynchronous activities defined by classes <em>Interleave</em>, <em>Sequence</em>, <em>ReadLine</em> And <em>WriteLine</em> that all implement <em>Activity</em>.   An activity can invoke other activities,  so it&#8217;s possible to create new control structures.  Activities can wait for things to happen in the outside world (such as a web request or an email message) by listening to a queue.   WWF also defines an elaborate model for error handling.</p>
<p>Although other uses are possible,   WWF is intended for the implementation of server applications implementations that implement workflows.  Imagine,  for instance,  a college applications system,  which must wait for a number of forms from the outside,  such as</p>
<ul>
<li>an application,</li>
<li>standardized test scores, and</li>
<li>letters of reccomendation</li>
</ul>
<p>and that needs to solicit internal input from</p>
<ul>
<li>an initial screening committee,</li>
<li>the faculty of individual departments,  and</li>
<li>the development office.</li>
</ul>
<p>The state of a workflow can be serialized to a database,   so the workflow can be something that takes place over a long time,  such as months or weeks &#8212; multiple instances of the workflow can exist at the same time.</p>
<p>WWF looks like a fun environment to program for,  but I don&#8217;t know if I&#8217;d trust it for a real business application.  Why?  I&#8217;ve been building this sort of application for years using relational databases,  I know that it&#8217;s possible to handle the maintenance situations that occur in real life with a relational representation:  both the little tweaks you need to make to a production system from time to time,  and the more major changes required when your process changes.  Systems based on object serialization,  such as WWF,   tend to have trouble when you need to change the definition of objects over time.</p>
<p>I can say,  however,  that the <a href="http://www.amazon.com/gp/product/0321399838/103-7142849-0321425?ie=UTF8&amp;tag=honeymediasys-20&amp;linkCode=xm2&amp;camp=1789&amp;creativeASIN=0321399838">Shukla and Schmidt</a> book is so clear that an ambitious programmer could understand enough of the ideas behind WWF to develop a similar framework that&#8217;s specialized for developing asynchronous RIAs in Javascript,  Java,  or C# pretty quickly.   Read it!</p>
<h2>Transforming Javascript and Other Languages</h2>
<p>Another line of attack on asynchronous programming is the creation of compilers and translators that transform a synchronous program into a synchronous program.  This is particularly popular in Javascript,  where open-source tools such as <a href="http://chumsley.org/jwacs/demos.html">jwacs</a> (Javascript With Advanced Continuation Syntax) let you write code like this:</p>
<pre>[49] function main() {
[50]    document.getElementById('contentDiv').innerHTML =
[51]      '&lt;pre&gt;'
[52]      + JwacsLib.fetchData('GET', 'dataRows.txt')
[53]      + '&lt;/pre&gt;';
[54] }</pre>
<p>Jwacs adds four new keywords to the Javascript language:  internally,  it applies transformations like the ones in the Thibaud paper.  Although it looks as if the call to <em>JwacsLib.fetchData</em> blocks,  in reality,  it splits the <em>main()</em> function into two halves,  executing the function by a form of cooperative multitasking.</p>
<p><a href="http://neilmix.com/narrativejs/doc/index.html">Narrative Javascript</a> is a similar open-source translator that adds -&gt;,  a &#8220;yielding&#8221; operator to Javascript.  This signals the translator to split the enclosing function,  and works for timer and UI event callbacks as well as XHR.  Therefore,  it&#8217;s possible to write a pseudo-blocking sleep() function like:</p>
<pre>[55] function sleep(millis) {
[56]    var notifier = new EventNotifier();
[57]    setTimeout(notifier, millis);
[58]    notifier.wait-&gt;();
[59] }</pre>
<p>Narrative Javascript doesn&#8217;t remember the special nature of the the sleep() function,  so you need to call it with the yielding operator too.  With it,  you can animate an element like so:</p>
<pre>[60] for (var i = 0; i &lt; frameCount - 1; i++) {
[61]    var nextValue = startValue + (jumpSize * i);
[62]    element.style[property] = nextValue + "px";
[63]    sleep-&gt;(frequency);
[64] }</pre>
<p>You can use the yielding operator to wait on user interface events as well.  If you first define</p>
<pre>[65] function waitForClick(element) {
[66]    var notifier = new EventNotifier();
[67]    element.onclick = notifier;
[68]    notifier.wait-&gt;();
[69] }</pre>
<p>you can call it with the yielding operator to wait for a button press</p>
<pre>[70] theButton.innerHTML = "go right";
[71] waitForClick-&gt;(theButton);
[72] theButton.innerHTML = "--&gt;";
[73] ... continue animation ...</pre>
<p>The <a href="http://rifers.org/wiki/display/RIFE/Web+continuations">RIFE Continuation Engine</a> implements something quite similar in Java,  but it translates at the bytecode level instead of at the source code level:  it aims to transform the server-side of web applications,  rather than the client,  by allowing the execution of a function to span two separate http requests.</p>
<h2>Conclusion</h2>
<p>It&#8217;s possible to systematically transform a function that&#8217;s written in terms of conventional control structures and synchronous function calls into a collection of functions that performs the same logic using asynchronous function calls.   A paper by <a href="http://www.thibaudlopez.net/">Thibaud Lopez Schneider</a> points the way,  and is immediately useful for RIA programmers that need to convert conventional control structures in their head into asynchronous code.</p>
<p>A longer-term strategy is to develop frameworks and languages that make it easier to express desired control flows for asynchronous program.  The Windows Workflow Foundation from Microsoft is a fascinating attempt to create a specialized language for assembling asynchronous programs from a collection of <em>Activity</em> objects.  <a href="http://chumsley.org/jwacs/demos.html">jwacs</a> and <a href="http://neilmix.com/narrativejs/doc/index.html">Narrative Javascript</a> are bold attempts to extend the Javascript language so that people can express asynchronous logic as pseudo-threaded programs.  The <a href="http://rifers.org/wiki/display/RIFE/Web+continuations">RIFE Continuation Engine</a> demonstrates that this kind of behavior can be implemented in more static languages such as Java and C#.  Although none of these tools are ready for production-quality RIA work,  they may lead to something useful in the next few years.</p>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2008/08/13/converting-a-synchronous-program-into-an-asynchronous-program/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Stop Catching Exceptions!</title>
		<link>http://gen5.info/q/2008/07/31/stop-catching-exceptions/</link>
		<comments>http://gen5.info/q/2008/07/31/stop-catching-exceptions/#comments</comments>
		<pubDate>Fri, 01 Aug 2008 01:45:24 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[Dot Net]]></category>
		<category><![CDATA[Exceptions]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://gen5.info/q/?p=43</guid>
		<description><![CDATA[Motivation It&#8217;s clear that a lot of programmers are uncomfortable with exceptions [1] [2]; in the feedback of an article I wrote about casting, it seemed that many programmers saw the throwing of a NullReferenceException at a cast to be an incredible catastrophe. In this article, I&#8217;ll share a philosophy that I hope will help [...]]]></description>
			<content:encoded><![CDATA[<h2>Motivation</h2>
<p>It&#8217;s clear that a lot of programmers are uncomfortable with exceptions <a href="http://www.joelonsoftware.com/items/2003/10/13.html">[1]</a> <a href="http://www.ckwop.me.uk/Why-Exceptions-Suck.html">[2]</a>;  in the feedback of an article I wrote about casting,  it seemed that many programmers saw the throwing of a <em>NullReferenceException</em> at a cast to be an incredible catastrophe.</p>
<p>In this article,  I&#8217;ll share a philosophy that I hope will help programmers overcome the widespread fear of exceptions.  It&#8217;s motivated by five goals:</p>
<ol>
<li>Do no harm</li>
<li>To write as little error handling code as possible,</li>
<li>To think about error handling as little as possible</li>
<li>To handle errors correctly when possible,</li>
<li>Otherwise errors should be handled sanely</li>
</ol>
<p>To do that, I</p>
<ol>
<li>Use <em>finally</em> to stabilize program state when exceptions are thrown</li>
<li><em>Catch</em> and handle exceptions locally when the effects of the error are local and completely understood</li>
<li>Wrap independent units of work in <em>try-catch</em> blocks to handle errors that have global impact</li>
</ol>
<p>This isn&#8217;t the last word on error handling,  but it avoids many of the pitfalls that people fall into with exceptions.  By building upon this strategy,  I believe it&#8217;s possible to develop an effective error handling strategy for most applications:  future articles will build on this topic,  so keep posted by subscribing to the <a href="http://feeds.feedburner.com/Generation5">Generation 5 RSS Feed</a>.</p>
<h2><span id="more-43"></span>The Tragedy of Checked Exceptions</h2>
<p>Java&#8217;s done a lot of good,  but checked exceptions are probably the worst legacy that Java has left us.  Java has influenced Python,  PHP,  Javascript,  C# and many of the popular languages that we use today.  Unfortunately,  checked exceptions taught Java programmers to catch exceptions prematurely,  a habit that Java programmers carried into other languages,  and has result in a code base that sets bad examples.</p>
<p>Most exceptions in Java are checked,  which means that the compiler will give you an error if you write</p>
<pre>[01] public void myMethod() {
[02]    throw new ItDidntWorkException()
[03] };</pre>
<p>unless you either catch the exception inside <em>myMethod</em> or you replace line [01] with</p>
<pre>[04] public void myMethod() throws ItDidntWorkException {</pre>
<p>The compiler is also aware of any checked exceptions that are thrown by methods underneath <em>myMethod</em>,  and forces you to either catch them inside <em>myMethod</em> or to declare them in the throws clause of <em>myMethod</em>.</p>
<p>I thought that this was a great idea when I started programming Java in 1995.  With the hindsight of a decade,  we can see that it&#8217;s a disaster.  The trouble is that every time you call a method that throws an exception,  you create an immediate crisis:  you break the build.   Rather than conciously planning an error handling strategy,  programmers do something,  anything,   to make the compiler shut up.  Very often you see people bypass exceptions entirely,  like this:</p>
<pre>[05] public void someMethod() {
[06]    try {
[07]       objectA.anotherMethod();
[08]    } catch(SubsystemAScrewedUpException ex) { };
[09] }</pre>
<p>Often you get this instead:</p>
<pre>[10]    try {
[11]       objectA.anotherMethod();
[12]    } catch(SubsystemAScrewedUp ex) {
[13]        // something ill-conceived to keep the compiler happy
[14]    }
[15]    // Meanwhile,  the programmer makes a mistake here because
[16]    // writing an exception handler broke his concentration</pre>
<p>This violates the first principle,  to &#8220;do no harm.&#8221;  It&#8217;s simple,  and often correct,  to pass the exception up to the calling function,</p>
<pre>[17] public int someMethod() throws SubsystemAScrewedUp {</pre>
<p>But,   this still breaks the build,  because now every function that calls <em>someMethod()</em> needs to do something about the exception.  Imagine a program of some complexity that&#8217;s maintained by a few programmers,  in which method A() calls method B() which calls method C() all the way to method F().</p>
<p><img src="http://gen5.info/q/wp-content/uploads/2008/07/dontthrowcalls.png" alt="" /></p>
<p>The programmer who works on method F() can change the signature of that method,  but he may not have the authority to change the signature of the methods above.  Depending on the culture of the shop,  he might be able to do it himself,  he might talk about it with the other programmers over IM,  he might need to get the signatures of three managers,  or he might need to wait until the next group meeting.  If they keep doing this,  however,  A() might end up with a signature like</p>
<pre>[18] public String A() throws SubsystemAScrewedUp, IOException, SubsystemBScrewedUp,
[19]   WhateverExceptionVendorZCreatedToWrapANullPointerException, ...</pre>
<p>This is getting out of hand,  and they realize they can save themselvesa lot of suffering by just writing</p>
<pre>[20] public int someMethod() throws Exception {</pre>
<p>all the time,  which is essentially disabling the checked exception mechanism.  Let&#8217;s not dismiss the behavior of the compiler out of hand,  however,  because it&#8217;s teaching us an important lesson:  error handling is a holistic property of a program:  an error handled in method F() can have implications for methods A()&#8230;E().  <em><strong>Errors often break the assumption of encapsulation</strong></em>,  and require a global strategy that&#8217;s applied consistently throughout the code.</p>
<p>PHP,  C# and other post-Java languages tend to not support checked exceptions.  Unfortunately,  checked exception thinking has warped other langages,  so you&#8217;ll find that catch statements are used neurotically everywhere.</p>
<h2>Exception To The Rule: Handling Exceptions Locally</h2>
<p>Sometimes you can anticipate an exception,  and know what exact action to take.  Consider the case of a compiler,  or a program that processes a web form,  which might find more than one error in user input.  Imagine something like (in C#):</p>
<pre>[21] List&lt;string&gt; errors=new List&lt;string&gt;();
[22] uint quantity=0;
[23] ... other data fields ...
[24]
[25] try {
[26]   quantity=UInt32.Parse(Params["Quantity"]);
[27] } catch(Exception ex) {
[28]   errors.Add("You must enter a valid quantity");
[29] }
[30]
[31] ... other parsers/validators ...
[32]
[33] if (errors.Empty()) {
[34]    ... update database,  display success page ...
[35] } else {
[36]    ... redraw form with error messages ...
[37] }</pre>
<p>Here it makes sense to catch the exception locally,  because the exceptions that can happen on line [22] are completely handled,  and don&#8217;t have an effect on other parts of the application.  The one complaint you might make is that I should be catching something more specific than <em>Exception</em>.  Well,  that would bulk the code up considerably and violate the DRY (don&#8217;t repeat yourself) principle: <em>UInt32.Parse</em> can throw three different exceptions:  <em>ArgumentNullException</em>,  <em>FormatException</em>,  and <em>OverflowException</em>.  On paper,  the process of looking up the &#8220;Quantity&#8221; key in <em>Params</em> could throw an <em>ArgumentNullException</em> or a <em>KeyNotFoundException</em>.</p>
<p>I don&#8217;t think either <em>ArgumentNullException</em> can really happen,  and I think the <em>KeyNotFoundException </em>would only occur in development,  or if somebody was trying to submit the HTML form with an unauthorized program.   Probably the best thing to do in either case would be to abort the script with a 500 error and log the details,  but the error handling on line [24] is <strong>sane</strong> in that it prevents corruption of the database.</p>
<p>The handling of <em>FormatException</em> and <em>OverflowException</em>,  in the other case,  is fully correct.  The user gets an error message that tells them what they need to do to fix the situation.</p>
<p>This example demonstrates a bit of why error handling is so difficult and why the perfect can be the enemy of the good:  the real cause of an<em> IOException</em> could be a microscopic scratch on the surface of a hard drive,  and operating system error, or the fact that somebody spilled a coke on a router in Detroit &#8212; diagnosing the problem and offering the right solution is an insoluble problem.</p>
<h2>Fixing it up with <em>finally</em></h2>
<p>The first exception handling construct that should be on your fingertips is <em>finally</em>,  not <em>catch</em>.  Unfortunately,  <em>finally</em> is a bit obscure:  the pattern in most languages is</p>
<pre>[38] try {
[39]    ... do something that might throw an exception ...
[40] } finally {
[41]    ... clean up ...
[42] }</pre>
<p>The code in the <em>finally</em> clause get runs whether or not an exception is thrown in the <em>try</em> block.  <em>Finally</em> is a great place to release resources,  roll back transactions,  and otherwise protect the state of the application by enforcing invariants.  Let&#8217;s think back to the chain of methods <em>A()</em> through <em>F()</em>:  with <em>finally</em>,  the maintainer of <em>B() </em>can implement a local solution to a global problem that starts in <em>F()</em>:  no matter what goes wrong downstream,  B() can repair invariants and repair the damage.  For instance,  if B()&#8217;s job is to write something into a transactional data store,  B() can do something like:</p>
<pre>[43] Transaction tx=new Transaction();
[44] try {
[45]    ...
[46]    C();
[47]    ...
[48]    tx.Commit();
[49] } finally {
[50]    if (tx.Open)
[51]        tx.Rollback();
[52] }</pre>
<p>This lets the maintainer of B() act defensively,  and offer the guarantee that the persistent data store won&#8217;t get corrupted because of an exception that was thrown in the <em>try</em> block.  Because B() isn&#8217;t catching the exception,  it can do this <strong>without depriving upstream methods</strong>,  <strong>such as A() from doing the same.</strong></p>
<p>C# gets extra points because it has syntactic sugar that makes a simple case simple:  The <em>using</em> directive accepts an <em>IDisposable </em>as an argument and wraps the block after it with a finally clause that calls the <em>Dispose()</em> method of the <em>IDisposable</em>.  ASP.NET applications can fail catastrophically if you don&#8217;t <em>Dispose() </em>database connections and result sets,  so</p>
<pre>[53] using (var reader=sqlCommand.ExecuteReader()) {
[54]   ... scroll through result set ...
[55] }</pre>
<p>is a widespread and effective pattern.</p>
<p>PHP loses points because it doesn&#8217;t support <em>finally</em>.  Granted,  <em>finally</em> isn&#8217;t as important in PHP,  because all resources are released when a PHP script ends.  The absense of <em>finally</em>,  however,   encourages PHP programmers to overuse <em>catch</em>,  which perpetuates exception phobia.   The PHP developers are adding great features to PHP 5.3,  such as late static binding,   so we can hope that they&#8217;ll change their mind and bring us a <em>finally</em> clause.</p>
<h2>Where should you catch exceptions?</h2>
<p>At high levels of your code,  you should wrap <strong>units of work</strong> in a try-catch block.  A unit of work is something that makes sense to either give up on or retry.  Let&#8217;s work out a few simple examples:</p>
<p><strong>Scripty Command line program:</strong> This program is going to be used predominantly by the person who wrote it and close associates,  so it&#8217;s acceptable for the program to print a stack trace if it fails.  The &#8220;unit of work&#8221; is the whole program.</p>
<p><strong>Command line script that processes a million records:</strong> It&#8217;s likely that some records are corrupted or may trigger bugs in the program.  Here it&#8217;s reasonable for the &#8220;unit of work&#8221; to be the processing of a single record.  Records that cause exceptions should be logged,  together with a stack trace of the exception.</p>
<p><strong>Web application: </strong>For a typical web application in PHP,  JSP or ASP.NET,  the &#8220;unit of work&#8221; is the web request.  Ideally the application returns a &#8220;500 Internal Error&#8221;,  displays a message to the user (that&#8217;s useful but not overly revealing) and logs the stack trace (and possibly other information) so the problem can be investigated.  If the application is in debugging mode,   it&#8217;s sane to display the stack trace to the web browser.</p>
<p><strong>GUI application: </strong>The &#8220;unit of work&#8221; is most often an event handler that&#8217;s called by the GUI framework.  You push a button,  something does wrong,  then what?  Unlike server-side web applications,  which tend to assume that exceptions don&#8217;t involve corruption of static memory or of a database,  GUI applications tend to shut down when they experience unexpected exceptions.  [<a href="http://blogs.msdn.com/larryosterman/archive/2008/05/01/resilience-is-not-necessarily-a-good-thing.aspx">3</a>]  As a result,  GUI applications tend to need infrastructure to convert common and predictable exceptions (such as network timeouts) into human readable error messages.</p>
<p><strong>Mail server: </strong>A mail server stores messages in a queue and delivers them over a unreliable network.  Exceptions occur because of full disks (locally or remote),  network failures,  DNS misconfigurations,  remote server falures,  and an occasionaly cosmic ray.  The &#8220;unit of work&#8221; is the delivery of a single message.  If an exception is thrown during delivery of the message,  it stays in the queue:  the mail server attempts to resend on a schedule,  discarding it if it is unable to deliver after seven days.</p>
<h2>What should you do when you&#8217;ve caught one?</h2>
<p>That&#8217;s the subject of another article.  <a href="http://feeds.feedburner.com/Generation5">Subscribe to my RSS</a> feed if you want to read it when it&#8217;s ready.  For now,  I&#8217;ll enumerate a few questions to think about:</p>
<ol>
<li>What do tell the end user?</li>
<li>What do you tell the developer?</li>
<li>What do you tell the sysadmin?</li>
<li>Will the error clear if up if we try to repeat this unit of work again?</li>
<li>How long would we need to wait?</li>
<li>Could we do something else instead?</li>
<li>Did the error happen because the state of the application is corrupted?</li>
<li>Did the error cause the state of the application to get corrupted?</li>
</ol>
<h2>Conclusion</h2>
<p>Error handling is tough.  Because errors come from many sources such as software defects,  bad user input,  configuration mistakes,  and both permanent and transient hardware failures,  it&#8217;s impossible for a developer to anticipate and perfectly handle everything that can go wrong.  Exceptions are an excellent method of separating error handling logic from the normal flow of programs,  but many programmers are too eager to catch exceptions:  this either causes errors to be ignores,  or entangles error handling with mainline logic,  complicating both.  The long term impact is that many programmers are afraid of exceptions and turn to return values as an error signals,  which is a step backwards.</p>
<p>A strategy that (i) uses <em>finally</em> as the first resort for containing corrupting and maintaining invariants,   (ii) uses <em>catch</em> locally when the exceptions thrown in an area are completely understood, and (iii) surrounds independent units of work with <em>try-catch</em> blocks is an effective basis for using exceptions that can be built upon to develop an exception handling policy for a particular application.</p>
<p>Error handling is a topic that I spend entirely too much time thinking about,  so I&#8217;ll be writing about it more.  Subscribe to my <a href="http://feeds.feedburner.com/Generation5">RSS Feed</a> if you think I&#8217;ve got something worthwhile to say.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fgen5.info%2fq%2f2008%2f07%2f31%2fstop-catching-exceptions%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fgen5.info%2fq%2f2008%2f07%2f31%2fstop-catching-exceptions%2f" border="0" alt="kick it on DotNetKicks.com" /></a><br />
<script type="text/javascript"><!--
digg_url = 'http://digg.com/programming/Stop_Catching_Exceptions';
// --></script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2008/07/31/stop-catching-exceptions/feed/</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
		<item>
		<title>The Multiton Design Pattern</title>
		<link>http://gen5.info/q/2008/07/25/the-multiton-design-pattern/</link>
		<comments>http://gen5.info/q/2008/07/25/the-multiton-design-pattern/#comments</comments>
		<pubDate>Fri, 25 Jul 2008 16:04:05 +0000</pubDate>
		<dc:creator>Paul Houle</dc:creator>
				<category><![CDATA[Asynchronous Communications]]></category>
		<category><![CDATA[GWT]]></category>
		<category><![CDATA[Silverlight]]></category>

		<guid isPermaLink="false">http://gen5.info/q/?p=41</guid>
		<description><![CDATA[Introduction Many people have independely discovered a new design pattern, the &#8220;Multiton&#8221;, which, like the &#8220;Singleton&#8221; is an initialization pattern in the style of the Design Patterns book. Like the Singleton, the Multiton provides a method that controls the construction of a class: instead of maintaining a single copy of an object in an address [...]]]></description>
			<content:encoded><![CDATA[<h2>Introduction</h2>
<p>Many people have independely discovered a new design pattern,  the &#8220;Multiton&#8221;,  which,  like the &#8220;Singleton&#8221; is an initialization pattern in the style of the Design Patterns book.  Like the Singleton,  the Multiton provides a method that controls the construction of a class:  instead of maintaining a single copy of an object in an address space,  the Multiton maintains a Dictionary that maps keys to unique objects.</p>
<p>The Multiton pattern can be used in systems that store persistent data in a back-end store,  such as a relational databases.  The Multiton pattern can be used to maintain a set of objects are mapped to objects (rows) in a persistent store:  it applies obviously to object-relational mapping systems,  and is also useful in asynchronous RIA&#8217;s,  which need to keep track of user interface elements that are interested in information from the server.</p>
<p><a href="http://gen5.info/q/wp-content/uploads/2008/07/multitondiagram.png"><img title="multitondiagram" src="http://gen5.info/q/wp-content/uploads/2008/07/multitondiagram.png" alt="" /></a></p>
<p>An alternate use case of Mulitons,  seen in the &#8220;<a href="http://en.wikipedia.org/wiki/PureMVC">Multicore</a>&#8221; version of the PureMVC framework,  is the extension of the Singleton pattern to support multiple instances of a system in a single address space.</p>
<p>As useful as the Multiton pattern is,  this article explains how Multitons use references in a way that doesn&#8217;t work well with conventional garbage collection.  Multitons are a great choice when the number of Multitons is small,  but they may leak memory unacceptablely when more than a few thousand are created.  Future posts will describe patterns,  such as the Captive Multiton,  that provide the same capabilities with more scalable memory management &#8212; subscribe to our <a href="http://feeds.feedburner.com/Generation5">RSS feed</a> to keep informed.</p>
<h2><span id="more-41"></span>Use of a Multiton in An Asynchronous Application</h2>
<p>In our last article on <a href="http://gen5.info/q/2008/07/18/the-role-of-the-model-in-silverlight-gwt-and-javascript/">Model-View Separation in Asynchronous RIA&#8217;s</a>,   we used a Singleton object that represented an entire table in a relational database.  This object maintained a list of listerners that were interested in the contents of a table.  In this case,  the amount of information in the table was small,  and often used in the aggregate,   so retreiving a complete copy of the table was a reasonable level of granularity.  We could imagine a situation,  however,  where the number of records and size of the records is enough that we need to transfer records individually.  (This specific case is an outline of an implementation for Silverlight:  a GWT implementation would be similar &#8212; details specific to GWT are talked about in <a href="http://gen5.info/q/2008/07/18/the-role-of-the-model-in-silverlight-gwt-and-javascript/">a previous post</a>.)</p>
<p>Imagine,  for instance,  a <em>BlogPosting</em> object,  which represents a post in a blog,  which in turn has an integer primary key.  The BlogPosting object is a multiton,  so you&#8217;d write</p>
<pre>[01] var posting=BlogPosting.GetInstance(postId);</pre>
<p>to get the instance of <em>BlogPosting</em> that corresponds to <em>postId</em>.  Client objects can&#8217;t really write something like</p>
<pre>[02] TitleField.Text=posting.Title</pre>
<p>because the operation of retrieving text from an the server is asynchronous,  and won&#8217;t return in time to return a value,  either on line [01] or [02].  More reasonably,  a <em>BlogPostingViewer</em> can register itself against a <em>BlogPosting</em> instance so it will be notified when information is available about the blog posting.</p>
<pre>[03] public class BlogPostingViewer: UserControl,IBlogPostingListener {
[04]     protected int PostId;
[05]
[06]     public BlogPostViewer(int postId) {
[07]        PostId=postId;
[08]        BlogPosting.GetInstance(postId).AddListener(this);
[09]     }
[10]
[11]     public void Dispose() {
[12]        BlogPosting.GetInstance(postId).RemoveListener(this);
[13]        super.Dispose();
[14]     }</pre>
<p>This example shows a pattern usable in a Silverlight applicaton,  unlike the GWT style in the <a href="http://gen5.info/q/2008/07/18/the-role-of-the-model-in-silverlight-gwt-and-javascript/">model-view article</a>.  The <em>Dispose()</em> method will need to be called manually when the <em>BlogPostingViewer</em> is no longer needed,  since it will never be garbage collected so long as a reference to it inside the <em>BlogPosting</em> exists.  (This points to a general risk of memory leaks with Multitons that we&#8217;ll talk about later.)  This problem can be addre</p>
<p>The <em>BlogPostingViewer</em> goes on to implement the <em>IBlogPostingListener</em> interface,  updating the visual appearance of the user interface to reflect information from the UI:</p>
<pre>[15]     public void UpdatePosting(BlogPostingData d) {
[16]         if (d==null) {
[17]            ClearUserInterface();   // user-defined method blanks out UI
[18]            return
[19]         }
[20]         TitleField.Text=d.Title;
[21]         ...
[22]     }
}</pre>
<p>We assume that <em>BlogPostingData</em> represents the state of the <em>BlogPosting</em> at a moment in time,  distinct from the <em>BlogPosting</em>,  which represents the <em>BlogPosting</em> as a persistent object.  <em>BlogPostingData</em> might (roughly) correspond to the the columns of a relational table and look something like:</p>
<pre>[23] public class BlogPostingData {
[24]    public string Title { get; set;}
[25]    public Contributor Author { get; set; }
[26]    public string Body { get; set;}
[27]    public Category[] AssociatedCategories { get; set;}
[28]    ...
[29] }</pre>
<p>We could then add a <em>BlogPostingViewer</em> to the user interface and schedule it&#8217;s initialization by writing</p>
<pre>[30] var viewer=new BlogPostingViewer(PostId);
[31] OuterControl.Children.Add(viewer);
[32] BlogPosting.GetInstance(PostId).Fetch();</pre>
<p>Note that line [32] tells the <em>BlogPosting</em> instance to retreive a copy of the posting from the server (an instance of <em>BlogPostingData</em>) and call <em>UpdatePosting()</em> on all of the listeners.  Therefore,  there will be a time between line [30] and the time when the async call started on line [32] gets back when the <em>BlogPostingViewer</em> is empty (not initialized with <em>BlogPostingData</em>.)  Therfore,  the <em>BlogPostingViewer</em> must be designed so that nothing bad happens when it&#8217;s in that state:  it has to show something reasonable to user and not crash the app if the user clicks a button that isn&#8217;t ready yet.</p>
<p>(In a more developed application,  the <em>BlogPosting</em> could keep a cache of the latest <em>BlogPostingData</em>:  this could improve responsiveness by updating the <em>BlogPostingViewer</em> at the moment it registers,  or by doing a timestamp or checksum stamp against the server to reduce the bandwidth requirements of a <em>Fetch()</em>,  just watch out for the <a href="http://gen5.info/q/2008/04/21/once-asynchronous-always-asynchronous/">unintended consequences of multiple code paths</a>.)</p>
<h2>Implementing a Muliton</h2>
<p>Here&#8217;s an implementation of a Multiton in C# that&#8217;s not too different from the <a href="http://gen5.info/q/2008/04/21/once-asynchronous-always-asynchronous/">Java implementation from Wikipedia</a>.</p>
<pre>class BlogPosting {
    #region Initialization
    private static readonly Dictionary&lt;int,BlogPosting&gt; _Instances =
       new Dictionary&lt;int,BlogPosting&gt;();

    private BlogPosting(int key) {
        ... construct the object ...
    }

    public static BlogPosting GetInstance(int key) {
        lock(_Instances) {
            BlogPosting instance;
            if (_Instances.TryGetValue(key,out instance)) {
                return instance;
            }</pre>
<pre>            instance = new BlogPosting(key);
            _Instances.Add(key, instance);
            return instance;
        }
    }
    #endregion

    ... the rest of the class ...

}</pre>
<p>I&#8217;m pretty sure that a  version of this could be created in C# with slightly sweeter syntax that would look like</p>
<p>BlogPosting.Instance[postId]</p>
<p>but this doesn&#8217;t address the weak implementation of  static inheritence in many popular languages that requires us to cut-and-paste roughly 20 lines of code for each Multiton class,  rather than being able to reuse inheritence logic.  The Ruby Applications Library,  on the other hand,  contains a <a href="http://raa.ruby-lang.org/project/multiton/">Multiton</a> class that can be used to bolt Multiton behavior onto a class.  It would be interesting to see what could be accomplished with PHP 5.3&#8242;s <a href="http://www.colder.ch/news/08-24-2007/28/late-static-bindings-expl.html">late static binding</a>.</p>
<h2>Multitons And Memory Leaks</h2>
<p>Multitons,  unfortunately,  don&#8217;t interact well with garbage collectors.  Once a Multiton is created,  the static <em>_Instances</em> array will maintain a reference to every Multiton in the system,  so that Multitons won&#8217;t be collected,  even if  no active references exist.</p>
<p>You might think you could manually remove Multitons from the <em>_Instances</em> list,  but this won&#8217;t be entirely reliable.  In the case above,  each <em>BlogPosting </em>maintains a list of <em>IBlogPostingListeners</em>.  You could,  in principle,  scavenge <em>BlogPostings</em> with an empty set of listerners,  but that doesn&#8217;t stop a class from squirreling away a copy of a <em>BlogPosting</em> that will later conflict with a new BlogPosting that somebody creates by using <em>BlogPosting.GetInstance()</em>.</p>
<p><em>WeakReferences</em>,  as available in dot-Net and the full Java platform (as opposed to GWT),  are not an answer to this problem,  because references work backwards in this case:  a <em>BlogPosting</em> is collectable if (i) no references to the <em>BlogPosting</em> exist outside the <em>_Instances</em> array,  and (ii) a <em>BlogPosting </em>doesn&#8217;t hold references to other objects that may need to be updated in the future.</p>
<p>The severity of this issue depends on the number of Multitons created and the size of the Mulitons.  If the granularity of Multitons is coarse,  and you&#8217;ll only create five of them,  there&#8217;s no problem.  1000 Multitons that each consume 1 kilobyte will consume about a megabyte of RAM,  which is inconsequential for most applications these days.  However,  this amounts to a scaling issue:  an application that works fine when it creates 50 Mulitons could break down when it creates 50,000.</p>
<p>One answer to this problem is to restrict access to Muliton so that:  (i) references to Multitons can&#8217;t be saved by arbitrary objects and (ii) manages Multitons with a kind of reversed reference count,  so that Multitons are discared when they no longer hold useful informaton.  I call this a <em>Captive Multiton</em>,  and this will be the subject of our next exciting episode:  <a href="http://feeds.feedburner.com/Generation5">subscribe to our RSS feed </a>so you won&#8217;t miss it.</p>
<h2>More Information About Multitons</h2>
<p>So far as I can tell,  Multitons have been independently discovered by many developers in recent years.  I used Multitons (I called them &#8220;Parameterized Singleons&#8221;) in the manner above in a GWT application that I developed in summer 2007.  <a href="http://en.wikipedia.org/wiki/PureMVC">The PureMVC Framework uses Multitons</a> to allow multiple instances of the framework to exist in an address space.   A <a href="http://raa.ruby-lang.org/project/multiton/">reusable Multiton implementation</a> exists in Ruby.</p>
<h2>Conclusion</h2>
<p>The Muliton Pattern is an initialization pattern in the sense defined in the notorious &#8220;Design Patterns&#8221; Book.  Mulitons are like Singletons in that they use static methods to control access to a private constructor,  but instead of maintaining a single copy of an object in an address space,  a Multiton maintains a mapping from key values to objects.  A number of uses are emerging for mulitons:  (i) Multitons are useful when we want to use something like the Singleton pattern,  but support multiple named instances of a system in an an address space and (ii) Multitons can be a useful representation of an object in a persistent store,  such as a relational database.  Multitons,  however,  are not collected properly by conventional garbage collectors:  this is harmless for applications that create a small number of mulitons,  but poses a scaling problem when Multitons are used to represent a large number of objects of fine granularity &#8212; a future posting will introduce a Captive Multiton that solves this problem:  <a href="http://feeds.feedburner.com/Generation5">subscribe to our RSS feed</a> to follow this developing story.</p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fgen5.info%2fq%2f2008%2f07%2f25%2fthe-multiton-design-pattern%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fgen5.info%2fq%2f2008%2f07%2f25%2fthe-multiton-design-pattern%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://gen5.info/q/2008/07/25/the-multiton-design-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
