<?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/"
  >

<channel>
  <title>CodeGear TeamB Blogs Master Site Feed</title>
  <link>http://blogs.teamb.com/feeds</link>
  <description>Shows all posts, comments, and pages from all blogs on this WPMU powered site</description>
  <pubDate>Fri, 21 Nov 2008 22:01:48 +0000</pubDate>
  <generator>http://wordpress.org/?v=2.6.2</generator>
  <language>en</language>
  <item>
    <title>A Proof of the Undecidability of the Halting Problem, In Verse</title>
    <link>http://blogs.teamb.com/craigstuntz/2008/11/21/37850/</link>
    <comments>http://blogs.teamb.com/craigstuntz/2008/11/21/37850/#comments</comments>
    <pubDate>Fri, 21 Nov 2008 22:01:48 +0000</pubDate>
    <dc:creator>Craig Stuntz</dc:creator>
    
		<category><![CDATA[General Software Development]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/craigstuntz/?p=37850</guid>
    <description><![CDATA[Well, the title of this post pretty much tells the story; Geoffrey K. Pullum has published a proof that the Halting Problem is undecidable, in verse.  Here&#8217;s an excerpt:
Here’s the trick that I’ll use – and it’s simple to do.
I’ll define a procedure, which I will call Q,
that will use P’s predictions of halting success
to [...]]]></description>
      <content:encoded><![CDATA[<p>Well, the title of this post pretty much tells the story; Geoffrey K. Pullum has published a proof that the Halting Problem is undecidable, in verse.  Here&#8217;s an excerpt:</p>
<blockquote><p>Here’s the trick that I’ll use – and it’s simple to do.<br />
I’ll define a procedure, which I will call <em>Q</em>,<br />
that will use <em>P</em>’s predictions of halting success<br />
to stir up a terrible logical mess.</p></blockquote>
<p>Do read <a href="http://ling.ed.ac.uk/~gpullum/loopsnoop.pdf">the whole thing</a>, as it actually does contain a peer-reviewed proof.</p>
<p>Personally, I find rhyme and meter to be underused tools in the fields of mathematics and computer science. I suspect that most programmers don&#8217;t read technical journals at all; making the research more entertaining can only help the field. Then again, <a href="http://blogs.msdn.com/oldnewthing/archive/2007/11/13/6157507.aspx#6178257">I&#8217;ve been known to cancel spam in verse</a>, so my opinion may be outside of the mainstream.</p>
<p>So anyway, I&#8217;m off to adapt Beowulf into a proof in epic verse of the <a href="http://mathworld.wolfram.com/Taniyama-ShimuraConjecture.html">Taniyama–Shimura conjecture</a>.  I&#8217;m still dithering over whether to base my adaptation on <a href="http://www.wwnorton.com/college/english/nael/beowulf/introbeowulf.htm">Seamus Heaney&#8217;s translation</a>, or <a href="http://beowulf.engl.uky.edu/~kiernan/ENG619/eBeowulf-ed/ed/ed.htm">the original, Old English</a>.</p>
<p class="akst_link"><a href="http://blogs.teamb.com/craigstuntz/?p=37850&amp;akst_action=share-this" onclick="akst_share('37850', 'http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F11%2F21%2F37850%2F', 'A+Proof+of+the+Undecidability+of+the+Halting+Problem%2C+In+Verse'); return false;" title="Post to del.icio.us, etc." id="akst_link_37850" class="akst_share_link" rel="nofollow">Share This</a> | <a href="mailto:?subject=A%20Proof%20of%20the%20Undecidability%20of%20the%20Halting%20Problem%2C%20In%20Verse&body=Have you seen this? http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F11%2F21%2F37850%2F" id="akst_email_37850" class="akst_share_email" rel="nofollow">Email this page to a friend</a></p>]]></content:encoded>
      <wfw:commentRss></wfw:commentRss>
    </item>
  <item>
    <title>My CodeRage Presentation: Functional Programming in Delphi 2009</title>
    <link>http://blogs.teamb.com/craigstuntz/2008/11/04/37845/</link>
    <comments>http://blogs.teamb.com/craigstuntz/2008/11/04/37845/#comments</comments>
    <pubDate>Tue, 04 Nov 2008 20:22:56 +0000</pubDate>
    <dc:creator>Craig Stuntz</dc:creator>
    
		<category><![CDATA[CodeRage]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/craigstuntz/?p=37845</guid>
    <description><![CDATA[
I&#8217;ll be speaking at the CodeRage III virtual conference, on the subject of functional programming in Delphi 2009.  Here&#8217;s the (rather bland) abstract:
Delphi 2009 includes several new features well-suited to a functional style of programming.  We&#8217;ll explore the use of generics, anonymous methods, and new RTL types while introducing concepts from functional programming.
If you&#8217;ve been [...]]]></description>
      <content:encoded><![CDATA[<p><a href="http://conferences.codegear.com/coderage08"><img src="http://conferences.codegear.com/coderage08/article/38867/images/38867/03000001.png" alt="CodeRage 2008 logo" /></a></p>
<p>I&#8217;ll be speaking at the CodeRage III virtual conference, on the subject of functional programming in Delphi 2009.  Here&#8217;s the (rather bland) abstract:</p>
<blockquote><p>Delphi 2009 includes several new features well-suited to a functional style of programming.  We&#8217;ll explore the use of generics, anonymous methods, and new RTL types while introducing concepts from functional programming.</p></blockquote>
<p>If you&#8217;ve been following my blog over the past few months, you might have <a title="Implementing Memoize in Delphi 2009" href="http://blogs.teamb.com/craigstuntz/2008/10/01/37839">a fair idea of what to expect</a>.  As you can tell from the somewhat vague abstract, I&#8217;m still rounding out the details of the presentation.  If there&#8217;s anything you&#8217;d like to see me cover, please make your suggestion in comments.</p>
<p class="akst_link"><a href="http://blogs.teamb.com/craigstuntz/?p=37845&amp;akst_action=share-this" onclick="akst_share('37845', 'http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F11%2F04%2F37845%2F', 'My+CodeRage+Presentation%3A+Functional+Programming+in+Delphi+2009'); return false;" title="Post to del.icio.us, etc." id="akst_link_37845" class="akst_share_link" rel="nofollow">Share This</a> | <a href="mailto:?subject=My%20CodeRage%20Presentation%3A%20Functional%20Programming%20in%20Delphi%202009&body=Have you seen this? http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F11%2F04%2F37845%2F" id="akst_email_37845" class="akst_share_email" rel="nofollow">Email this page to a friend</a></p>]]></content:encoded>
      <wfw:commentRss></wfw:commentRss>
    </item>
  <item>
    <title>LINQ to SQL : Entity Framework :: WinForms : WPF</title>
    <link>http://blogs.teamb.com/craigstuntz/2008/11/03/37844/</link>
    <comments>http://blogs.teamb.com/craigstuntz/2008/11/03/37844/#comments</comments>
    <pubDate>Mon, 03 Nov 2008 16:29:21 +0000</pubDate>
    <dc:creator>Craig Stuntz</dc:creator>
    
		<category><![CDATA[.NET]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/craigstuntz/2008/11/03/37844</guid>
    <description><![CDATA[Microsoft has announced their intention to "de-emphasize" LINQ to SQL, and guided us to use the Entity Framework, instead. This is not too surprising, considering that LINQ to SQL was never supposed to exist in the first place. But, just like with WinForms, a lot of people have used LINQ to SQL in production code [...]]]></description>
      <content:encoded><![CDATA[<p>Microsoft has announced their intention to <a href="http://blogs.msdn.com/adonet/archive/2008/10/29/update-on-linq-to-sql-and-linq-to-entities-roadmap.aspx">"de-emphasize" LINQ to SQL, and guided us to use the Entity Framework, instead</a>. This is not too surprising, considering that <a href="http://blogs.msdn.com/mattwar/archive/2007/05/31/the-origin-of-linq-to-sql.aspx" title="The Origin of LINQ to SQL">LINQ to SQL was never supposed to exist in the first place</a>. But, just like with WinForms, a lot of people have used LINQ to SQL in production code in no small part because the preferred solution wasn&#8217;t ready yet, and LINQ to SQL includes features which are not in the current released version of the Entity Framework.</p>
<p>This speaks to the importance of abstracting data access.  The nice thing about object relational mapping is that once you&#8217;ve read the data, your data are just objects, whether or not they&#8217;re POCOs. You can and should emphasize this encapsulation by hiding the reading and writing behind a framework such as the <a href="http://martinfowler.com/eaaCatalog/repository.html">Repository pattern</a>.  It is, IMHO, a mistake to ever call something like Context.SaveChanges inside of a controller.</p>
<p class="akst_link"><a href="http://blogs.teamb.com/craigstuntz/?p=37844&amp;akst_action=share-this" onclick="akst_share('37844', 'http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F11%2F03%2F37844%2F', 'LINQ+to+SQL+%3A+Entity+Framework+%3A%3A+WinForms+%3A+WPF'); return false;" title="Post to del.icio.us, etc." id="akst_link_37844" class="akst_share_link" rel="nofollow">Share This</a> | <a href="mailto:?subject=LINQ%20to%20SQL%20%3A%20Entity%20Framework%20%3A%3A%20WinForms%20%3A%20WPF&body=Have you seen this? http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F11%2F03%2F37844%2F" id="akst_email_37844" class="akst_share_email" rel="nofollow">Email this page to a friend</a></p>]]></content:encoded>
      <wfw:commentRss></wfw:commentRss>
    </item>
  <item>
    <title>Transforming Models</title>
    <link>http://blogs.teamb.com/craigstuntz/2008/10/30/37843/</link>
    <comments>http://blogs.teamb.com/craigstuntz/2008/10/30/37843/#comments</comments>
    <pubDate>Thu, 30 Oct 2008 17:48:45 +0000</pubDate>
    <dc:creator>Craig Stuntz</dc:creator>
    
		<category><![CDATA[General Software Development]]></category>

		<category><![CDATA[Web]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/craigstuntz/2008/10/30/37843</guid>
    <description><![CDATA[In my last post, "&#8216;Model&#8217; Is an Overloaded Word," I discussed several types of models which might be present in an MVC application. But I limited the discussion to models which are actually in the executable.  There may of course be additional models, such as ERDs, UML models, etc., which exist in the development environment, [...]]]></description>
      <content:encoded><![CDATA[<p>In my last post, "<a href="http://blogs.teamb.com/craigstuntz/2008/10/28/37842">&#8216;Model&#8217; Is an Overloaded Word</a>," I discussed several types of models which might be present in an MVC application. But I limited the discussion to models which are actually in the executable.  There may of course be additional models, such as <acronym title="Entity Relationship Diagram">ERD</acronym>s, UML models, etc., which exist in the development environment, but are not actually part of the executable.</p>
<p>It is often the case that we use software tools to transform these conceptual models into executable code of one form or another.  For example, a database management tool may know how to transform an ERD into physical database metadata.  A UML design surface might know how to transform a UML model into compilable code.  Most object-relational mappers designed for non-dynamic languages such as C# and Java seem to work by transforming some kind of schema file, usually XML, into compilable code.  And so on&#8230;</p>
<p>Inside the application, at runtime, a similar transformation of models occurs.  Let&#8217;s examine the pipeline which results in transforming data in a database into HTML which a user can view:</p>
<ol>
<li>The user invokes an action.  This starts a chain of events ultimately resulting in a call to the database server in the form of an SQL statement.  The database server transforms its will on-disk representation of the data into a result set understandable by the data access components.</li>
<li>The object-relational mapping transforms the result set into entity instances — instances of classes in a form useful to implementers of business logic.</li>
<li>If the application is using the Repository pattern, these entity instances may be passed directly to the controller.  Or they may be transformed into lightweight data access objects.</li>
<li>Whatever their form, the entity instances will be wrapped up into a model containing all of the information required to render a view.</li>
<li>The view will transform the entities into a different kind of model: HTML.</li>
<li>The browser will transform the HTML into a DOM which can be further manipulated via JavaScript.</li>
</ol>
<p>A similar series of transformations between model types occurs when we accept user input and store it back in the database.</p>
<p>These series of transformations are not so different from the transformations I mentioned above, like transforming a UML model into executable code.  Indeed, compilation itself is just another kind of model transformation, changing a representation which is (hopefully!) readable by a developer into a representation readable by a machine.  If the transformation is lossless, then it can probably be done in both directions.</p>
<p>So one way to look at an application is as a series of transformations from one model type to another, not only in execution, but also in the manner in which the application itself is built. However, the transformations are performed with wildly different implementations:</p>
<ul>
<li>A special-purpose executable (e.g., a compiler) can be used to transform the models. Such executables are typically fairly limited; most compilers support only one language, and do not, for example, transform UML models into code.</li>
<li> We can write code in a high-level language to transform the models, often in a way which is dependent on the specific types or properties involved (e.g, A.Foo = b.Foo), or possibly at a more generic level, such as with a common interface.</li>
<li>We can create informally-specified principles for model transformation, such as "<a href="http://en.wikipedia.org/wiki/Convention_over_Configuration">convention over configuration</a>," which are often sufficient to completely specify the transformation without requiring code.</li>
<li>We can create systems of rules for model transformation. The formal name for such a system of rules is an <a href="http://mathworld.wolfram.com/Algebra.html">algebra</a>, not to be confused with the <a href="http://en.wikipedia.org/wiki/Elementary_algebra">elementary algebra</a> you learned in high school. This is a set of simple rules designed to be composed into more advanced transformations. One such system is <a href="http://www.vocw.vn/content/m10536/latest/">relational algebra</a>, which surfaces (in a heavily mutilated form) in SQL databases.</li>
</ul>
<p>Now, my purpose in this post is not to claim that one of these methods is superior to the others.  "The best tool for the job" still applies.  The idea of model transformation, however, encompasses more parts of a software system than many programmers commonly suppose.  The notion of treating your source code as a model which can be transformed via an algebra into an equivalent, but faster and provably correct, application <a href="http://www.stanford.edu/class/cs242/readings/backus.pdf" title="Can Programming Be Liberated from the von Neumann Style?  A Functional Style and Its Algebra of Programs">is not new</a>, but is perhaps surprising to programmers who have not studied functional programming. So the question is not "How do I create an instance of Bar from an instance of Foo?," but "What kind of transformation is this, and how does it fit into the context of the other transformations I&#8217;m performing in this application?"</p>
<p>Such a worldview makes technologies like Haskell&#8217;s monads and LINQ, designed as generic solutions for the problem of transforming one type of set into another, even more interesting than they already are.</p>
<p class="akst_link"><a href="http://blogs.teamb.com/craigstuntz/?p=37843&amp;akst_action=share-this" onclick="akst_share('37843', 'http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F10%2F30%2F37843%2F', 'Transforming+Models'); return false;" title="Post to del.icio.us, etc." id="akst_link_37843" class="akst_share_link" rel="nofollow">Share This</a> | <a href="mailto:?subject=Transforming%20Models&body=Have you seen this? http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F10%2F30%2F37843%2F" id="akst_email_37843" class="akst_share_email" rel="nofollow">Email this page to a friend</a></p>]]></content:encoded>
      <wfw:commentRss></wfw:commentRss>
    </item>
  <item>
    <title>"Model" Is an Overloaded Word</title>
    <link>http://blogs.teamb.com/craigstuntz/2008/10/28/37842/</link>
    <comments>http://blogs.teamb.com/craigstuntz/2008/10/28/37842/#comments</comments>
    <pubDate>Tue, 28 Oct 2008 14:44:59 +0000</pubDate>
    <dc:creator>Craig Stuntz</dc:creator>
    
		<category><![CDATA[General Software Development]]></category>

		<category><![CDATA[Web]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/craigstuntz/2008/10/28/37842</guid>
    <description><![CDATA[Let&#8217;s say you&#8217;re writing a web application, and using the Model View Controller design.  Maybe you&#8217;re using an out-of-the-box framework like the ASP.NET MVC Framework or Rails, or maybe you&#8217;re using a different implementation; it doesn&#8217;t matter.  It&#8217;s pretty obvious that the "View" portion of the design is the part which provides a template for [...]]]></description>
      <content:encoded><![CDATA[<p>Let&#8217;s say you&#8217;re writing a web application, and using the Model View Controller design.  Maybe you&#8217;re using an out-of-the-box framework like the ASP.NET MVC Framework or Rails, or maybe you&#8217;re using a different implementation; it doesn&#8217;t matter.  It&#8217;s pretty obvious that the "View" portion of the design is the part which provides a template for rendered HTML, and that the "Controller" portion of the design is the part which handles requests, specifying the general outline for what should be returned to the user.  But what about the "Model?"</p>
<p>Most non-trivial applications have many different models, and for good reason.  If the application uses a relational database, it will have a relational model.  A non-trivial web application may use an application server, containing an entity model with an object-relational mapping, perhaps based on a framework like the Entity Framework or NHibernate.  In some designs, these entity types are not exposed from the application server, but rather represented as lightweight <a href="http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html">data access objects</a>.  These data access objects are made available to clients of the application server, such as a web application.</p>
<p>Inside the web application, it&#8217;s possible that the lightweight data access objects will be made available directly to the View, without being wrapped up inside any other type.  But it&#8217;s more likely that additional information will need to be passed to the View, requiring the use of an additional model type, which wraps up the information required by a particular View.  Or, a View might require a different representation of the data access objects, such as XML or JSON.</p>
<p>So let&#8217;s count the different types of "Models" I&#8217;ve listed so far:</p>
<ol>
<li>Relational data model</li>
<li>Entity model, perhaps with an object-relational mapping</li>
<li>Lightweight data access objects</li>
<li>View-specific models</li>
</ol>
<p>To be clear, I don&#8217;t think the existence of multiple types of models is by itself a problem.  But I do think that the overloading of the term create some confusion about how to follow the MVC application design.</p>
<p>When you create a new ASP.NET MVC web application, Visual Studio creates a Solution containing a single project for the web application itself, with a folder called Models.  Many of the demonstrations of ASP.NET MVC projects that I&#8217;ve seen drop a LINQ-to-SQL model inside of this folder.  I understand that people like to keep their demonstrations simple, but as a rule I think that any type of object-relational model should be in a separate assembly from the web application, along with any business logic implementation required.  This second assembly becomes the API for your data which the web application will use.  It can be a web service, or an assembly which exposes methods for accessing the data directly, e.g. with the <a href="http://martinfowler.com/eaaCatalog/repository.html">Repository pattern</a>. However, I keep the Models folder in the web application, and use it for "View models," which handle things like pagination, aggregation of multiple instances required by the view, etc.</p>
<p>Maybe MVC should stand for Model<strong>s</strong> View Controller?</p>
<p>In the second part of this series, I will examine additional types of models, and <a href="http://blogs.teamb.com/craigstuntz/2008/10/30/37843" title="Transforming Models">the general problem of transforming one model into another</a>.</p>
<p class="akst_link"><a href="http://blogs.teamb.com/craigstuntz/?p=37842&amp;akst_action=share-this" onclick="akst_share('37842', 'http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F10%2F28%2F37842%2F', '%22Model%22+Is+an+Overloaded+Word'); return false;" title="Post to del.icio.us, etc." id="akst_link_37842" class="akst_share_link" rel="nofollow">Share This</a> | <a href="mailto:?subject=%22Model%22%20Is%20an%20Overloaded%20Word&body=Have you seen this? http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F10%2F28%2F37842%2F" id="akst_email_37842" class="akst_share_email" rel="nofollow">Email this page to a friend</a></p>]]></content:encoded>
      <wfw:commentRss></wfw:commentRss>
    </item>
  <item>
    <title>Database Workbench Lite for InterBase</title>
    <link>http://blogs.teamb.com/craigstuntz/2008/10/20/37841/</link>
    <comments>http://blogs.teamb.com/craigstuntz/2008/10/20/37841/#comments</comments>
    <pubDate>Mon, 20 Oct 2008 20:53:50 +0000</pubDate>
    <dc:creator>Craig Stuntz</dc:creator>
    
		<category><![CDATA[Databases]]></category>

		<category><![CDATA[InterBase]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/craigstuntz/2008/10/20/37841</guid>
    <description><![CDATA[Martijn Tonies e-mailed me to inform me of the release of Database Workbench Lite for InterBase.  It&#8217;s a free version of Database Workbench, a full-featured administration tool for InterBase and other database servers.  You can compare the "lite" and "professional" feature sets here. Upscene had also just released version 3.2 of Database Workbench Professional.
Share This [...]]]></description>
      <content:encoded><![CDATA[<p>Martijn Tonies e-mailed me to inform me of the <a href="http://www.upscene.com/index.htm?./news/20081020b.htm">release</a> of <a href="http://www.upscene.com/index.htm?./products/dbw/index.htm">Database Workbench Lite for InterBase</a>.  It&#8217;s a free version of Database Workbench, a full-featured administration tool for InterBase and other database servers.  You can <a href="http://www.upscene.com/documentation/dbw3/index.html?gs_editions.htm">compare the "lite" and "professional" feature sets here</a>. Upscene had also just released version 3.2 of Database Workbench Professional.</p>
<p class="akst_link"><a href="http://blogs.teamb.com/craigstuntz/?p=37841&amp;akst_action=share-this" onclick="akst_share('37841', 'http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F10%2F20%2F37841%2F', 'Database+Workbench+Lite+for+InterBase'); return false;" title="Post to del.icio.us, etc." id="akst_link_37841" class="akst_share_link" rel="nofollow">Share This</a> | <a href="mailto:?subject=Database%20Workbench%20Lite%20for%20InterBase&body=Have you seen this? http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F10%2F20%2F37841%2F" id="akst_email_37841" class="akst_share_email" rel="nofollow">Email this page to a friend</a></p>]]></content:encoded>
      <wfw:commentRss></wfw:commentRss>
    </item>
  <item>
    <title>OpenCTF - Component Test Framework</title>
    <link>http://blogs.teamb.com/craigstuntz/2008/10/15/37840/</link>
    <comments>http://blogs.teamb.com/craigstuntz/2008/10/15/37840/#comments</comments>
    <pubDate>Wed, 15 Oct 2008 18:36:19 +0000</pubDate>
    <dc:creator>Craig Stuntz</dc:creator>
    
		<category><![CDATA[Delphi]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/craigstuntz/2008/10/15/37840</guid>
    <description><![CDATA[In my CodeRage presentation last year, I demonstrated a framework for semi-automatically building unit tests of Delphi components.  I left the project very much in an alpha state, and haven&#8217;t had time to return to it, as other things are taking up my time recently.  I still think, however, that the concept of automatically generating [...]]]></description>
      <content:encoded><![CDATA[<p>In my CodeRage presentation last year, I demonstrated <a href="http://cc.codegear.com/Item/25266">a framework for semi-automatically building unit tests of Delphi components</a>.  I left the project very much in an alpha state, and haven&#8217;t had time to return to it, as other things are taking up my time recently.  I still think, however, that the concept of automatically generating test cases is a good one.</p>
<p>So I&#8217;d like to note another project which uses the same general concept in a very different manner.  <a href="http://www.mikejustin.com/products.html#item_261">OpenCTF </a>is a free framework which generates DUnit test cases by looking for certain "known" errors in arbitrary components.</p>
<p>Delphi&#8217;s relatively limited introspection/RTTI features restrict how far you can go with projects like this.  It&#8217;s really only possible to automatically test published properties and published methods with known signatures.  Likewise, most of the Delphi-aware automated testing tools require that you change your application to include special testing interfaces in order to get full functionality from the tool. One of the benefits of enhanced RTTI in the future would be more options for automated testing.</p>
<p class="akst_link"><a href="http://blogs.teamb.com/craigstuntz/?p=37840&amp;akst_action=share-this" onclick="akst_share('37840', 'http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F10%2F15%2F37840%2F', 'OpenCTF+-+Component+Test+Framework'); return false;" title="Post to del.icio.us, etc." id="akst_link_37840" class="akst_share_link" rel="nofollow">Share This</a> | <a href="mailto:?subject=OpenCTF%20-%20Component%20Test%20Framework&body=Have you seen this? http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F10%2F15%2F37840%2F" id="akst_email_37840" class="akst_share_email" rel="nofollow">Email this page to a friend</a></p>]]></content:encoded>
      <wfw:commentRss></wfw:commentRss>
    </item>
  <item>
    <title>Implementing Memoize in Delphi 2009</title>
    <link>http://blogs.teamb.com/craigstuntz/2008/10/01/37839/</link>
    <comments>http://blogs.teamb.com/craigstuntz/2008/10/01/37839/#comments</comments>
    <pubDate>Wed, 01 Oct 2008 18:30:10 +0000</pubDate>
    <dc:creator>Craig Stuntz</dc:creator>
    
		<category><![CDATA[Delphi]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/craigstuntz/2008/10/01/37839</guid>
    <description><![CDATA[My last series on Delphi 2009&#8217;s generics was self-consciously investigating a corner case.  This post, however, is going to bring us back to Earth very quickly, so prepare for a steep descent!  I&#8217;m going to implement a useful, higher-order function, Memoize, using Delphi 2009&#8217;s generics and anonymous methods.
Memoization is a generic solution to the problem [...]]]></description>
      <content:encoded><![CDATA[<p><a href="http://blogs.teamb.com/craigstuntz/2008/09/09/37833" title="Building a Generic Statistics Library">My last series on Delphi 2009&#8217;s generics</a> was self-consciously investigating a corner case.  This post, however, is going to bring us back to Earth very quickly, so prepare for a steep descent!  I&#8217;m going to implement a useful, higher-order function, <a href="http://en.wikipedia.org/wiki/Memoization">Memoize</a>, using Delphi 2009&#8217;s generics and anonymous methods.</p>
<p>Memoization is a generic solution to the problem of caching function results. The function Memoize accepts a function as an argument and returns a function which does exactly the same thing, except that it caches the results.  Here&#8217;s the prototype:</p>
<blockquote>
<pre><code><strong>class function </strong>Memoize&lt;A, R&gt;(AFunc: TFunc&lt;A, R&gt;): TFunc&lt;A, R&gt;;</code></pre>
</blockquote>
<p>So my version of Memoize will accept any function which takes a single argument of any type, and returns a result of any type. Memoize returns a new function with exactly the same signature. I&#8217;ve often written systems to cache the results of database queries in my older Delphi code.  Lately, I&#8217;ve been using TClientDataSet to do the same thing, but it still results in several lines of code to accomplish what is essentially a single function call.  Memoize allows me to solve this problem one time and use it for as many situations as I can imagine.</p>
<p>Well, almost any function.  Caching is obviously only useful for functions which are referentially transparent, which is another way of saying that their output is completely determined by their input.  You wouldn&#8217;t want a cached version of "Now()" or "Create()", for example. Memoization is most useful when a function performs a lengthy calculation, or queries a database or a web service with a lot of latency.  In order to simulate such a function for the purpose of testing my implementation of Memoize, I&#8217;ve written the following test function:</p>
<blockquote>
<pre><code><strong>class function </strong>TestTMemoize.SlowIncrement(ANum: integer): integer;<strong>
begin
  </strong>Sleep(100); // simulate web service / db access
  Result := ANum + 1;<strong>
end;</strong></code></pre>
</blockquote>
<p>This is useless, but it allows me to distribute a testable version of the project without having any dependency on any specific database or Web service.  Feel free to substitute a more useful function if you try this yourself. <img src='http://blogs.teamb.com/feeds/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> In order to create a memoized version of this function, I just pass it to Memoize, and call the function that is returned instead of the original one:</p>
<blockquote>
<pre><code><strong>procedure </strong>DoStuff;
<strong>var</strong>
  MemoizedFunc: TFunc&lt;integer,integer&gt;;
  iResult: integer;
<strong>begin</strong>
  MemoizedFunc := TMemoize.Memoize&lt;integer,integer&gt;(SlowIncrement);
  iResult := MemoizedFunc(1);
<strong>end</strong>;</code></pre>
</blockquote>
<p>The Memoize function certainly sounds useful, but how could I write such a thing?  Well, I obviously need generics, or my version of Memoize would be limited to functions which only accepted and returned one specific type.  And I need anonymous methods, because that is the only way that I can return new functions at runtime.  Finally, I need some kind of cache to store pairs of arguments and results, so that successive executions with the same argument can find result in the cache.</p>
<p>Let&#8217;s examine the last requirement first.  Delphi 2009&#8217;s Generics.Collections unit includes a TDictionary&lt;TKey,TValue&gt; type which, at first glance, it appears to do what I need.  Unfortunately, it isn&#8217;t lifetime-managed. So I will just subtype Delphi 2009&#8217;s TDictionary&lt;TKey,TValue&gt; and implement a new IDictionary&lt;TKey,TValue&gt; interface I will create.</p>
<p>I will explain why it is important to have a lifetime-managed dictionary in order to implement this function at the end of this post. You can easily understand the rest of the post without grasping this detail, if you&#8217;re willing to take my word on the fact that I need a lifetime-managed list. For the time being, let&#8217;s just continue with the code. Here&#8217;s the full source code for Memoize, which is actually very simple:</p>
<blockquote>
<pre><code><strong>class function</strong> TMemoize.Memoize&lt;A,R&gt;(AFunc: TFunc&lt;A, R&gt;): TFunc&lt;A, R&gt;;
<strong>var</strong>
  Map: IDictionary&lt;A, R&gt;;
<strong>begin</strong>
  Map := TManagedDictionary&lt;A, R&gt;.Create;

  Result := <strong>function</strong>(arg: A): R
  <strong>var</strong>
    FuncResult: R;
  <strong>begin</strong>
    <strong>if </strong>Map.TryGetValue(arg, FuncResult) <strong>then begin</strong>
      Exit(FuncResult);
    <strong>end</strong>;
    FuncResult := AFunc(arg);
    Map.Add(arg, FuncResult);
    Exit(FuncResult);
  <strong>end</strong>;
<strong>end</strong>;</code></pre>
</blockquote>
<p>In Delphi 2009, you can call Exit with an argument in order to return a certain value from a function immediately, as if you had assigned Result and then called Exit without the argument.  Other than that, I don&#8217;t think there is too much to explain about the implementation above.</p>
<p>In order to prove that it works, I wrote a unit test.  The unit test shows that the second execution of a Memoized version of a slow function for the same argument (1) returns the same value and (2) is more than two orders of magnitude faster.  One of the reasons I included this unit test was to demonstrate that unit tests can be used to verify performance goals as well as functional specifications.  In order to profile the function, I&#8217;ve "borrowed" <a href="http://barrkel.blogspot.com/2008/08/anonymous-methods-in-testing-profiling.html" title="Anonymous methods in testing / profiling situations">Barry Kelly&#8217;s useful TBenchmarker class</a>. Here&#8217;s the test:</p>
<blockquote>
<pre><code><strong>procedure</strong> TestTMemoize.TestMemoize;
<strong>var</strong>
  Cold, Warm: Double;
  ColdResult, WarmResult, AnonResult: integer;
  MemoizedSlowInc: TFunc&lt;integer, integer&gt;;
  BenchmarkProc: TProc;
<strong>begin</strong>
  MemoizedSlowInc := TMemoize.Memoize&lt;integer,integer&gt;(SlowIncrement);
  BenchmarkProc := <strong>procedure</strong>()
  <strong>begin</strong>
    AnonResult := MemoizedSlowInc(1);
  <strong>end</strong>;

  // first execution should be slow
  Cold := TBenchmarker.Benchmark(BenchmarkProc, 1, 0);
  ColdResult := AnonResult;
  // next time for same value should be fast
  Warm := TBenchmarker.Benchmark(BenchmarkProc, 1, 0);
  WarmResult := AnonResult;

  CheckEquals(ColdResult, WarmResult);
  CheckTrue(Warm &lt; (Cold / 100));
<strong>end</strong>;</code></pre>
</blockquote>
<p>You can download the <a href="http://cc.codegear.com/item/26106" title="Memoize implementation for Delphi 2009">full source code</a> from CodeCentral.</p>
<p>Finally, here&#8217;s the full explanation for why I needed to create a lifetime-managed dictionary:</p>
<p>Anonymous methods, in every implementation I&#8217;ve ever seen, can "capture" variables in the declaring method.  This means that you can use variables (or method arguments) declared in the method which defines the anonymous method, without passing them as arguments.  But since we are going to return the anonymous function as the result of the defining function, any object referenced in the anonymous function must not be freed by the defining function.  In Delphi 2009, captured variables are captured by reference (this is similar to C#, but different than JavaScript).  Recall that anonymous methods are reference counted.  When an anonymous method captures a variable in the declaring method, it will be freed when there are no more references to the anonymous method, provided that the captured variable is a lifetime-managed type, such as a string, a record, an interface, etc.</p>
<p class="akst_link"><a href="http://blogs.teamb.com/craigstuntz/?p=37839&amp;akst_action=share-this" onclick="akst_share('37839', 'http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F10%2F01%2F37839%2F', 'Implementing+Memoize+in+Delphi+2009'); return false;" title="Post to del.icio.us, etc." id="akst_link_37839" class="akst_share_link" rel="nofollow">Share This</a> | <a href="mailto:?subject=Implementing%20Memoize%20in%20Delphi%202009&body=Have you seen this? http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F10%2F01%2F37839%2F" id="akst_email_37839" class="akst_share_email" rel="nofollow">Email this page to a friend</a></p>]]></content:encoded>
      <wfw:commentRss></wfw:commentRss>
    </item>
  <item>
    <title>CDN Search, Part 3: Search Results</title>
    <link>http://blogs.teamb.com/yaminov/2008/09/24/cdn-search-part-3-search-results/</link>
    <comments>http://blogs.teamb.com/yaminov/2008/09/24/cdn-search-part-3-search-results/#comments</comments>
    <pubDate>Wed, 24 Sep 2008 17:44:19 +0000</pubDate>
    <dc:creator>Yorai Aminov</dc:creator>
    
		<category><![CDATA[CDN]]></category>

		<category><![CDATA[GetPublished]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/yaminov/2008/09/24/cdn-search-part-3-search-results/</guid>
    <description><![CDATA[Previously on this blog: we deployed a new search engine and used background jobs to index content.
When you run a search query on CDN, you&#8217;ll see just below your search results line of text that looks something like this:
Query processed in 375ms (31.25ms server/network, 343.75ms database)
This text describes exactly how long it took to prepare [...]]]></description>
      <content:encoded><![CDATA[<p>Previously on this blog: we <a href="http://blogs.teamb.com/yaminov/2008/09/21/cdn-search-part-1-new-search-engine/">deployed a new search engine</a> and <a href="http://blogs.teamb.com/yaminov/2008/09/23/cdn-search-part-2-background-jobs/">used background jobs</a> to index content.</p>
<p>When you run a search query on CDN, you&#8217;ll see just below your search results line of text that looks something like this:</p>
<p>Query processed in 375ms (31.25ms server/network, 343.75ms database)</p>
<p>This text describes exactly how long it took to prepare the query, run it, retrieve all information required for display from the database, check the visibility of every result, sort the results according to the user&#8217;s preference, and prepare the set of results in the current page for display.</p>
<p>The times I quoted above came from a run of <a href="http://dn.codegear.com/search?qall=TClientDataSet&amp;in=source&amp;sourcelang=cpp&amp;allsites=y">this query</a>, which searches all indexed sites for C++ source code that contains the word "TClientDataSet". The text is slightly inaccurate: although the total processing time was indeed 375ms, there are other valid methods of counting the other times.</p>
<p>The "server/network" time represents the time it took to send the query to Lucene, get the results from the web service, and convert them to classes and records GetPublished can process. Over 95% of that time is used for transferring the results over the network. The rest is taken by the actual search engine on the Lucene server and the result processing code on the server running GetPublished.</p>
<p>Almost everything else GetPublished does with the results involves the database, so we say the rest of the time belongs to "database". However, for large result sets the Lucene engine processing time - and certainly network transfer time - will be longer. GetPublished actually uses that time to execute additional queries, by running the code in multiple threads.</p>
<p>Here&#8217;s the actual processing log from GetPublished for the same query:</p>
<pre>Search expression started
Getting list of sites to include in the search
Search includes one or more GetPublished sites
Retrieving external sites
Search includes one or more external sites
Building Lucene query
Lucene query: +appid:(gp blogs blogsteamb cc qc) AND (cpp.source:(+TClientDataSet))
Search sites: 1,5,7,9,10,11,12
Search thread starting
Retrieving language ID
Retrieving site names
Retrieving visible version IDs
Retrieving staged visible version IDs
Retrieving welcome content types for welcome page queries
Welcome content filter:  IN (26,314,322)
Query completed in 31.25ms
The web service returned in 31.25ms
The search engine ran the query in 0ms
Total number of results: 59
Sorting results by AppID and version ID
Adding information for live versions in search results
Adding information for staged versions in search results
Removing versions that are not visible to the user
Updated number of items in search results: 59
Sorting results for welcome page processing
Query ran before retrieving live welcome versions - retrieving now
Live welcome versions:
Language ID: 1
Country ID: 239
Removing welcome pages that are not visible to the user
Final number of items in search results: 59
Parsing dates for sorting
Sorting results
Creating result list
Updating site names for visible results
Creating article headers for display and loading additional information
Search expression processing completed in 375ms</pre>
<p>As you can see, GetPublished does a lot more than just run the search query. The reason it does so is that it needs to convert the search results - a list of version records - to a list of articles the user can see. Here are some of the things that affect the visibility of articles and versions:</p>
<ol>
<li>Articles can have multiple versions, but only one version per article can be "live" (that is, visible to users).
<li>Articles can be mapped to multiple sites, and have different publishing and expiration dates on each site.
<li>GetPublished supports "staging sites", that use a different set of versions.
<li>Articles are filtered based on the user&#8217;s <a href="http://dn.codegear.com/article/33608">preferred language</a>.
<li>Certain articles may only be visible in <a href="http://blogs.teamb.com/yaminov/2008/04/25/select-your-location/">specific countries or regions</a>.
<li>Articles of a special type, known as a "welcome page", are shown on specific site areas instead of in article lists. On such pages, only one "welcome page" can be visible.</li>
</ol>
<p>The list of results returned by the search web service is trimmed and expanded based on the search criteria, user preferences, and visibility settings:</p>
<ol>
<li>Versions that are not visible to the user are removed from the list.
<li>If an article is mapped to multiple sites that are included in the search, additional result records are created for each site.
<li>Welcome pages that are mapped to multiple area are stored once per site, but all valid links are stored in the result record to be displayed later.
<li>Of multiple welcome pages mapped to a single area, only the one visible by the user is kept.</li>
</ol>
<p>Many of these checks can run concurrently. For example, if the search engine takes a while to process the query, GetPublished retrieves all visible articles and welcome pages from the database. If the engine returns quickly, GetPublished only checks the database for versions that are included in the search results. Similarly, GetPublished tries to reduce the working result set as much as possible. For example, when sorting by site name, GetPublished has to set the site name of every result before sorting and paging. When sorting by other fields, GetPublished waits until the results are sorted and only sets the site name for results that are going to be displayed.</p>
<p class="akst_link"><a href="http://blogs.teamb.com/yaminov/?p=40&amp;akst_action=share-this" onclick="akst_share('40', 'http%3A%2F%2Fblogs.teamb.com%2Fyaminov%2F2008%2F09%2F24%2Fcdn-search-part-3-search-results%2F', 'CDN+Search%2C+Part+3%3A+Search+Results'); return false;" title="Post to del.icio.us, etc." id="akst_link_40" class="akst_share_link" rel="nofollow">Share This</a> | <a href="mailto:?subject=CDN%20Search%2C%20Part%203%3A%20Search%20Results&body=Have you seen this? http%3A%2F%2Fblogs.teamb.com%2Fyaminov%2F2008%2F09%2F24%2Fcdn-search-part-3-search-results%2F" id="akst_email_40" class="akst_share_email" rel="nofollow">Email this page to a friend</a></p>]]></content:encoded>
      <wfw:commentRss></wfw:commentRss>
    </item>
  <item>
    <title>Building a Generic Statistics Library, Part 5: Implementation</title>
    <link>http://blogs.teamb.com/craigstuntz/2008/09/24/37838/</link>
    <comments>http://blogs.teamb.com/craigstuntz/2008/09/24/37838/#comments</comments>
    <pubDate>Wed, 24 Sep 2008 12:55:45 +0000</pubDate>
    <dc:creator>Craig Stuntz</dc:creator>
    
		<category><![CDATA[Delphi]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/craigstuntz/2008/09/24/37838</guid>
    <description><![CDATA[This post is the last in my series on building a statistics library using Delphi 2009’s new generic types.  Having implemented the functions FoldL and Map, and having used FoldL to implement Count and Sum, implementing Average and StandardDeviation are now trivial [...]]]></description>
      <content:encoded><![CDATA[<p>This post is the last in my series on building a statistics library using Delphi 2009’s new generic types.  If you’re new to the series, you might want to start with <a href="http://blogs.teamb.com/craigstuntz/2008/09/09/37833" title="Building a Generic Statistics Library, Part 1: Interface">the first post</a>. Having implemented the functions <a href="http://blogs.teamb.com/craigstuntz/2008/09/11/37836">FoldL</a> and <a href="http://blogs.teamb.com/craigstuntz/2008/09/17/37837">Map</a>, and having used FoldL to implement <a href="http://blogs.teamb.com/craigstuntz/2008/09/11/37836">Count and Sum</a>, implementing Average and StandardDeviation are now trivial:</p>
<blockquote>
<pre><code><strong>class function </strong>TStatistics&lt;T&gt;.Average(
  <strong>const </strong>AData: TEnumerable&lt;T&gt;;
  AAdder: TBinaryOp&lt;T&gt;;
  ADivider: TBinaryOp&lt;T&gt;;
  AExplicitCast: TFunc&lt;integer, T&gt;): T;
<strong>var</strong>
  Total, Num: T;
<strong>begin</strong>
  Total := Sum(AData, AAdder, AExplicitCast);
  Num := Count(AData, AAdder, AExplicitCast);
  Result := ADivider(Total, Num);
<strong>end</strong>;

<strong>class function </strong>TStatistics&lt;T&gt;.StandardDeviation(
  <strong>const </strong>AData: TEnumerable&lt;T&gt;;
  ADeviation, AAdder, ADivider:TBinaryOp&lt;T&gt;;
  ARoot, ASquare: TUnaryOp&lt;T&gt;;
  AExplicitCast: TFunc&lt;integer, T&gt;): T;
<strong>var</strong>
  Avg, Variance: T;
  SquaredDeviations: TEnumerable&lt;T&gt;;
<strong>begin</strong>
  Avg := Average(AData, AAdder, ADivider, AExplicitCast);
  SquaredDeviations := Map(
    <strong>function</strong>(AValue: T): T
    <strong>begin</strong>
      Result := ASquare(ADeviation(AValue, Avg));
    <strong>end</strong>,
    AData);
  <strong>try</strong>
    Variance := Average(SquaredDeviations, AAdder, ADivider, AExplicitCast);
    Result := ARoot(Variance);
  <strong>finally</strong>
    SquaredDeviations.Free;
  <strong>end</strong>;
<strong>end</strong>;
</code></pre>
</blockquote>
<p>You can download <a href="http://cc.codegear.com/item/26088" title="26088, Generic Statistics Demo">the complete project</a> from CodeCentral.</p>
<p>Even having to use functions like "AAdder" in place of the more conventional "+", I think the algorithm is still fairly easy to read here, at least if you understand the <a href="http://en.wikipedia.org/wiki/Standard_deviation">standard deviation</a>.  As <a href="http://blogs.teamb.com/craigstuntz/2008/09/17/37837#comment-3847">Raymond points out in comments to the previous post</a>, however, the syntax may not be familiar to see folks who have spent most of their time in older versions of Delphi.</p>
<p>I&#8217;m afraid you&#8217;re just going to have to get used to it.  Delphi is well behind the pack in getting support for anonymous methods, and in many environments it is difficult to get much done without them.  JavaScript comes to mind; the asynchronous nature of much of what you have to do in JavaScript <a href="http://marijn.haverbeke.nl/cps/" title="Continuation-Passing Style and why JavaScript developers might be interested in it">makes a continuation-passing style quite practical</a>.  Lambda expressions, which are, very roughly, a more concise version of an anonymous function, are required to do any useful work in LINQ.  In languages like Lisp and Haskell, all "lines" of code are (again, very roughly) functions, which are anonymous by default. Few mainstream languages don&#8217;t support this, and many environments leverage it heavily. If you don&#8217;t understand such syntax well, you will find it hard to work outside of Delphi, like a COBOL programmer who doesn&#8217;t understand OO. You aren&#8217;t required to like it, but you <strong>have</strong> to understand it.</p>
<blockquote>
<pre></pre>
</blockquote>
<p class="akst_link"><a href="http://blogs.teamb.com/craigstuntz/?p=37838&amp;akst_action=share-this" onclick="akst_share('37838', 'http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F09%2F24%2F37838%2F', 'Building+a+Generic+Statistics+Library%2C+Part+5%3A+Implementation'); return false;" title="Post to del.icio.us, etc." id="akst_link_37838" class="akst_share_link" rel="nofollow">Share This</a> | <a href="mailto:?subject=Building%20a%20Generic%20Statistics%20Library%2C%20Part%205%3A%20Implementation&body=Have you seen this? http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F09%2F24%2F37838%2F" id="akst_email_37838" class="akst_share_email" rel="nofollow">Email this page to a friend</a></p>]]></content:encoded>
      <wfw:commentRss></wfw:commentRss>
    </item>
  <item>
    <title>CDN Search, Part 2: Background Jobs</title>
    <link>http://blogs.teamb.com/yaminov/2008/09/23/cdn-search-part-2-background-jobs/</link>
    <comments>http://blogs.teamb.com/yaminov/2008/09/23/cdn-search-part-2-background-jobs/#comments</comments>
    <pubDate>Tue, 23 Sep 2008 08:39:22 +0000</pubDate>
    <dc:creator>Yorai Aminov</dc:creator>
    
		<category><![CDATA[CDN]]></category>

		<category><![CDATA[GetPublished]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/yaminov/2008/09/23/cdn-search-part-2-background-jobs/</guid>
    <description><![CDATA[The previous post in this series described how GetPublished processes content and passes it to the Lucene index. I noted there was a problem with the final steps of the process, which were:

GetPublished indexes the content by calling the search web service.
GetPublished stores all data in the database.

The problem is that since we&#8217;re updating multiple [...]]]></description>
      <content:encoded><![CDATA[<p>The <a href="http://blogs.teamb.com/yaminov/2008/09/21/cdn-search-part-1-new-search-engine/">previous post</a> in this series described how GetPublished processes content and passes it to the Lucene index. I noted there was a problem with the final steps of the process, which were:</p>
<ol>
<li>GetPublished indexes the content by calling the search web service.
<li>GetPublished stores all data in the database.</li>
</ol>
<p>The problem is that since we&#8217;re updating multiple data stores (the Lucene index and GetPublished&#8217;s database), we have no way of controlling the entire process as a single transaction. Writing a distributed transaction manager and extending both GetPublished and Lucene to use it wasn&#8217;t really an option, but we needed a way to make sure the database and the Lucene index matched.</p>
<p>When faced with complex design decisions, it help to analyze the risks involved. Here&#8217;s my initial risk assessment. It estimates the risk of receiving incorrect search results for index-only and database-only failures (if both operations succeed or fail, the database and index match, and we have no problem). </p>
<table cellspacing="0" cellpadding="2" border="1">
<tbody>
<tr>
<td valign="top" width="133">&nbsp;</td>
<td valign="top" width="133">Index-only failure</td>
<td valign="top" width="133">Database-only failure</td>
</tr>
<tr>
<td valign="top" width="133">New content</td>
<td valign="top" width="133">Medium</td>
<td valign="top" width="133">None</td>
</tr>
<tr>
<td valign="top" width="133">Changed content</td>
<td valign="top" width="133">Low</td>
<td valign="top" width="133">High</td>
</tr>
<tr>
<td valign="top" width="133">Deleted content</td>
<td valign="top" width="133">None</td>
<td valign="top" width="133">High</td>
</tr>
</tbody>
</table>
<p>The risks are based on the following assumptions:</p>
<ol>
<li>Only content in the database is "real" - this is what users see.
<li>GetPublished rarely modifies existing content - most edits generate new versions.
<li>All search results have to be filtered for visibility by GetPublished.</li>
</ol>
<p>Based on these assumptions, we can determine that there&#8217;s generally little risk in index failures. That risk can be further mitigated by retrying to index later. On the other hand, database-only failures are usually a high risk, so we&#8217;d better find a way to avoid them. I therefore based the design on the following requirements:</p>
<ol>
<li>If we were unable to commit changes to the database, we must not update the index.
<li>If we were unable to update the index, we should retry later.</li>
</ol>
<p>The first part is easy: all we have to do is make sure all processing is wrapped in a database transaction. Only if the transaction is successfully committed, can we index the content. By only reading committed data and running the indexing code outside the content processing transaction we can make sure we&#8217;re only indexing successfully committed data.</p>
<p>The second part is the real problem. Once data is committed, we have to try to index it. But what if we can&#8217;t? We can&#8217;t keep trying indefinitely - we need to respond to user requests. So, we need to run the indexing request in another thread, one that can keep trying while we return control to the user.</p>
<p>Background threads are a particular problem in web applications. Web applications usually only live for the duration of a single request. The web server software (IIS, in GetPublished&#8217;s case) can - and will - terminate the process, including background thread, at any time. Additional complications arise from GetPublished&#8217;s distributed architecture and ASP.NET&#8217;s application model. GetPublished is designed to run on multiple servers concurrently (web farm). ASP.NET applications run in application pools, which may be recycled (manually by administrators, or automatically by the server or external monitoring tools), terminating all running threads.</p>
<p>GetPublished solves this problem by implementing a system of background jobs. Instead of arbitrary threads, jobs are special classes that can be tracked and monitored by GetPublished. Since the application runs on multiple servers, and can be restarted at any time, jobs are stored in the database. When GetPublished starts, it creates a job monitoring thread, whose job is to periodically check the database and start job threads as necessary:</p>
<p><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="251" alt="Background Jobs" src="http://blogs.teamb.com/files/2008/09/backgroundjobs_787.png" width="531" border="0"> </p>
<p>Requests that require processing that may take longer than a normal web request can use background jobs. Instead of spawning worker threads, requests can create job records in the database. The job monitoring thread will then pick up the request and spawn a worker thread next time it checks the database. GetPublished even lets administrators monitor, stop, and restart running jobs:</p>
<p><a href="http://blogs.teamb.com/files/2008/09/clip-image002_789.jpg"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="58" alt="Job Monitoring View" src="http://blogs.teamb.com/files/2008/09/clip-image002-thumb_791.jpg" width="640" border="0"></a></p>
<p>Using background jobs, we can now change the article submission process:</p>
<p><a href="http://blogs.teamb.com/files/2008/09/submittransactional_793.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="480" alt="Transactional submission process" src="http://blogs.teamb.com/files/2008/09/submittransactional-thumb_795.png" width="614" border="0"></a> </p>
<p>The indexing job is created as part of the same transaction that stores the content. This means the job will only run if the data has been successfully committed. The job calls the web service to index the content, and can safely retry the operation if necessary without blocking the user.</p>
<p>So far, we&#8217;ve covered indexing. That&#8217;s only half the job of a search engine. <a href="http://blogs.teamb.com/yaminov/2008/09/24/cdn-search-part-3-search-results/">Next time</a>, I&#8217;ll describe the actual search.</p>
<p class="akst_link"><a href="http://blogs.teamb.com/yaminov/?p=39&amp;akst_action=share-this" onclick="akst_share('39', 'http%3A%2F%2Fblogs.teamb.com%2Fyaminov%2F2008%2F09%2F23%2Fcdn-search-part-2-background-jobs%2F', 'CDN+Search%2C+Part+2%3A+Background+Jobs'); return false;" title="Post to del.icio.us, etc." id="akst_link_39" class="akst_share_link" rel="nofollow">Share This</a> | <a href="mailto:?subject=CDN%20Search%2C%20Part%202%3A%20Background%20Jobs&body=Have you seen this? http%3A%2F%2Fblogs.teamb.com%2Fyaminov%2F2008%2F09%2F23%2Fcdn-search-part-2-background-jobs%2F" id="akst_email_39" class="akst_share_email" rel="nofollow">Email this page to a friend</a></p>]]></content:encoded>
      <wfw:commentRss></wfw:commentRss>
    </item>
  <item>
    <title>CDN Search, Part 1: New Search Engine</title>
    <link>http://blogs.teamb.com/yaminov/2008/09/21/cdn-search-part-1-new-search-engine/</link>
    <comments>http://blogs.teamb.com/yaminov/2008/09/21/cdn-search-part-1-new-search-engine/#comments</comments>
    <pubDate>Sun, 21 Sep 2008 15:29:36 +0000</pubDate>
    <dc:creator>Yorai Aminov</dc:creator>
    
		<category><![CDATA[CDN]]></category>

		<category><![CDATA[GetPublished]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/yaminov/2008/09/21/cdn-search-part-1-new-search-engine/</guid>
    <description><![CDATA[A few days ago we deployed a new search engine on all major CodeGear sites. At the heart of the engine is the Apache Lucene library, which I highly recommend. We&#8217;ll be providing more information about our overall implementation in the near future (update: John Kaster published an article about this), but I wanted to [...]]]></description>
      <content:encoded><![CDATA[<p>A few days ago we deployed a <a href="http://dn.codegear.com/article/38720">new search engine</a> on all major CodeGear sites. At the heart of the engine is the <a href="http://lucene.apache.org/java/docs/">Apache Lucene</a> library, which I highly recommend. We&#8217;ll be providing more information about our overall implementation in the near future (update: John Kaster published <a href="http://dn.codegear.com/article/38723">an article about this</a>), but I wanted to discuss some of the implementation details specific to GetPublished. There&#8217;s a lot to cover, so I&#8217;ll post this as a multi-part series.</p>
<p>The previous search engine was based on keywords rather the full-text, and had several limitations:</p>
<ul>
<li>The keyword parser did not correctly handle Unicode text, particularly east-Asian languages.
<li>Lack of a full-text index prevented phrase and proximity searches, and did not allow correct scoring of search results.
<li>The use of multiple databases by CDN applications prevented unified searches across all web sites.
<li>It was slow.</li>
</ul>
<p>Obviously, the engine needed to be replaced. We&#8217;ve looked at several search engines in the past, but didn&#8217;t find one that matched our needs. We started rewriting our parser, but decided to take another look at the latest version of Lucene - and were pleasantly surprised. Lucene seemed more than capable of handling our needs, and since it is open source, we knew we could tweak it if necessary.</p>
<p>The first problem we needed to solve was how to integrate the Lucene index into our applications. CDN applications are written in several languages (Delphi, Java, C#, and PHP), run on multiple platforms (Native Windows, ASP.NET, and Linux), and use several databases (InterBase, Blackfish SQL, Oracle, and Microsoft SQL Server). In addition, most CDN applications run on multiple load-balanced application servers.</p>
<p>One solution would have been to let Lucene access our databases directly. This would have involved setting up special tables that match the index structure, and maintaining application-specific information on the indexing server. For multiple applications and databases, this can become a serious headache. Instead, we wrapped the search engine in a web service. Each application already controls its content, and notifies the search engine of content changes - indexing new content, re-indexing updated content, and removing deleted content:</p>
<p><a href="http://blogs.teamb.com/files/2008/09/luceneservice_779.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="165" alt="Search web service" src="http://blogs.teamb.com/files/2008/09/luceneservice-thumb_781.png" width="640" border="0"></a> </p>
<p>Next, we had to decide what constitutes a "document" in the index. A document is a single entry, identified by a unique ID, that can be return as a search result. A single document can have multiple fields, but is included no more than once in search results. Each CDN application has a different concept of a document, which may or may not correspond to what users may consider a single piece of content. Here&#8217;s what we came up with:</p>
<ul>
<li>For blogs, a single blog post is a document.
<li>For CodeCentral, both a complete submission and a single source code file within a submission are considered documents. They are indexed using different IDs, so we can search for submissions, source code, or both.
<li>For GetPublished, a single version of an article is considered a document. GetPublished articles can have multiple versions, and GetPublished uses a complex set of rules to determine actual content visibility on its sites. Instead of indexing all possible visibility combinations, we index each version once, and let GetPublished convert search results into a set of articles visible to the user.
<li>For QualityCentral, a single report is a document.</li>
</ul>
<p>GetPublished uses <a href="http://blogs.teamb.com/yaminov/2008/05/02/document-adapters/">DocAdapter</a> to process submitted files and convert them into HTML articles. Among other things, DocAdapter extracts source code snippets from the submitted document and uses <a href="http://lingua.codegear.com/yapp/">YAPP</a> to <a href="http://dn.codegear.com/article/34095">automatically syntax-highlight</a> them. Since DocAdapter already knew how to extract source code from an article, it was fairly simple to extend the code to return the original snippets to GetPublished, so they could be indexed by Lucene.</p>
<p>Here is what happens when a user submits an article to GetPublished:</p>
<p><a href="http://blogs.teamb.com/files/2008/09/submitworkflow_783.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="384" alt="Article submission processing" src="http://blogs.teamb.com/files/2008/09/submitworkflow-thumb_785.png" width="640" border="0"></a> </p>
<p>Roughly, the steps are:</p>
<ol>
<li>GetPublished checks the submitted files and form fields and generates the necessary data for the article (for example, a unique article ID for a new article).
<li>GetPublished then sends the content to DocAdapter for processing.
<li>DocAdapter converts the content to HTML, and extracts all code snippets.
<li>Each code snippet is stored, then sent to YAPP for syntax highlighting.
<li>DocAdapter merges the syntax-highlighted snippets into the final HMTL.
<li>DocAdapter returns the merged HTML, all source code snippets, and any additional required information to GetPublished.
<li>GetPublished indexes the content by calling the search web service.
<li>GetPublished stores all data in the database.</li>
</ol>
<p>You&#8217;ll notice I painted the line from GetPublished to the web service red. This is because there&#8217;s a problem here: the process I just describes only works when there&#8217;s no error. If either step 7 (indexing) or step 8 (data storage) fails, we&#8217;re left with inconsistent data.</p>
<p>One possible solution would be to switch steps 7 and 8. After we store the data (and commit the transaction) successfully, we can safely call the web service, knowing we&#8217;re indexing valid content. This still doesn&#8217;t solve the problem of index failure: if the web service call then fails, we&#8217;re left with new content that&#8217;s not indexed.</p>
<p>Another option is to roll back the entire transaction if step 7 fails. This works in case of an indexing error, but doesn&#8217;t help us if indexing succeeded but the database commit failed. Once again, the database and index won&#8217;t match.</p>
<p>Since we don&#8217;t have distributed transactions with the Lucene index, what we need is a way to tie an indexing request to a successful commit, and the ability to ensure the indexing request succeeds - or at least, notify an administrator if there&#8217;s a problem.</p>
<p>In my <a href="http://blogs.teamb.com/yaminov/2008/09/23/cdn-search-part-2-background-jobs/">next post</a>, I&#8217;ll describe how GetPublished accomplishes this task.</p>
<p class="akst_link"><a href="http://blogs.teamb.com/yaminov/?p=33&amp;akst_action=share-this" onclick="akst_share('33', 'http%3A%2F%2Fblogs.teamb.com%2Fyaminov%2F2008%2F09%2F21%2Fcdn-search-part-1-new-search-engine%2F', 'CDN+Search%2C+Part+1%3A+New+Search+Engine'); return false;" title="Post to del.icio.us, etc." id="akst_link_33" class="akst_share_link" rel="nofollow">Share This</a> | <a href="mailto:?subject=CDN%20Search%2C%20Part%201%3A%20New%20Search%20Engine&body=Have you seen this? http%3A%2F%2Fblogs.teamb.com%2Fyaminov%2F2008%2F09%2F21%2Fcdn-search-part-1-new-search-engine%2F" id="akst_email_33" class="akst_share_email" rel="nofollow">Email this page to a friend</a></p>]]></content:encoded>
      <wfw:commentRss></wfw:commentRss>
    </item>
  <item>
    <title>Building a Generic Statistics Library, Part 4: Map</title>
    <link>http://blogs.teamb.com/craigstuntz/2008/09/17/37837/</link>
    <comments>http://blogs.teamb.com/craigstuntz/2008/09/17/37837/#comments</comments>
    <pubDate>Wed, 17 Sep 2008 23:11:55 +0000</pubDate>
    <dc:creator>Craig Stuntz</dc:creator>
    
		<category><![CDATA[Delphi]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/craigstuntz/2008/09/17/37837</guid>
    <description><![CDATA[It&#8217;s been a busy week here in Columbus, what with the highest wind speeds ever recorded in the city and no power in my house — or 1/2 million others — since Sunday.  But don&#8217;t feel too bad for me; a lot of people have it worse. Anyway, this will be a fairly short post.
This [...]]]></description>
      <content:encoded><![CDATA[<p>It&#8217;s been a busy week here in Columbus, what with the highest wind speeds ever recorded in the city and no power in my house — <a href="http://www.dispatch.com/live/content/local_news/stories/2008/09/16/stormfollow.ART_ART_09-16-08_A1_KPBBBMU.html?sid=101" title="Some power back; Columbus schools will stay closed Wednesday">or 1/2 million others</a> — since Sunday.  But don&#8217;t feel too bad for me; <a href="http://www.boston.com/bigpicture/2008/09/the_short_but_eventful_life_of.html" title="The short - but eventful - life of Ike">a lot of people have it worse</a>. Anyway, this will be a fairly short post.</p>
<p>This post is the fourth in my series on building a statistics library using Delphi 2009&#8217;s new generic types.  If you&#8217;re new to the series, you might want to start with <a href="http://blogs.teamb.com/craigstuntz/2008/09/09/37833" title="Building a Generic Statistics Library, Part 1: Interface">the first post</a>.  Today I&#8217;m going to discuss the second higher-order function that the library uses internally, <a href="http://en.wikipedia.org/wiki/Map_(higher-order_function)">Map</a>.</p>
<p>Map is a function which takes a list, and a function which operates on individual items in the list, and returns a new list, formed by executing the function against each entry in the original list.  For example, suppose I had this list of integers:</p>
<blockquote><p>1, 2, 3, 4, 5</p></blockquote>
<p>Now let&#8217;s say that I call Map, passing this list, and the function Inc(). The result would be this list:</p>
<blockquote><p>2, 3, 4, 5, 6</p></blockquote>
<p>Don&#8217;t confuse Map with functions like jQuery&#8217;s <a href="http://docs.jquery.com/Core/each">each</a> which merely iterate the list and call a passed function without returning a new list.  That&#8217;s a different kind of function.</p>
<p>To calculate the standard deviation of a list, I first need to create a list of the squares of the deviations of each entry in the list. Later, I will perform additional calculations to compute the standard deviation, but first I need this list.  Here&#8217;s how I do it, using Map:</p>
<blockquote>
<pre><code>  SquaredDeviations := Map(<strong>function</strong>(AValue: T): T
    <strong>begin</strong>
      Result := ASquare(ADeviation(AValue, Avg));
    <strong>end</strong>,
    AData);
    // [...]
</code></pre>
</blockquote>
<p>The anonymous function I pass as an argument to Map computes the <a href="http://mathworld.wolfram.com/Deviation.html">deviation</a> of the individual item it is passed, squares it, and returns a value.  This anonymous function is called once for each item in the original list. And here is the implementation of Map itself:</p>
<blockquote>
<pre><code><strong>class function </strong>TStatistics&lt;T&gt;.Map(
  AFunc: TUnaryOp&lt;T&gt;;
  <strong>const </strong>AData: TEnumerable&lt;T&gt;): TEnumerable&lt;T&gt;;
<strong>var</strong>
  Current: T;
  NewList: TList&lt;T&gt;;
<strong>begin</strong>
  NewList := TList&lt;T&gt;.Create;
  <strong>for </strong>Current <strong>in </strong>AData <strong>do begin</strong>
    NewList.Add(AFunc(Current));
  <strong>end</strong>;
  Result := NewList;
<strong>end</strong>;
</code></pre>
</blockquote>
<p>Note that I have Map returning a new instance.  It is behaving as a constructor of sorts.  Indeed, it might make sense to have a constructor of this style on a list type. You could also write a version of Map which accepted an entity list to use as the result if it makes your lifetime management easier.</p>
<p class="akst_link"><a href="http://blogs.teamb.com/craigstuntz/?p=37837&amp;akst_action=share-this" onclick="akst_share('37837', 'http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F09%2F17%2F37837%2F', 'Building+a+Generic+Statistics+Library%2C+Part+4%3A+Map'); return false;" title="Post to del.icio.us, etc." id="akst_link_37837" class="akst_share_link" rel="nofollow">Share This</a> | <a href="mailto:?subject=Building%20a%20Generic%20Statistics%20Library%2C%20Part%204%3A%20Map&body=Have you seen this? http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F09%2F17%2F37837%2F" id="akst_email_37837" class="akst_share_email" rel="nofollow">Email this page to a friend</a></p>]]></content:encoded>
      <wfw:commentRss></wfw:commentRss>
    </item>
  <item>
    <title>"Disabling" code-folding</title>
    <link>http://blogs.teamb.com/davenottage/2008/09/15/33688/</link>
    <comments>http://blogs.teamb.com/davenottage/2008/09/15/33688/#comments</comments>
    <pubDate>Sun, 14 Sep 2008 21:21:20 +0000</pubDate>
    <dc:creator>Dave Nottage</dc:creator>
    
		<category><![CDATA[Uncategorized]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/davenottage/2008/09/15/33688</guid>
    <description><![CDATA[Code-folding was introduced into Delphi 2005, and is a means whereby sections of your code can be "collapsed", eg from this:

to this:

Code-folding is switched on by default, and there appears to be no way to turn it off permanently.  For those (like me) that never use it, this can be annoying, especially when you click [...]]]></description>
      <content:encoded><![CDATA[<p>Code-folding was introduced into <a href="http://www.codegear.com/delphi">Delphi</a> 2005, and is a means whereby sections of your code can be "collapsed", eg from this:</p>
<p><a href="/files/2008/09/codeexpanded_771.JPG" title="Code Expanded"><img src="/files/2008/09/codeexpanded_771.JPG" alt="Code Expanded" /></a></p>
<p>to this:</p>
<p><a href="/files/2008/09/codecollapsed_773.JPG" title="Code collapsed"><img src="/files/2008/09/codecollapsed_773.JPG" alt="Code collapsed" /></a></p>
<p>Code-folding is switched on by default, and there appears to be no way to turn it off permanently.  For those (like me) that never use it, this can be annoying, especially when you click the node to collapse code when you wanted to click elsewhere in the gutter, or you just want to have a few extra pixels of space in your editor.</p>
<p>The hot-key sequence for turning off code-folding is Ctrl-Shift-K-O (KO.. knock-out.. stands to reason) . Unfortunately this doesn&#8217;t turn it off permanently as it is not saved between sessions. Fortunately, the setting *is* saved in desktop settings, so if you turn off code-folding and then save the desktop (View|Desktops|Save desktop&#8230;) the setting will persist for that desktop. That means you will need to turn it off in each desktop you want it saved to, and save that desktop, too.</p>
<p>Thanks go to Alexander Tereshchenko for the suggestion, which he made in <a href="http://www.codegear.com">CodeGear&#8217;s</a> <a href="http://forums.codegear.com">newsgroups</a>.</p>
<p class="akst_link"><a href="http://blogs.teamb.com/davenottage/?p=33688&amp;akst_action=share-this" onclick="akst_share('33688', 'http%3A%2F%2Fblogs.teamb.com%2Fdavenottage%2F2008%2F09%2F15%2F33688%2F', '%22Disabling%22+code-folding'); return false;" title="Post to del.icio.us, etc." id="akst_link_33688" class="akst_share_link" rel="nofollow">Share This</a> | <a href="mailto:?subject=%22Disabling%22%20code-folding&body=Have you seen this? http%3A%2F%2Fblogs.teamb.com%2Fdavenottage%2F2008%2F09%2F15%2F33688%2F" id="akst_email_33688" class="akst_share_email" rel="nofollow">Email this page to a friend</a></p>]]></content:encoded>
      <wfw:commentRss></wfw:commentRss>
    </item>
  <item>
    <title>Building a Generic Statistics Library, Part 3: Fold</title>
    <link>http://blogs.teamb.com/craigstuntz/2008/09/11/37836/</link>
    <comments>http://blogs.teamb.com/craigstuntz/2008/09/11/37836/#comments</comments>
    <pubDate>Thu, 11 Sep 2008 12:39:03 +0000</pubDate>
    <dc:creator>Craig Stuntz</dc:creator>
    
		<category><![CDATA[Delphi]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/craigstuntz/2008/09/11/37836</guid>
    <description><![CDATA[I chose statistical functions as a sample problem because it is so easy to express a statistical function in terms of operations across lists, and operations across lists are what mapping functions do well.  In this post, I am going to discuss two list operations, Fold and Map, which will be useful in implementing the Average and StandardDeviation functions. Then I'll go into some detail about what Fold does and how I use it to compute the sum and count of list elements.]]></description>
      <content:encoded><![CDATA[<p>This post is the third in a series on building a statistics library using Delphi 2009&#8217;s generic types.  If you&#8217;re new to the series, you might want to start at <a href="http://blogs.teamb.com/craigstuntz/2008/09/09/37833" title="Building a Generic Statistics Library, Part 1: Interface">the beginning</a>.</p>
<p>Computing the Average or Standard Deviation of a set of numbers is a fairly trivial task.  For smaller sets, you can do it in your head.  It certainly does not require advanced programming techniques to do in code.  But recall that my purpose in writing this series was to answer commentor <a href="http://blogs.teamb.com/craigstuntz/2008/08/28/37831#comment-3793">Raymond&#8217;s request for "something like MapReduce."</a>  So when you read this post and wonder why I&#8217;ve chosen such a roundabout method of doing some simple sums, keep this purpose in mind.  The point is to learn about generic list operations, not to learn how to compute an average.  If you need help computing an average, you probably won&#8217;t understand the rest of this post.</p>
<p>I chose statistical functions as a sample problem because it is so easy to express a statistical function in terms of operations across lists, and operations across lists are what mapping functions do well.  In this post, I am going to discuss two list operations, Fold and Map, which will be useful in implementing the Average and StandardDeviation functions. Then I&#8217;ll go into some detail about what Fold does and how I use it to compute the sum and count of list elements. I&#8217;ll discuss Map further in the next post in this series.</p>
<p>Both Fold and Map are "higher order functions," which simply means that they take a function as one of their arguments.  Both Fold and Map transform a list, but they do it in different ways.  Fold applies a function to <strong>pairs </strong>of entries in a list, carrying an aggregated value as it works, whereas Map generates a new list by applying a function to <strong>individual </strong>entries in a list, and creating a new list from the results of the function.</p>
<p>In my implementation of the average and standard deviation functions, I will use Fold to calculate the sum and count of entries in a list, and Map to create a new list containing the squared deviations of entries in the original list.</p>
<p>Anyone who has ever balanced a checkbook can intuitively understand what Fold does.  Yet, people often find the function confusing, because of differences in how different versions of the function operate.  So I&#8217;m going to examine it in some detail.</p>
<p>Fold is a function which can only be used on ordered lists such as arrays and TList. Note that when I say "ordered" here I don&#8217;t mean alphabetical or numeric order, only that each item in the list has a defined position.  In other words, something unlike a (mathematical) <a href="http://mathworld.wolfram.com/Set.html">set</a>. Fold takes three arguments: The list of values, a function which takes two values as arguments and returns a single value, and an "initial" value.  The Fold traverses the list, performing an operation on each item in the list, and also passing to this operation the result of the previous operation.</p>
<p>Since the fold function internally works on pairs of values, and since it does the same operation on each item in the list, there is also a need for an "initial" value.  Otherwise, we would not have a second argument for the passed function when we evaluated the first (or at last, depending on implementation) entry in the list. This is why I need the "mapping" function I described in my first post in this series.  The function allows me to express an "initial" value in terms of the type used as the type parameter.  However, as I&#8217;ve developed this series, I&#8217;ve decided to call the function an "explicit cast" instead of a "mapping" function.  Explicit is a Delphi operator which performs exactly the task I&#8217;m trying to do.  Using this name is both to avoid confusion with the unrelated Map function I&#8217;ll describe later, and for consistency with the notion of passing functions as an alternative to "real" operator constraints.</p>
<p>I will use Fold to calculate the sum of the entries in the list like this:</p>
<blockquote>
<pre><code><strong>class function </strong>TStatistics&lt;T&gt;.Sum(
  <strong>const </strong>AData: TEnumerable&lt;T&gt;;
  AAdder: TBinaryOp&lt;T&gt;;
  AExplicitCast: TFunc&lt;integer, T&gt;): T;
<strong>var</strong>
  Init: T;
<strong>begin</strong>
  Init := AExplicitCast(0);
  Result := FoldL(AAdder, AData, Init);
<strong>end</strong>;</code></pre>
</blockquote>
<p>FoldL will execute like this: Start with the initial value.  Execute the passed function (in this case, addition), passing the initial value and the first item in the list.  Execute the function again, passing the result of the first execution and the second item in the list.  Execute the function again, passing the results of the second execution and the third item in the list.  Continue in this way until we are out of items.  Since the "initial" value I pass is zero, the result will be the sum of the values in the list.</p>
<p>By modifying the AAdder function slightly, I can calculate a count of the items in the list rather than a sum.  How can I modify a function passed as an argument?  By wrapping it in an anonymous method:</p>
<blockquote>
<pre><code><strong>class function </strong>TStatistics&lt;T&gt;.Count(
  <strong>const </strong>AData: TEnumerable&lt;T&gt;;
  AAdder: TBinaryOp&lt;T&gt;;
  AExplicitCast: TFunc&lt;integer, T&gt;): T;
<strong>var</strong>
  Init: T;
<strong>begin</strong>
  Init := AExplicitCast(0);
  Result := FoldL(
    <strong>function</strong>(ALeft, ARight: T): T
    begin
      Result := AAdder(ALeft, AExplicitCast(1));
    end,
    AData,
    Init);
<strong>end</strong>;</code></pre>
</blockquote>
<p>So Count works almost exactly like Sum, except that I alter the passed AAdder function such that it ignores its second argument and always adds 1 to the running total. (Why couldn&#8217;t I just use the Count property of the list? TEnumerable&lt;T&gt; doesn&#8217;t have one.)</p>
<p>You might have noticed that I called my Fold function Fold<strong>L</strong> instead of just Fold.  This is because there are two variants of Fold: A left fold and a right fold. Despite the names, both variants process entries in the list in the same order, from start to finish.  The "left" and "right" variants differ in terms of where the "initial" value is used.  If we write down the entries in the list from left to right, the left fold variant positions the initial value on the far left-hand side of the list, and the right fold variant positions the value on the far right-hand side of the list.  In a recursive implementation of fold, the left and right variants also differ in terms of the point at which recursion occurs.  If the compiler does a tail recursion optimization, this results in a substantial performance benefit for the right fold variant.  But in a looping implementation, like the one I&#8217;m going to demonstrate, performance should be identical in both variants.</p>
<p>With a <a href="http://mathworld.wolfram.com/Commutative.html">commutative</a>  function, like addition, the result will also be identical in both variants. So for my Count and Sum functions, I could have used either FoldL or FoldR. With a noncommutative operation such as subtraction, FoldL and FoldR will obviously give different results.  The following diagrams <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)" title="Fold (higher-order function)">from Wikipedia</a> illustrate the two functions well.</p>
<p><img src="http://upload.wikimedia.org/wikipedia/commons/5/5a/Left-fold-transformation.png" width="320" height="158" />  <img src="http://upload.wikimedia.org/wikipedia/commons/3/3e/Right-fold-transformation.png" width="320" height="158" /></p>
<p>My implementation of FoldL is quite simple.  Note that this is a very limited FoldL; in keeping with my desire to not make this series overly long I&#8217;ve restricted this FoldL to only be able to return T. A more general FoldL would allow an arbitrary return type.</p>
<blockquote>
<pre><code><strong>class function </strong>TStatistics&lt;T&gt;.FoldL(AFunc: TBinaryOp&lt;T&gt;;<strong>
  const </strong>AData: TEnumerable&lt;T&gt;; <strong>const </strong>AInit: T): T;<strong>
var
</strong>  Current, Previous: T;<strong>
begin
</strong>  Previous := AInit;
<strong>  for </strong>Current <strong>in </strong>AData <strong>do begin
    </strong>Previous := AFunc(Previous, Current);<strong>
  end;
  </strong>Result := Previous;<strong>
end;</strong> </code></pre>
</blockquote>
<p>In my next post, I&#8217;ll discuss Map.</p>
<p class="akst_link"><a href="http://blogs.teamb.com/craigstuntz/?p=37836&amp;akst_action=share-this" onclick="akst_share('37836', 'http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F09%2F11%2F37836%2F', 'Building+a+Generic+Statistics+Library%2C+Part+3%3A+Fold'); return false;" title="Post to del.icio.us, etc." id="akst_link_37836" class="akst_share_link" rel="nofollow">Share This</a> | <a href="mailto:?subject=Building%20a%20Generic%20Statistics%20Library%2C%20Part%203%3A%20Fold&body=Have you seen this? http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F09%2F11%2F37836%2F" id="akst_email_37836" class="akst_share_email" rel="nofollow">Email this page to a friend</a></p>]]></content:encoded>
      <wfw:commentRss></wfw:commentRss>
    </item>
  <item>
    <title>Building a Generic Statistics Library, Part 2: Unit Tests</title>
    <link>http://blogs.teamb.com/craigstuntz/2008/09/10/37834/</link>
    <comments>http://blogs.teamb.com/craigstuntz/2008/09/10/37834/#comments</comments>
    <pubDate>Wed, 10 Sep 2008 17:18:33 +0000</pubDate>
    <dc:creator>Craig Stuntz</dc:creator>
    
		<category><![CDATA[Delphi]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/craigstuntz/2008/09/10/37834</guid>
    <description><![CDATA[Since I have a signature, I have enough to start writing unit tests, even without an implementation. Not only does this allow me to check that my implementation works, it's also a convenient way to run routines in a library-in-progress, without building a "throwaway" user interface.]]></description>
      <content:encoded><![CDATA[<p>Yesterday, I <a href="http://blogs.teamb.com/craigstuntz/2008/09/09/37833" title="Building a Generic Statistics Library, Part 1: Interface">introduced a short series I&#8217;m writing on building a statistics library using Delphi 2009 generic methods</a>, and discussed the signature of the Average function.  Since I have a signature, I have enough to start writing unit tests, even without an implementation. Not only does this allow me to check that my implementation works, it&#8217;s also a convenient way to run routines in a library-in-progress, without building a "throwaway" user interface.</p>
<p>So I added a new test project to my project group, and then I added a new test case to the test project.  The test case wizard got confused by the class methods, so I just wrote the tests manually.  They&#8217;re quite simple:</p>
<blockquote>
<pre><strong>uses</strong>
  TestFramework, Classes, Unit7, Generics.Collections, SysUtils;

<strong>type</strong>
  TestTIntStatistics = <strong>class</strong>(TTestCase)
  <strong>published</strong>
    <strong>procedure </strong>TestAverage;
    <strong>procedure </strong>TestStandardDeviation;
  <strong>end</strong>;

<strong>implementation</strong>

<strong>procedure </strong>TestTIntStatistics.TestAverage;
<strong>var</strong>
  ReturnValue: Integer;
  AData: TList&lt;integer&gt;;
<strong>begin</strong>
  AData := TList&lt;integer&gt;.Create;
  <strong>try</strong>
    AData.Add(2);
    AData.Add(4);
    AData.Add(6);

    ReturnValue := TIntStatistics.Average(AData);

    CheckEquals(4, ReturnValue);
  <strong>finally</strong>
    AData.Free;
  <strong>end</strong>;
<strong>end</strong>;

<strong>procedure </strong>TestTIntStatistics.TestStandardDeviation;
<strong>var</strong>
  ReturnValue: Integer;
  AData: TList&lt;integer&gt;;
<strong>begin</strong>
  AData := TList&lt;integer&gt;.Create;
  <strong>try</strong>
    AData.Add(2);
    AData.Add(4);
    AData.Add(6);

    ReturnValue := TIntStatistics.StandardDeviation(AData);

    CheckEquals(1, ReturnValue);
  <strong>finally</strong>
    AData.Free;
  <strong>end</strong>;
<strong>end</strong>;</pre>
</blockquote>
<p>I have just created a small list with values for which it is easy to calculate the average and (integer) standard deviation in my head, and checked that the values returned by my functions correspond to the values I calculated myself. That&#8217;s not a rigorous test, but it&#8217;s enough to allow me to debug through my code and check for obvious failures.</p>
<p>Of course, I haven&#8217;t actually implemented the functions yet, so the tests fail:</p>
<p><img src="http://blogs.teamb.com/files/2008/09/testfail_767.png" alt="Generic Statistics Library unit test failure" width="549" height="448" /></p>
<p>With a functioning unit test, however, I can start implementing the library.  In the <a href="http://blogs.teamb.com/craigstuntz/2008/09/11/37836" title="Building a Generic Statistics Library, Part 3: Fold">next post, I&#8217;ll start to discuss some of the higher order functions</a> the library will use internally.</p>
<p class="akst_link"><a href="http://blogs.teamb.com/craigstuntz/?p=37834&amp;akst_action=share-this" onclick="akst_share('37834', 'http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F09%2F10%2F37834%2F', 'Building+a+Generic+Statistics+Library%2C+Part+2%3A+Unit+Tests'); return false;" title="Post to del.icio.us, etc." id="akst_link_37834" class="akst_share_link" rel="nofollow">Share This</a> | <a href="mailto:?subject=Building%20a%20Generic%20Statistics%20Library%2C%20Part%202%3A%20Unit%20Tests&body=Have you seen this? http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F09%2F10%2F37834%2F" id="akst_email_37834" class="akst_share_email" rel="nofollow">Email this page to a friend</a></p>]]></content:encoded>
      <wfw:commentRss></wfw:commentRss>
    </item>
  <item>
    <title>Building a Generic Statistics Library, Part 1: Interface</title>
    <link>http://blogs.teamb.com/craigstuntz/2008/09/09/37833/</link>
    <comments>http://blogs.teamb.com/craigstuntz/2008/09/09/37833/#comments</comments>
    <pubDate>Tue, 09 Sep 2008 15:37:25 +0000</pubDate>
    <dc:creator>Craig Stuntz</dc:creator>
    
		<category><![CDATA[Delphi]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/craigstuntz/2008/09/09/37833</guid>
    <description><![CDATA[In the comments to another post on the subject of Delphi 2009 generics, Raymond asked for an implementation of MapReduce.  I thought about how I might demonstrate that in the context of generics, and decided that implementing the higher order functions Fold and Map would be a slightly better demonstration than MapReduce.  But since higher order functions can be a pretty abstract concept, I wanted to show an example of how you might use them, so I will use these functions to build a library that does some simple statistical operations, namely, computing the average and the standard deviation of a list of numbers.]]></description>
      <content:encoded><![CDATA[<p>Let me start this post with an apology: I know that generics are a new technology in Delphi for Win32 and that many people might be looking for a simple, gentle introduction to using them.  However, I&#8217;m not going to write that sort of post, at least today.  Instead, I&#8217;m going to probe the limitations of Delphi 2009 generics, and work around them when possible.</p>
<p>You can do a lot with Delphi 2009&#8217;s generic types, but one thing that you can&#8217;t do is specify an "operator constraint." This means that I cannot perform operations like +, -, implicit type conversions, etc., on a type passed as a type parameter. In my last post on this subject, <a href="http://blogs.teamb.com/craigstuntz/2008/08/29/37832" title="D2009 Generics and Type Constraints">I suggested one possible solution</a>, and experimented enough to show that it does work.  But, as I noted in the post, I suspected it might not be the best way. In particular, I didn&#8217;t like the fact that my previous approach used virtual methods, and it required creating a new "adder" type for each value type you wanted to use as a type parameter to the generic type.  That&#8217;s just too much work.</p>
<p>In the comments to another post on the subject of Delphi 2009 generics, <a href="http://blogs.teamb.com/craigstuntz/2008/08/28/37831#comment-3793">Raymond asked for an implementation of MapReduce</a>.  I thought about how I might demonstrate that in the context of generics, and decided that implementing the <a href="http://en.wikipedia.org/wiki/Higher-order_function">higher order functions</a> <a href="http://en.wikipedia.org/wiki/Fold_(higher-order_function)">Fold</a> and <a href="http://en.wikipedia.org/wiki/Map_(higher-order_function)">Map</a> would be a slightly better demonstration than MapReduce.  But since higher order functions can be a pretty abstract concept, I wanted to show an example of how you might use them, so I will use these functions to build a library that does some simple statistical operations, namely, computing the <a href="http://mathworld.wolfram.com/ArithmeticMean.html">average</a> and the <a href="http://mathworld.wolfram.com/StandardDeviation.html">standard deviation</a> of a list of numbers.</p>
<p>By using generics, I can write the algorithms for average and standard deviation once and reuse them for <strong>any </strong>type which supports certain primitive operations, like addition and taking the square root.</p>
<p>I&#8217;m going to cover a lot of ground in this demo, so I&#8217;ll be breaking it down into several posts.  In today&#8217;s post, I&#8217;m going to examine how data will be supplied to the generic statistical routines.</p>
<p>Most statistical functions take a list of numbers as input and supply one or more numbers as output.  For example, the arithmetic mean, or average, function takes a list of numbers and returns a single number.  A function which returns the <a href="http://mathworld.wolfram.com/Mode.html">mode</a> or modes of a list would take as input a list of numbers and return a different list, which might have one entry, or many.</p>
<p>So right away, I have a problem: I&#8217;d like to take a list of numbers as an invalid argument to a function, but I don&#8217;t know what type the numbers in the list will be, never mind the type of the list.  Ideally, I would be able to write something like this:</p>
<blockquote><p> <code><strong>function </strong>Average&lt;A, R&gt;(AData: IEnumerable&lt;A&gt;): R;</code></p></blockquote>
<p>This declaration should mean that the function Average accepts any list of values of type A which can be enumerated in a for&#8230;in loop and returns a value of type R. However, there are a few roadblocks in the Delphi 2009 RTL which make this impossible.</p>
<p>While the Delphi 2009 RTL does define an IEnumerable&lt;T&gt; interface type, neither TList&lt;T&gt; nor its abstract parent type TEnumerable&lt;T&gt; implement this interface.  If a trivial filesystem search can be believed, nothing else does, either. I&#8217;ve tried, unsuccessfully, to implement it myself; that&#8217;s one of many things that I haven&#8217;t figured out how to do in Delphi 2009 yet, and is perhaps the subject for another post.</p>
<p>My wild guess is that the most common type users of my statistics library will want to pass as the argument AData will be TList&lt;A&gt;. So I have to support that.  But I&#8217;d like to support other types of lists, as well.  It seems to me that the best I can do today is to specify TEnumerable&lt;T&gt; as the list argument type.  Then, at least, a user of the library can use other subtypes of TEnumerable&lt;T&gt;, such as TStack&lt;T&gt;, TQueue&lt;T&gt;, etc.</p>
<p>So my function declaration now looks like this:</p>
<blockquote><p> <code><strong>function </strong>Average&lt;A, R&gt;(AData: TEnumerable&lt;A&gt;): R;</code></p></blockquote>
<p>This, unfortunately, means that the user of the library cannot supply input data in the form of an array, although it&#8217;s trivial to write a class which exposes array data in the form of a TEnumerable&lt;T&gt; (using the <a href="http://en.wikipedia.org/wiki/Facade_pattern">facade pattern</a>), so this isn&#8217;t a huge loss.</p>
<p>In order to make the code I&#8217;m going to show simpler, I&#8217;ll use the same type argument for the input and output.  In other words, if the function is passed a list of integers, it will return the average as an integer.  If it&#8217;s passed a list of doubles, it will return the average as a double.  This is probably not ideal for a general-purpose statistical library, but, for the purposes of this demo, it makes the code quite a bit easier to understand.</p>
<p>That makes the function prototype look like this:</p>
<blockquote><p> <code><strong>function </strong>Average&lt;T&gt;(AData: TEnumerable&lt;T&gt;): T;</code></p></blockquote>
<p>However, since I have no way of specifying an "operator constraint" on T, and because specifying an interface constraint on T would prevent using my functions with primitive types, at least in Delphi 2009, and because I suspect that primitive types are the most common use case for a statistical library, I have to tell the function how to perform the mathematical operations it needs to do its work.  In order to compute an average, I need to be able to add two values and divide two values.  For reasons that I&#8217;ll cover in a future post, it will also be useful if I can map an integer value into the type of the type argument, so I&#8217;m going to require a function for that, as well.</p>
<p>Here&#8217;s the final version of the function&#8217;s interface:</p>
<blockquote><p> <code></code></p>
<pre><strong>type
</strong>  TBinaryOp&lt;T&gt; = reference <strong>to function</strong>(ALeft, ARight: T): T</pre>
<pre>  TStatistics&lt;T&gt; = <strong>class</strong>
<strong>    public</strong>
    <strong>  class function </strong>Average(<strong>const </strong>AData: TEnumerable&lt;T&gt;;
                             AAdder, ADivider: TBinaryOp&lt;T&gt;;
                             AMapper: TFunc&lt;integer, T&gt;): T; <strong>overload</strong>;</pre>
</blockquote>
<p>Calling methods with long lists of arguments can be kind of annoying, so I&#8217;ve marked a function as overloadable.  This allows me to subtype the class <strong>if I want to</strong>, implementing the primitive operations, and introducing an overloaded call to Average that passes those implementations, like this:</p>
<blockquote>
<pre><strong>  </strong>TIntStatistics <strong>= class(</strong>TStatistics&lt;integer&gt;<strong>)
  private
    class function </strong>Add(ALeft, ARight: integer): integer;<strong>
</strong><strong>    class function </strong>Divide(ALeft, ARight: integer): integer;<strong>
    class function </strong>Mapper(AValue: integer): integer;<strong>
</strong><strong>  public
    class function </strong>Average<strong>(const </strong>AData: TEnumerable&lt;integer&gt;): integer;<strong> overload;
  end;</strong></pre>
</blockquote>
<p>That gives me much closer to the "ideal" function prototype I designed above, but requires a new subtype to be implemented.  The nice thing about this current approach is that you can pick whichever solution you like: Implement a subtype if you want a simpler call to Average, or just pass the appropriate functions if you&#8217;d like to use a type parameter for which you don&#8217;t have a subtype available.</p>
<p>Since I&#8217;ve covered quite a bit of material just on the subject of the interface for one function, I&#8217;m going to take a break for today.  Stay tuned for <a href="http://blogs.teamb.com/craigstuntz/2008/09/10/37834" title="Building a Generic Statistics Library, Part 2: Unit Tests">part 2</a>!</p>
<p class="akst_link"><a href="http://blogs.teamb.com/craigstuntz/?p=37833&amp;akst_action=share-this" onclick="akst_share('37833', 'http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F09%2F09%2F37833%2F', 'Building+a+Generic+Statistics+Library%2C+Part+1%3A+Interface'); return false;" title="Post to del.icio.us, etc." id="akst_link_37833" class="akst_share_link" rel="nofollow">Share This</a> | <a href="mailto:?subject=Building%20a%20Generic%20Statistics%20Library%2C%20Part%201%3A%20Interface&body=Have you seen this? http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F09%2F09%2F37833%2F" id="akst_email_37833" class="akst_share_email" rel="nofollow">Email this page to a friend</a></p>]]></content:encoded>
      <wfw:commentRss></wfw:commentRss>
    </item>
  <item>
    <title>D2009 Generics and Type Constraints</title>
    <link>http://blogs.teamb.com/craigstuntz/2008/08/29/37832/</link>
    <comments>http://blogs.teamb.com/craigstuntz/2008/08/29/37832/#comments</comments>
    <pubDate>Fri, 29 Aug 2008 13:52:11 +0000</pubDate>
    <dc:creator>Craig Stuntz</dc:creator>
    
		<category><![CDATA[Delphi]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/craigstuntz/2008/08/29/37832</guid>
    <description><![CDATA[The .NET type system is rooted at System.Object. The Delphi/Win32 type system isn&#8217;t rooted (built-in simple types, records, and classes don&#8217;t have a common ancestor), and primitive types can&#8217;t/don&#8217;t implement interfaces, so someone in the newsgroups asked how to deal with generics which must perform operations on primitive types, without the use of IComparable, et. [...]]]></description>
      <content:encoded><![CDATA[<p>The .NET type system is rooted at System.Object. The Delphi/Win32 type system isn&#8217;t rooted (built-in simple types, records, and classes don&#8217;t have a common ancestor), and primitive types can&#8217;t/don&#8217;t implement interfaces, so someone in the newsgroups asked how to deal with generics which must perform operations on primitive types, without the use of IComparable, et. al. Here&#8217;s one way. I&#8217;m not sure if it&#8217;s the best way, but it works.</p>
<blockquote>
<pre><code><strong>unit </strong>Unit5;

<strong>interface</strong>

<strong>uses</strong>
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

<strong>type</strong>
  TAdder&lt;T&gt; = <strong>class</strong>
  <strong>public</strong>
    <strong>function</strong> AddEm(A, B: T): T; virtual; abstract;
  <strong>end</strong>;

  TIntAdder = <strong>class</strong>(TAdder&lt;integer&gt;)
  <strong>public</strong>
    <strong>function</strong> AddEm(A, B: integer): integer; override;
  <strong>end</strong>;

  TStringAdder = <strong>class</strong>(TAdder&lt;<strong>string</strong>&gt;)
  <strong>public</strong>
    <strong>function</strong> AddEm(A, B: <strong>string</strong>): string; override;
  <strong>end</strong>;

  TMath&lt;T; A: TAdder&lt;T&gt;, <strong>constructor</strong>&gt; = <strong>class</strong>
  <strong>public</strong>
     <strong>function</strong> AddTwoDigits(Left, Right: T): T;
  <strong>end</strong>;

  TForm5 = <strong>class</strong>(TForm)
    Button1: TButton;
    <strong>procedure</strong> Button1Click(S<strong>end</strong>er: TObject);
  <strong>end</strong>;

<strong>var</strong>
  Form5: TForm5;

<strong>implementation</strong>

{$R *.dfm}

<strong>procedure</strong> TForm5.Button1Click(S<strong>end</strong>er: TObject);
<strong>var</strong>
  AddInt: TMath&lt;integer, TIntAdder&gt;;
  AddString: TMath&lt;<strong>string</strong>, TStringAdder&gt;;
<strong>begin</strong>
  AddInt := TMath&lt;integer, TIntAdder&gt;.Create;
  <strong>try</strong>
    ShowMessage(IntToStr(AddInt.AddTwoDigits(2, 2)));
  <strong>finally</strong>
    AddInt.Free;
  <strong>end</strong>;
  AddString := TMath&lt;<strong>string</strong>, TStringAdder&gt;.Create;
  <strong>try</strong>
    ShowMessage(AddString.AddTwoDigits('2', '2'));
  <strong>finally</strong>
    AddString.Free;
  <strong>end</strong>;
<strong>end</strong>;

{ TIntAdder }

<strong>function</strong> TIntAdder.AddEm(A, B: integer): integer;
<strong>begin</strong>
  Result := A + B;
<strong>end</strong>;

{ TStringAdder }

<strong>function</strong> TStringAdder.AddEm(A, B: <strong>string</strong>): <strong>string</strong>;
<strong>begin</strong>
  Result := IntToStr(StrToInt(A) + StrToInt(B));
<strong>end</strong>;

{ TMath&lt;T, A&gt; }

<strong>function</strong> TMath&lt;T, A&gt;.AddTwoDigits(Left, Right: T): T;
<strong>var</strong>
  Add: A;
<strong>begin</strong>
  Add := A.Create;
  <strong>try</strong>
    Result := Add.AddEm(Left, Right);
  <strong>finally</strong>
    Add.Free;
  <strong>end</strong>;
<strong>end</strong>;

<strong>end</strong>.
</code></pre>
</blockquote>
<p class="akst_link"><a href="http://blogs.teamb.com/craigstuntz/?p=37832&amp;akst_action=share-this" onclick="akst_share('37832', 'http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F08%2F29%2F37832%2F', 'D2009+Generics+and+Type+Constraints'); return false;" title="Post to del.icio.us, etc." id="akst_link_37832" class="akst_share_link" rel="nofollow">Share This</a> | <a href="mailto:?subject=D2009%20Generics%20and%20Type%20Constraints&body=Have you seen this? http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F08%2F29%2F37832%2F" id="akst_email_37832" class="akst_share_email" rel="nofollow">Email this page to a friend</a></p>]]></content:encoded>
      <wfw:commentRss></wfw:commentRss>
    </item>
  <item>
    <title>An Enumeration of Prime Numbers with Anonymous Methods</title>
    <link>http://blogs.teamb.com/craigstuntz/2008/08/28/37831/</link>
    <comments>http://blogs.teamb.com/craigstuntz/2008/08/28/37831/#comments</comments>
    <pubDate>Thu, 28 Aug 2008 13:31:25 +0000</pubDate>
    <dc:creator>Craig Stuntz</dc:creator>
    
		<category><![CDATA[Delphi]]></category>

		<category><![CDATA[General Software Development]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/craigstuntz/2008/08/28/37831</guid>
    <description><![CDATA[In this post, I am going to demonstrate a programming technique which cannot be done without anonymous methods (or lambda expressions).  I'll throw in some generics for fun.]]></description>
      <content:encoded><![CDATA[<p>In this post, I am going to demonstrate a programming technique which cannot be done without anonymous methods (or lambda expressions).  I&#8217;ll throw in some generics for fun. First, though, I need to describe the problem I&#8217;m solving.</p>
<p>I want to solve problem three of <a href="http://projecteuler.net/">Project Euler</a>. Project Euler is a web site which poses a series of programming problems intended to teach you mathematical concepts.  Here is <a href="http://projecteuler.net/index.php?section=problems&amp;id=3">problem three</a>:</p>
<blockquote><p>The prime factors of 13195 are 5, 7, 13 and 29.</p>
<p>What is the largest prime factor of the number 600851475143 ?</p></blockquote>
<p>In order to compute prime factors, it helps to have a method to return a list of primes.  A very simple algorithm to do this is called the <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes">Sieve of Eratosthenes</a>. If you don&#8217;t already know this algorithm well enough to implement it yourself, then please read the Wikipedia article I just linked before continuing.  The rest of this post will make very little sense unless you understand the Sieve.</p>
<p>I&#8217;m going to make a minor change to the algorithm described in the article. In that version, you begin by "writing a list of numbers from 2 to the largest number, say n, you want to test for primality." That won&#8217;t work for me, since I don&#8217;t know the largest number I need to test for primality.  I could guess, but I might be wrong, and, in any event, it seems inelegant.</p>
<p>So I&#8217;m going to take a different approach.  Whenever I have a need for a sequence of something, say, prime numbers, I think of enumerations.  It&#8217;s common to see enumerations over a fixed list, like strings in a TStringList, but they work just as well for infinite lists.  So I&#8217;m going to write an enumerator which returns prime numbers in ascending order.</p>
<p>The basic outline of the algorithm is this:</p>
<ol>
<li>Start with the lowest prime number.</li>
<li>Increment the current prime number.</li>
<li>Test it with a function which returns false if any of the previous prime numbers are factors of the number tested, true otherwise.</li>
<li>Repeat steps 2 and 3 until a new prime is found.</li>
</ol>
<p>Obviously, the heart of the algorithm is the function in step 3. To solve this problem without anonymous methods, I would need to maintain a list of the primes returned previously, and test each one in sequence.  That would work fine, but I am going to demonstrate a different approach.</p>
<p>Since I happen to know that 2 is prime, I&#8217;m going to start with a function which returns true.  So in step 1 I&#8217;ll begin with 1, not a prime number, but the "uninitialized" start of the enumeration.  Note that the value 1 will never be returned by the enumeration. In step 2, I&#8217;ll increment it to 2.  In step 3, I&#8217;ll test it with my function, which, at this point, returns the constant true.  So far, so good, since 2 is prime.</p>
<p>Now I need to change the function to one which excludes products of 2, the first returned prime.  That way, when we get to 4, it will be rejected by the function. In order to do this, I&#8217;m going to dynamically create a new function and substitute it for the original function which always returned true.</p>
<p>OK, enough chat.  Let&#8217;s look at some code.  First, here is the interface for the enumerator:</p>
<blockquote>
<pre><code>  TPrimeNumberEnumerator = <strong>class</strong>
  <strong>private</strong>
    FCurrent: integer;
    FIsPrime: TPredicate&lt;integer&gt;;
    <strong>function </strong>MakeFilter(CurrentPredicate: TPredicate&lt;integer&gt;; CurrentPrime: integer): TPredicate&lt;integer&gt;;
  <strong>public</strong>
    <strong>constructor </strong>Create;
    <strong>function </strong>GetCurrent: Integer;
    <strong>function </strong>MoveNext: boolean;
    <strong>procedure </strong>Reset;
    <strong>property </strong>Current: integer <strong>read </strong>GetCurrent;
  <strong>end</strong>;</code></pre>
</blockquote>
<p>The public portion of the interface is just an implementation of the enumerator pattern in Delphi, plus the constructor, which simply calls Reset.  FCurrent will hold the last prime number returned, or 1 if no primes have been returned yet. FIsPrime is a reference to a function which returns false if any of the previously returned returned primes are even factors of the integer argument passed, and true otherwise.  TPredicate&lt;integer&gt; means a function which returns a Boolean with a single, integer argument. GetCurrent just returns FCurrent. First, let&#8217;s look at Reset, which gets everything ready.</p>
<blockquote>
<pre><code><strong>procedure </strong>TPrimeNumberEnumerator.Reset;
begin
  FCurrent := 1;
  FIsPrime := <strong>function</strong>(AValue: integer): boolean
  <strong>begin</strong>
    Result := True;
  <strong>end</strong>;
<strong>end</strong>;</code></pre>
</blockquote>
<p>FCurrent is initialized to the value below the first value returned, as with many enumerator implementations. FIsPrime, at this point, ignores its argument, and simply returns true.  I used an anonymous function here for consistency with the rest of the code, but a non-anonymous function could have been used in this part. Again, since I know that 3 is prime, this trivial function is good enough for this specific case, although we&#8217;ll need something better soon!</p>
<p>The heart of the enumerator is in MoveNext and MakeFilter. Here&#8217;s MoveNext:</p>
<blockquote>
<pre><code><strong>function </strong>TPrimeNumberEnumerator.MoveNext: boolean;
begin
  Inc(FCurrent);
  <strong>while not </strong>FIsPrime(FCurrent) <strong>do </strong>Inc(FCurrent);
  FIsPrime := MakeFilter(FIsPrime, FCurrent);
  Result := true;
<strong>end</strong>;</code></pre>
</blockquote>
<p>That&#8217;s just the algorithm I described above.  Increment FCurrent, then test this value for primality.  Keep incrementing until we find a new prime. Return True, since there&#8217;s always another prime.</p>
<p>Importantly, however, when a prime is found I modify the predicate FIsPrime in such a way that it excludes products of this prime.  That&#8217;s the Sieve of Eratosthenes. Let&#8217;s look at how this is done:</p>
<blockquote>
<pre><code><strong>function </strong>TPrimeNumberEnumerator.MakeFilter(
  CurrentPredicate: TPredicate&lt;integer&gt;;
  CurrentPrime: integer): TPredicate&lt;integer&gt;;
<strong>begin</strong>
  Result := <strong>function</strong>(AValue: integer): boolean
  <strong>begin</strong>
    Result := CurrentPredicate(AValue) <strong>and </strong>((AValue <strong>mod </strong>CurrentPrime) &lt;&gt; 0);
  <strong>end</strong>;
<strong>end</strong>;
</code></pre>
</blockquote>
<p>MakeFilter takes the function it was passed plus a new prime number and returns a new function, which returns false if the passed function, CurrentPredicate, returns false or the integer argument, AValue, can be evenly divided by the prime number passed to MakeFilter.  The new function returns true, otherwise. Note that the function is "capturing" both the original function, CurrentPredicate, and CurrentPrime, both of which are arguments to MakeFilter, but not to the function returned.</p>
<p>Since I always pass FIsPrime as the CurrentPredicate argument, each time I call MakeFilter I&#8217;m enhancing FIsPrime to exclude more non-prime numbers.</p>
<p>In effect, I&#8217;m creating a new function which has only one argument, AValue, but incorporates two additional arguments, CurrentPredicate and CurrentPrime.  The difference is that CurrentPredicate and CurrentPrime are captured from the creating method and hence fixed at the time the function is <em>created</em>, whereas AValue will be specified at the time the function is <em>executed</em>.  This is a technique called <a href="http://en.wikipedia.org/wiki/Currying">currying</a>, and it&#8217;s quite common in functional programming.  You cannot do currying in the general sense without anonymous methods or lambda expressions.  So this is a new programming technique available in Delphi 2009.</p>
<p>Having done all this, I need to be able to get an instance of my enumerator:</p>
<blockquote>
<pre><code>  TPrimes = <strong>class</strong>
  <strong>public</strong>
    <strong>function </strong>GetEnumerator: TPrimeNumberEnumerator;
  <strong>end</strong>;</code></pre>
</blockquote>
<p>And now I can solve the original problem:</p>
<blockquote>
<pre><code><strong>procedure </strong>TForm4.btnGoClick(Sender: TObject);
<strong>var</strong>
  Current: integer;
  Primes: TPrimes;
  Composite: Int64;
<strong>begin</strong>
  Composite := 600851475143;
  lboResults.Items.Clear;
  Primes := TPrimes.Create;
  <strong>try</strong>
    <strong>for </strong>Current <strong>in </strong>Primes <strong>do begin</strong>
      <strong>if </strong>Composite <strong>mod </strong>Current = 0 <strong>then begin</strong>
        Composite := Composite <strong>div </strong>Current;
        lboResults.Items.Add(IntToStr(Current));
        <strong>if </strong>Composite = 1 <strong>then break</strong>;
      <strong>end</strong>;
    <strong>end</strong>;
  <strong>finally</strong>
    Primes.Free;
  <strong>end</strong>;
<strong>end</strong>;
</code></pre>
</blockquote>
<p class="akst_link"><a href="http://blogs.teamb.com/craigstuntz/?p=37831&amp;akst_action=share-this" onclick="akst_share('37831', 'http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F08%2F28%2F37831%2F', 'An+Enumeration+of+Prime+Numbers+with+Anonymous+Methods'); return false;" title="Post to del.icio.us, etc." id="akst_link_37831" class="akst_share_link" rel="nofollow">Share This</a> | <a href="mailto:?subject=An%20Enumeration%20of%20Prime%20Numbers%20with%20Anonymous%20Methods&body=Have you seen this? http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F08%2F28%2F37831%2F" id="akst_email_37831" class="akst_share_email" rel="nofollow">Email this page to a friend</a></p>]]></content:encoded>
      <wfw:commentRss></wfw:commentRss>
    </item>
  <item>
    <title>FullTrust on the LocalIntranet</title>
    <link>http://blogs.teamb.com/craigstuntz/2008/08/14/37830/</link>
    <comments>http://blogs.teamb.com/craigstuntz/2008/08/14/37830/#comments</comments>
    <pubDate>Thu, 14 Aug 2008 12:56:29 +0000</pubDate>
    <dc:creator>Craig Stuntz</dc:creator>
    
		<category><![CDATA[.NET]]></category>

		<category><![CDATA[Delphi]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/craigstuntz/2008/08/14/37830</guid>
    <description><![CDATA[I had missed this before, but with .NET Framework 3.5 SP 1, Microsoft has changed the default permission for LocalInternet to FullTrust. It can do this because .NET 3.5 SP1 also installs .NET 2.0 SP2 and .NET 3.0 SP2. This should effectively end the headache that many Delphi for.NET developers experienced when referencing (instead of [...]]]></description>
      <content:encoded><![CDATA[<p>I had missed this before, but with .NET Framework 3.5 SP 1, <a href="http://blogs.msdn.com/vancem/archive/2008/08/13/net-framework-3-5-sp1-allows-managed-code-to-be-launched-from-a-network-share.aspx" title=".NET Framework 3.5 SP1 Allows managed code to be launched from a network share!">Microsoft has changed the default permission for LocalInternet to FullTrust</a>. It can do this because .NET 3.5 SP1 also installs .NET 2.0 SP2 and .NET 3.0 SP2. This should effectively end the headache that many Delphi for.NET developers experienced when referencing (instead of statically linking) the VCL for .NET assemblies, where users could run an application locally, but would see a permission here if they copied the same application, with the VCL for .NET assemblies, to a network share.  So if your users are experiencing this problem, getting the 3.5 SP 1 Framework, available from Windows Update, should fix it.</p>
<p class="akst_link"><a href="http://blogs.teamb.com/craigstuntz/?p=37830&amp;akst_action=share-this" onclick="akst_share('37830', 'http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F08%2F14%2F37830%2F', 'FullTrust+on+the+LocalIntranet'); return false;" title="Post to del.icio.us, etc." id="akst_link_37830" class="akst_share_link" rel="nofollow">Share This</a> | <a href="mailto:?subject=FullTrust%20on%20the%20LocalIntranet&body=Have you seen this? http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F08%2F14%2F37830%2F" id="akst_email_37830" class="akst_share_email" rel="nofollow">Email this page to a friend</a></p>]]></content:encoded>
      <wfw:commentRss></wfw:commentRss>
    </item>
  <item>
    <title>Generics: Not Just for Lists</title>
    <link>http://blogs.teamb.com/craigstuntz/2008/08/07/37829/</link>
    <comments>http://blogs.teamb.com/craigstuntz/2008/08/07/37829/#comments</comments>
    <pubDate>Thu, 07 Aug 2008 15:33:27 +0000</pubDate>
    <dc:creator>Craig Stuntz</dc:creator>
    
		<category><![CDATA[Delphi]]></category>

		<category><![CDATA[General Software Development]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/craigstuntz/2008/08/07/37829</guid>
    <description><![CDATA[It appears that the next version of Delphi, code-named Tiburón, will include support for generic types in the Win32 compiler.  Developers without .NET experience may not be familiar with use cases for generics.  Of course, generics work really well for typed containers, and this is often the first example that people give as a use case.  But they have many other uses as well.  I'll give a few examples; I hope this will help Delphi developers think about how they might want to use the feature in their own code.]]></description>
      <content:encoded><![CDATA[<p>It appears that <a href="http://dn.codegear.com/article/36620" title="Delphi and C++Builder Roadmap ">the next version of Delphi, code-named Tibur<span>ó</span>n</a>, will include support for generic types in the Win32 compiler.  Developers without .NET experience may not be familiar with use cases for generics.  Of course, generics work really well for typed containers, and this is often the first example that people give as a use case.  But they have many other uses as well.  I&#8217;ll give a few examples; I hope this will help Delphi developers think about how they might want to use the feature in their own code.</p>
<h3>Nullable&lt;T&gt;</h3>
<p>It&#8217;s common to have a reference in code to a value read in from a database.  Of course, most databases allow NULL, whereas many scalar types, like integer, do not. So a programmer can either choose to designate a certain scalar value as a "NULL flag," which can cause problems when that value is actually stored in the database, or to have a separate, Boolean reference indicating whether the other variable should, in fact, be treated as NULL.  Neither solution is great. A better way is to build a single structure which stores both the NULL flag and the scalar value.  This is a more elegant way of storing the value retrieved from the database, but it gets tedious and hard to maintain when you have to create such a structure for many different types.  Using a generic Nullable&lt;T&gt;, however, you can use a single type which can store a reference to any value, whether scalar or not.</p>
<h3>Mocks</h3>
<p>Generics work really well for mock classes used in unit testing.  Briefly, a mock is an object which appears to be of a certain type, but is, in fact, just an imitation of that type.  You use a mock in a unit test when including the actual object would make the unit test dependent on things which are not practical or advisable to include in a unit test, like a web service.  The mock can pretend to be the web service and return data without actually making an Internet connection.</p>
<p>Mocking is one of those things which is really simple to implement for one specific case, and fairly hard to implement for a general case.  You can fairly easily create a mock for one specific type.  It&#8217;s quite a bit harder to create a mocking framework which can imitate any type. But generics help a lot.</p>
<p>In my unit tests for my ASP.NET MVC web applications, I need to mock the HttpContext, since the version included with the .NET framework polls and a whole bunch of stuff related to web applications which I don&#8217;t need for the unit test.  So I use the <a href="http://code.google.com/p/moq/">Moq</a> framework and <a href="http://blogs.teamb.com/craigstuntz/2008/07/10/37824" title="Moq and MvcMockHelpers">a mocked context which I posted earlier</a>.  In general, to create a mock of a certain type using Moq, you write:</p>
<blockquote>
<pre><strong>var </strong>mockobject = <strong>new </strong>Mock&lt;TypeToMock&gt;();</pre>
</blockquote>
<p>After some additional code to specify what values the methods and properties of the "fake" TypeToMock should return, I can then supply the mocked object to some other instance which expects a "real" instance of TypeToMock, and it will be none the wiser:</p>
<blockquote>
<pre>testInstance.TypeToMockProperty = mockobject.Object;</pre>
</blockquote>
<p>Now, a full explanation of how to use the Moq framework is outside of the scope of this post; you can read <a href="http://code.google.com/p/moq/wiki/QuickStart" title="Introduction to Moq">a brief tutorial at the Moq site</a> if you&#8217;re interested.  But the important point is that mockobject.Object appears to the outside world to be an instance of TypeToMock, even though it isn&#8217;t, and doesn&#8217;t carry any of the baggage that the "real" TypeToMock might have.</p>
<h3>MVC</h3>
<p>Another area where I&#8217;ve found generics to be really helpful is when passing a model to a view in an ASP.NET MVC web application.  MVC View pages have a property called ViewData.Model which returns a model instance that was passed by the controller.  By default, this is of type System.Object, which means that you have to cast it to do anything useful with it.  But by using generics, you can get rid of the casts.  Let&#8217;s say that the model I want to supply to the view is of type MyModel.  I changed the view declaration from this:</p>
<blockquote>
<pre><strong>public partial class </strong>MyView : ViewPage</pre>
</blockquote>
<p>&#8230;to this:</p>
<blockquote>
<pre><strong>public partial class </strong>MyView : ViewPage&lt;MyModel&gt;</pre>
</blockquote>
<p>ViewPage&lt;MyModel&gt; is a different type than ViewPage (without the generic type parameter).  MyView is now subclassing a different parent type. In particular, the property ViewData.Model of ViewPage&lt;MyModel&gt; will be of type MyModel instead of type System.Object.  This means that in the code for my View, I can access properties of my model type directly, without any casts, like this:</p>
<blockquote>
<pre>editLink.HRef = ViewData.Model.EditUrl;</pre>
</blockquote>
<p>Note that this is not some kind of disguised cast. With a cast, you either sacrifice performance (with a safe/soft cast) or type safety (with an unsafe/hard cast).  With a generic, you don&#8217;t make either sacrifice.  Type checking is performed at compile time, just like with a property of a non-generic type.</p>
<h3>So When Should I Use Generics?</h3>
<p>There are some "<a href="http://en.wikipedia.org/wiki/Code_smell">code smells</a>" which indicate that you should consider using a generic type.  Whenever you find yourself writing similar code over and over again just to change one or two types (e.g., the type-safe lists that most of us have built in Delphi), or whenever you find yourself casting a reference regularly to the same type, you might want to consider using a generic type instead.</p>
<p class="akst_link"><a href="http://blogs.teamb.com/craigstuntz/?p=37829&amp;akst_action=share-this" onclick="akst_share('37829', 'http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F08%2F07%2F37829%2F', 'Generics%3A+Not+Just+for+Lists'); return false;" title="Post to del.icio.us, etc." id="akst_link_37829" class="akst_share_link" rel="nofollow">Share This</a> | <a href="mailto:?subject=Generics%3A%20Not%20Just%20for%20Lists&body=Have you seen this? http%3A%2F%2Fblogs.teamb.com%2Fcraigstuntz%2F2008%2F08%2F07%2F37829%2F" id="akst_email_37829" class="akst_share_email" rel="nofollow">Email this page to a friend</a></p>]]></content:encoded>
      <wfw:commentRss></wfw:commentRss>
    </item>
  <item>
    <title>Understanding Anonymous Methods</title>
    <link>http://blogs.teamb.com/craigstuntz/2008/08/04/37828/</link>
    <comments>http://blogs.teamb.com/craigstuntz/2008/08/04/37828/#comments</comments>
    <pubDate>Mon, 04 Aug 2008 14:37:16 +0000</pubDate>
    <dc:creator>Craig Stuntz</dc:creator>
    
		<category><![CDATA[Delphi]]></category>

    <guid isPermaLink="false">http://blogs.teamb.com/craigstuntz/2008/08/04/37828</guid>
    <description><![CDATA[It appears that the next version of Delphi will support a feature called anonymous methods.  The circumstances in which one might use an anonymous method do not seem to be obvious to everyone in the Delphi community, so I'm going to attempt to answer that.]]></description>
      <content:encoded><![CDATA[<p>It appears that the next version of Delphi will support a feature called anonymous methods.  The circumstances in which one might use an anonymous method do not seem to be obvious to everyone in the Delphi community, so I&#8217;m going to attempt to answer that.</p>
<p>There is, at the moment, no shipping version of Delphi which includes anonymous methods, so I&#8217;m basing my discussion on my experiences using them in other environments.  The final, released version may include a different feature set and what I describe below.</p>
<p>First, let&#8217;s answer the obvious question, with the obvious answer: What can I do with an anonymous method which I can&#8217;t do without an anonymous method?  <strong>Nothing</strong>.  In fact, there&#8217;s nothing which you can do with Delphi which you cannot do with ASM.  Anonymous methods are a convenience suited to certain styles of programming, like strong, static typing, and object orientation.  They will probably seem useless to people who do not adopt those styles of programming, just as virtual methods will seem useless or dangerous to a non-OO programmer.</p>
<p>I suspect that most "Pascal programmers" view procedures as being a fundamentally different type than other data structures.  In the static typing the world, we typically define the shape of a data structure at compile time, and the contents at runtime.  By contrast, even when passing a procedure as an argument to another procedure, in older versions of Delphi we have had to define both the shape and the contents of the procedure at compile time.  Only the arguments can be set at runtime.</p>
<p>With one exception: Nested procedures.  Let&#8217;s talk about that, for a moment.</p>
<h3>Nested procedures, scope, and variable capture</h3>
<p>Nested procedures are procedures declared inside of another procedure.  This essentially reduces the scope of the nested procedure to being callable within the nesting procedure only: Here is a simple example.</p>
<blockquote>
<pre><strong>procedure </strong>MyClass.Foo;
<strong>var</strong>
  i: integer;
  <strong>procedure </strong>Bar;
  <strong>begin</strong>
    Inc(i);
  <strong>end</strong>;
<strong>begin</strong>
  i := 1;
  Bar;
  WriteLn(IntToStr(i));
 