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

<channel>
	<title>stacyprowell.com &#187; Programming</title>
	<atom:link href="http://stacyprowell.com/blog/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://stacyprowell.com/blog</link>
	<description>Ugh, Stacy's talking again...</description>
	<lastBuildDate>Tue, 27 Apr 2010 20:09:26 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Watched Properties in Scala</title>
		<link>http://stacyprowell.com/blog/2010/04/27/watched-properties-in-scala/</link>
		<comments>http://stacyprowell.com/blog/2010/04/27/watched-properties-in-scala/#comments</comments>
		<pubDate>Tue, 27 Apr 2010 20:08:39 +0000</pubDate>
		<dc:creator>stacy</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[linkedin]]></category>

		<guid isPermaLink="false">http://stacyprowell.com/blog/?p=471</guid>
		<description><![CDATA[Scala is pretty damn neat.  I&#8217;ve only just started learning the language (an earlier attempt had to be sidelined because &#8220;real&#8221; work interfered), but I&#8217;m back to it now.
Properties
Here&#8217;s a funny little class I&#8217;ve been playing with in some development work.

class Property&#91;T&#93;&#40;var value:T&#41; &#123;
  def get:T = value
  def set&#40;newval:T&#41; = &#123;
  [...]]]></description>
			<content:encoded><![CDATA[<p>Scala is pretty damn neat.  I&#8217;ve only just started learning the language (an earlier attempt had to be sidelined because &#8220;real&#8221; work interfered), but I&#8217;m back to it now.<span id="more-471"></span></p>
<h1>Properties</h1>
<p>Here&#8217;s a funny little class I&#8217;ve been playing with in some development work.</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">class</span> Property<span style="color: #F78811;">&#91;</span>T<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span><span style="color: #0000ff; font-weight: bold;">var</span> value<span style="color: #000080;">:</span>T<span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#123;</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> get<span style="color: #000080;">:</span>T <span style="color: #000080;">=</span> value
  <span style="color: #0000ff; font-weight: bold;">def</span> set<span style="color: #F78811;">&#40;</span>newval<span style="color: #000080;">:</span>T<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">&#123;</span>
    value <span style="color: #000080;">=</span> newval
    <span style="color: #0000ff; font-weight: bold;">this</span>
  <span style="color: #F78811;">&#125;</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> <span style="color: #000080;">:=</span><span style="color: #F78811;">&#40;</span>newval<span style="color: #000080;">:</span>T<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> set<span style="color: #F78811;">&#40;</span>newval<span style="color: #F78811;">&#41;</span>
  <span style="color: #0000ff; font-weight: bold;">override</span> <span style="color: #0000ff; font-weight: bold;">def</span> toString <span style="color: #000080;">=</span> <span style="color: #6666FF;">&quot;Property(&quot;</span> + value + <span style="color: #6666FF;">&quot;)&quot;</span>
<span style="color: #F78811;">&#125;</span>
<span style="color: #0000ff; font-weight: bold;">implicit</span> <span style="color: #0000ff; font-weight: bold;">def</span> Property2value<span style="color: #F78811;">&#91;</span>T<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span>prop<span style="color: #000080;">:</span>Property<span style="color: #F78811;">&#91;</span>T<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> prop.<span style="color: #000000;">get</span></pre></div></div>

<p>I think that&#8217;s just too neat.  The property can be set with the (admittedly PL/1-ish) := operator, and the value can be extracted with a cast or assignment.</p>
<p>If I could override the assignment then I could make this very, very C++-ish-ish.  Note that I could have written something like the following.</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">def</span> `<span style="color: #000080;">=</span>`<span style="color: #F78811;">&#40;</span>newval<span style="color: #000080;">:</span>T<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> set<span style="color: #F78811;">&#40;</span>newval<span style="color: #F78811;">&#41;</span></pre></div></div>

<p>But then I&#8217;d have to use this as follows.</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;">scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">val</span> p <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> Property<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">12</span><span style="color: #F78811;">&#41;</span>
scala<span style="color: #000080;">&gt;</span> p `<span style="color: #000080;">=</span>` <span style="color: #F78811;">13</span></pre></div></div>

<p>That&#8217;s just not the same thing.  Scala does not allow overriding assignment; no copy constructor for you.</p>
<p>If you are willing to declare p to be a var, then you can do the following.  But this is really not what you want since it creates a new property, and does not modify the value of the existing property.</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;">scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">def</span> ValueToProperty<span style="color: #F78811;">&#91;</span>T<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span>value<span style="color: #000080;">:</span>T<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> Property<span style="color: #F78811;">&#40;</span>value<span style="color: #F78811;">&#41;</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">var</span> p <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> Property<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">12</span><span style="color: #F78811;">&#41;</span>
p<span style="color: #000080;">:</span> Property<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> Property<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">12</span><span style="color: #F78811;">&#41;</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> p <span style="color: #000080;">=</span> <span style="color: #F78811;">171</span>
p<span style="color: #000080;">:</span> Property<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> Property<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">171</span><span style="color: #F78811;">&#41;</span></pre></div></div>

<h1>Watched Property</h1>
<p>So what&#8217;s the point of having this mutable property class?  Well, now that I have the above I can add code to watch the property.</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">trait</span> Watcher<span style="color: #F78811;">&#91;</span>T,U<span style="color: #F78811;">&#93;</span> <span style="color: #F78811;">&#123;</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> notify<span style="color: #F78811;">&#40;</span>value<span style="color: #000080;">:</span>T, data<span style="color: #000080;">:</span>U<span style="color: #F78811;">&#41;</span>
<span style="color: #F78811;">&#125;</span>
<span style="color: #0000ff; font-weight: bold;">trait</span> Watchable<span style="color: #F78811;">&#91;</span>T,U<span style="color: #F78811;">&#93;</span> <span style="color: #F78811;">&#123;</span>
  <span style="color: #0000ff; font-weight: bold;">var</span> watchers<span style="color: #000080;">:</span>Map<span style="color: #F78811;">&#91;</span>Watcher<span style="color: #F78811;">&#91;</span>T,U<span style="color: #F78811;">&#93;</span>,U<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> Map<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#41;</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> register<span style="color: #F78811;">&#40;</span>watch<span style="color: #000080;">:</span>Watcher<span style="color: #F78811;">&#91;</span>T,U<span style="color: #F78811;">&#93;</span>, data<span style="color: #000080;">:</span>U<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">&#123;</span>
    watchers +<span style="color: #000080;">=</span> <span style="color: #F78811;">&#40;</span>watch -<span style="color: #000080;">&gt;</span> data<span style="color: #F78811;">&#41;</span>
  <span style="color: #F78811;">&#125;</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> notify<span style="color: #F78811;">&#40;</span>value<span style="color: #000080;">:</span>T<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">&#123;</span>
    watchers foreach <span style="color: #F78811;">&#123;</span>
      <span style="color: #0000ff; font-weight: bold;">case</span> <span style="color: #F78811;">&#40;</span>watcher, data<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=&gt;</span> watcher.<span style="color: #000000;">notify</span><span style="color: #F78811;">&#40;</span>value, data<span style="color: #F78811;">&#41;</span>
    <span style="color: #F78811;">&#125;</span>
  <span style="color: #F78811;">&#125;</span>
<span style="color: #F78811;">&#125;</span>
<span style="color: #0000ff; font-weight: bold;">class</span> WatchedProperty<span style="color: #F78811;">&#91;</span>T,U<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span>value<span style="color: #000080;">:</span>T<span style="color: #F78811;">&#41;</span> <span style="color: #0000ff; font-weight: bold;">extends</span> Property<span style="color: #F78811;">&#40;</span>value<span style="color: #F78811;">&#41;</span> <span style="color: #0000ff; font-weight: bold;">with</span> Watchable<span style="color: #F78811;">&#91;</span>T,U<span style="color: #F78811;">&#93;</span> <span style="color: #F78811;">&#123;</span>
  <span style="color: #0000ff; font-weight: bold;">override</span> <span style="color: #0000ff; font-weight: bold;">def</span> set<span style="color: #F78811;">&#40;</span>newval<span style="color: #000080;">:</span>T<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">&#123;</span>
    <span style="color: #0000ff; font-weight: bold;">super</span>.<span style="color: #000000;">set</span><span style="color: #F78811;">&#40;</span>newval<span style="color: #F78811;">&#41;</span>
    notify<span style="color: #F78811;">&#40;</span>newval<span style="color: #F78811;">&#41;</span>
    <span style="color: #0000ff; font-weight: bold;">this</span>
  <span style="color: #F78811;">&#125;</span>
<span style="color: #F78811;">&#125;</span></pre></div></div>

<p>Now I have a watcher and a watchable.  I mix in the watchable trait with the property, and presto!  I have a watched property.  It&#8217;s somewhat of a big deal for some work I&#8217;m doing now; this would have made my life <em>much</em> easier.</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">class</span> See<span style="color: #F78811;">&#91;</span>T,U<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#41;</span> <span style="color: #0000ff; font-weight: bold;">extends</span> Watcher<span style="color: #F78811;">&#91;</span>T,U<span style="color: #F78811;">&#93;</span> <span style="color: #F78811;">&#123;</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> notify<span style="color: #F78811;">&#40;</span>value<span style="color: #000080;">:</span>T, data<span style="color: #000080;">:</span>U<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">&#123;</span>
    println<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;Value is now &quot;</span> + value + <span style="color: #6666FF;">&quot; and data is &quot;</span> + data + <span style="color: #6666FF;">&quot;.&quot;</span><span style="color: #F78811;">&#41;</span>
  <span style="color: #F78811;">&#125;</span>
<span style="color: #F78811;">&#125;</span></pre></div></div>

<p>Finally, we do some &#8220;work.&#8221;</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;">scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">val</span> see <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> See<span style="color: #F78811;">&#91;</span>Int,String<span style="color: #F78811;">&#93;</span>
see<span style="color: #000080;">:</span> See<span style="color: #F78811;">&#91;</span>Int,String<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> See<span style="color: #000080;">@</span>fab91
&nbsp;
scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">val</span> watch <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> WatchedProperty<span style="color: #F78811;">&#91;</span>Int,String<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1</span><span style="color: #F78811;">&#41;</span>
watch<span style="color: #000080;">:</span> WatchedProperty<span style="color: #F78811;">&#91;</span>Int,String<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> Property<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">1</span><span style="color: #F78811;">&#41;</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> watch register <span style="color: #F78811;">&#40;</span>see,<span style="color: #6666FF;">&quot;watch&quot;</span><span style="color: #F78811;">&#41;</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> watch <span style="color: #000080;">:=</span> <span style="color: #F78811;">12</span>
Value is now <span style="color: #F78811;">12</span> and data is watch.
<span style="color: #000000;">res22</span><span style="color: #000080;">:</span> Property<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> Property<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">12</span><span style="color: #F78811;">&#41;</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> watch <span style="color: #000080;">:=</span> <span style="color: #F78811;">31</span>
Value is now <span style="color: #F78811;">31</span> and data is watch.
<span style="color: #000000;">res23</span><span style="color: #000080;">:</span> Property<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> Property<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">31</span><span style="color: #F78811;">&#41;</span></pre></div></div>

<p>Of course, I can also avoid new by declaring the companion object for WatchedProperty and adding a factory method.  Life in Scala is pretty good (so far).</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">object</span> WatchedProperty <span style="color: #F78811;">&#123;</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> apply<span style="color: #F78811;">&#91;</span>T,U<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span>value<span style="color: #000080;">:</span>T<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> WatchedProperty<span style="color: #F78811;">&#91;</span>T,U<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span>value<span style="color: #F78811;">&#41;</span>
<span style="color: #F78811;">&#125;</span></pre></div></div>

<h1>Cleaner Watched Property</h1>
<p>There is a problem with the implementation of watched property, and it is the type annotation U.  Why should the property have to know the type for the data?  The data only exists for the benefit of the watcher.  Worse, the watched property isn&#8217;t a drop-in replacement for property; it has two parameters instead of just one.  Finally, everyone who wants to register must use the same data type U (or a subclass).  Here are some alternatives.</p>
<ol>
<li>The watcher can maintain a map from watched property to the associated data.  The watched property can then send itself with the property change notification.  This is <em>bad</em>.  The watcher has to maintain the map.  If it is watching a lot of properties then it may have to maintain a big map, and there is lookup overhead.  We avoid that by having the property return the data with the notification.</li>
<li>We could treat the data as an Any.  Then it is the responsibility of the watcher to correctly cast the value during notification.  This is a nuisance because the compiler cannot catch type problems for us, but Java programmers should be used to that by now.</li>
</ol>
<p>Let&#8217;s try the second approach.</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">trait</span> Watcher<span style="color: #F78811;">&#91;</span>T<span style="color: #F78811;">&#93;</span> <span style="color: #F78811;">&#123;</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> notify<span style="color: #F78811;">&#40;</span>value<span style="color: #000080;">:</span>T, data<span style="color: #000080;">:</span>Any<span style="color: #F78811;">&#41;</span>
<span style="color: #F78811;">&#125;</span>
<span style="color: #0000ff; font-weight: bold;">trait</span> Watchable<span style="color: #F78811;">&#91;</span>T<span style="color: #F78811;">&#93;</span> <span style="color: #F78811;">&#123;</span>
  <span style="color: #0000ff; font-weight: bold;">var</span> watchers<span style="color: #000080;">:</span>Map<span style="color: #F78811;">&#91;</span>Watcher<span style="color: #F78811;">&#91;</span>T<span style="color: #F78811;">&#93;</span>,Any<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> Map<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#41;</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> register<span style="color: #F78811;">&#40;</span>watch<span style="color: #000080;">:</span>Watcher<span style="color: #F78811;">&#91;</span>T<span style="color: #F78811;">&#93;</span>, data<span style="color: #000080;">:</span>Any<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">&#123;</span>
    watchers +<span style="color: #000080;">=</span> <span style="color: #F78811;">&#40;</span>watch -<span style="color: #000080;">&gt;</span> data<span style="color: #F78811;">&#41;</span>
  <span style="color: #F78811;">&#125;</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> notify<span style="color: #F78811;">&#40;</span>value<span style="color: #000080;">:</span>T<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">&#123;</span>
    watchers foreach <span style="color: #F78811;">&#123;</span>
      <span style="color: #0000ff; font-weight: bold;">case</span> <span style="color: #F78811;">&#40;</span>watcher, data<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=&gt;</span> watcher.<span style="color: #000000;">notify</span><span style="color: #F78811;">&#40;</span>value, data<span style="color: #F78811;">&#41;</span>
    <span style="color: #F78811;">&#125;</span>
  <span style="color: #F78811;">&#125;</span>
<span style="color: #F78811;">&#125;</span>
<span style="color: #0000ff; font-weight: bold;">class</span> WatchedProperty<span style="color: #F78811;">&#91;</span>T<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span>value<span style="color: #000080;">:</span>T<span style="color: #F78811;">&#41;</span> <span style="color: #0000ff; font-weight: bold;">extends</span> Property<span style="color: #F78811;">&#40;</span>value<span style="color: #F78811;">&#41;</span> <span style="color: #0000ff; font-weight: bold;">with</span> Watchable<span style="color: #F78811;">&#91;</span>T<span style="color: #F78811;">&#93;</span> <span style="color: #F78811;">&#123;</span>
  <span style="color: #0000ff; font-weight: bold;">override</span> <span style="color: #0000ff; font-weight: bold;">def</span> set<span style="color: #F78811;">&#40;</span>newval<span style="color: #000080;">:</span>T<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">&#123;</span>
    <span style="color: #0000ff; font-weight: bold;">super</span>.<span style="color: #000000;">set</span><span style="color: #F78811;">&#40;</span>newval<span style="color: #000080;">:</span>T<span style="color: #F78811;">&#41;</span>
    notify<span style="color: #F78811;">&#40;</span>newval<span style="color: #F78811;">&#41;</span>
    <span style="color: #0000ff; font-weight: bold;">this</span>
  <span style="color: #F78811;">&#125;</span>
<span style="color: #F78811;">&#125;</span></pre></div></div>

<p>That&#8217;s better, actually.  Watched property is again a referentially-transparent replacement for property, and watchers can use any data type they want.  What could be better than this?</p>
<h1>Better Watched Property</h1>
<p>Actually that whole &#8220;Any&#8221; value is the problem now.  This implementation cleans up the design a bit with better information hiding and referential transparency, but it also musses up type safety a bit.  The watcher knows the type of the data; why can&#8217;t it get back properly-typed data during notification?</p>
<p>Maybe we&#8217;ve been asking the wrong question.  The issue is, I think, the Java-esque nature of the solution.  Why does notify really have to be passed the data?  Why not do something very different?  In fact, why not get rid of the watcher trait altogether?  Why do we need it?  We really just want to invoke a function (or method) when the property is changed.  Let&#8217;s just directly register the callback, and forget the middleman.</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">trait</span> Watchable<span style="color: #F78811;">&#91;</span>T<span style="color: #F78811;">&#93;</span> <span style="color: #F78811;">&#123;</span>
  <span style="color: #0000ff; font-weight: bold;">var</span> watchers<span style="color: #000080;">:</span>List<span style="color: #F78811;">&#91;</span><span style="color: #F78811;">&#40;</span>T<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=&gt;</span> Unit<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> List<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#41;</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> register<span style="color: #F78811;">&#40;</span>notify<span style="color: #000080;">:</span><span style="color: #F78811;">&#40;</span>T<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=&gt;</span> Unit<span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#123;</span>
    watchers +<span style="color: #000080;">=</span> notify
  <span style="color: #F78811;">&#125;</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> notify<span style="color: #F78811;">&#40;</span>value<span style="color: #000080;">:</span>T<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">&#123;</span>
    watchers foreach <span style="color: #F78811;">&#40;</span>notify <span style="color: #000080;">=&gt;</span> notify<span style="color: #F78811;">&#40;</span>value<span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
  <span style="color: #F78811;">&#125;</span>
<span style="color: #F78811;">&#125;</span>
<span style="color: #0000ff; font-weight: bold;">class</span> WatchedProperty<span style="color: #F78811;">&#91;</span>T<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span>value<span style="color: #000080;">:</span>T<span style="color: #F78811;">&#41;</span> <span style="color: #0000ff; font-weight: bold;">extends</span> Property<span style="color: #F78811;">&#40;</span>value<span style="color: #F78811;">&#41;</span> <span style="color: #0000ff; font-weight: bold;">with</span> Watchable<span style="color: #F78811;">&#91;</span>T<span style="color: #F78811;">&#93;</span> <span style="color: #F78811;">&#123;</span>
  <span style="color: #0000ff; font-weight: bold;">override</span> <span style="color: #0000ff; font-weight: bold;">def</span> set<span style="color: #F78811;">&#40;</span>newval<span style="color: #000080;">:</span>T<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> <span style="color: #F78811;">&#123;</span>
    <span style="color: #0000ff; font-weight: bold;">super</span>.<span style="color: #000000;">set</span><span style="color: #F78811;">&#40;</span>newval<span style="color: #F78811;">&#41;</span>
    notify<span style="color: #F78811;">&#40;</span>newval<span style="color: #F78811;">&#41;</span>
    <span style="color: #0000ff; font-weight: bold;">this</span>
  <span style="color: #F78811;">&#125;</span>
<span style="color: #F78811;">&#125;</span></pre></div></div>

<p>Watcher is gone.  The data item is gone.  The funny type problem is gone.  The code is simpler, and even more flexible, since anything can be a watcher, including lambdas.</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;">scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">val</span> prop <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> WatchedProperty<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">21</span><span style="color: #F78811;">&#41;</span>
prop<span style="color: #000080;">:</span> WatchedProperty<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> Property<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">21</span><span style="color: #F78811;">&#41;</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">def</span> see<span style="color: #F78811;">&#40;</span>x<span style="color: #000080;">:</span>Int<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=</span> println<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;Value changed to: &quot;</span> + x + <span style="color: #6666FF;">&quot;.&quot;</span><span style="color: #F78811;">&#41;</span>
see<span style="color: #000080;">:</span> <span style="color: #F78811;">&#40;</span>Int<span style="color: #F78811;">&#41;</span>Unit
&nbsp;
scala<span style="color: #000080;">&gt;</span> prop.<span style="color: #000000;">register</span><span style="color: #F78811;">&#40;</span>see<span style="color: #F78811;">&#41;</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> prop.<span style="color: #000000;">register</span><span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#40;</span>x<span style="color: #000080;">:</span>Int<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=&gt;</span> println<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;Lambda sees value: &quot;</span> + x + <span style="color: #6666FF;">&quot;.&quot;</span><span style="color: #F78811;">&#41;</span><span style="color: #F78811;">&#41;</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> prop <span style="color: #000080;">:=</span> <span style="color: #F78811;">413</span>
Value changed to<span style="color: #000080;">:</span> 413.
<span style="color: #000000;">Lambda</span> sees value<span style="color: #000080;">:</span> 413.
<span style="color: #000000;">res10</span><span style="color: #000080;">:</span> Property<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> Property<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">413</span><span style="color: #F78811;">&#41;</span></pre></div></div>

<h1>Data Again</h1>
<p>Well, what about data?  The value for data can be captured in a closure.  Here&#8217;s an example, where the data is a name for the property being monitored.</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">class</span> ChangeWatcher <span style="color: #F78811;">&#123;</span>
  <span style="color: #0000ff; font-weight: bold;">def</span> watch<span style="color: #F78811;">&#91;</span>T<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span>prop<span style="color: #000080;">:</span>WatchedProperty<span style="color: #F78811;">&#91;</span>T<span style="color: #F78811;">&#93;</span>, name<span style="color: #000080;">:</span>String<span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#123;</span>
    prop register <span style="color: #F78811;">&#123;</span>
      <span style="color: #F78811;">&#40;</span>value<span style="color: #000080;">:</span>T<span style="color: #F78811;">&#41;</span> <span style="color: #000080;">=&gt;</span> println<span style="color: #F78811;">&#40;</span>name + <span style="color: #6666FF;">&quot;: &quot;</span> + value<span style="color: #F78811;">&#41;</span>
    <span style="color: #F78811;">&#125;</span>
  <span style="color: #F78811;">&#125;</span>
<span style="color: #F78811;">&#125;</span></pre></div></div>

<p>Did you get all that?  The above is a fully-generic watcher.  You pass it a property and a name for the property.  Whenever the property is changed, it notifies you.  This works for any kind of property.</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;">scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">val</span> prop <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> WatchedProperty<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">21</span><span style="color: #F78811;">&#41;</span>
prop<span style="color: #000080;">:</span> WatchedProperty<span style="color: #F78811;">&#91;</span>Int<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> Property<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">21</span><span style="color: #F78811;">&#41;</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">val</span> status <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> WatchedProperty<span style="color: #F78811;">&#40;</span><span style="color: #6666FF;">&quot;okay&quot;</span><span style="color: #F78811;">&#41;</span>
status<span style="color: #000080;">:</span> WatchedProperty<span style="color: #F78811;">&#91;</span>java.<span style="color: #000000;">lang</span>.<span style="color: #000000;">String</span><span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> Property<span style="color: #F78811;">&#40;</span>okay<span style="color: #F78811;">&#41;</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">val</span> temp <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> WatchedProperty<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">21.8</span><span style="color: #F78811;">&#41;</span>
temp<span style="color: #000080;">:</span> WatchedProperty<span style="color: #F78811;">&#91;</span>Double<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> Property<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">21.8</span><span style="color: #F78811;">&#41;</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> <span style="color: #0000ff; font-weight: bold;">val</span> cw <span style="color: #000080;">=</span> <span style="color: #0000ff; font-weight: bold;">new</span> ChangeWatcher
cw<span style="color: #000080;">:</span> ChangeWatcher <span style="color: #000080;">=</span> ChangeWatcher<span style="color: #000080;">@</span>3da8bc
&nbsp;
scala<span style="color: #000080;">&gt;</span> cw.<span style="color: #000000;">watch</span><span style="color: #F78811;">&#40;</span>prop, <span style="color: #6666FF;">&quot;prop&quot;</span><span style="color: #F78811;">&#41;</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> cw.<span style="color: #000000;">watch</span><span style="color: #F78811;">&#40;</span>status, <span style="color: #6666FF;">&quot;status&quot;</span><span style="color: #F78811;">&#41;</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> cw.<span style="color: #000000;">watch</span><span style="color: #F78811;">&#40;</span>temp, <span style="color: #6666FF;">&quot;temperature&quot;</span><span style="color: #F78811;">&#41;</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> status <span style="color: #000080;">:=</span> <span style="color: #6666FF;">&quot;Danger!&quot;</span>
status<span style="color: #000080;">:</span> Danger<span style="color: #000080;">!</span>
res18<span style="color: #000080;">:</span> Property<span style="color: #F78811;">&#91;</span>java.<span style="color: #000000;">lang</span>.<span style="color: #000000;">String</span><span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> Property<span style="color: #F78811;">&#40;</span>Danger<span style="color: #000080;">!</span><span style="color: #F78811;">&#41;</span>
&nbsp;
scala<span style="color: #000080;">&gt;</span> temp <span style="color: #000080;">:=</span> <span style="color: #F78811;">73.2</span>
temperature<span style="color: #000080;">:</span> <span style="color: #F78811;">73.2</span>
res19<span style="color: #000080;">:</span> Property<span style="color: #F78811;">&#91;</span>Double<span style="color: #F78811;">&#93;</span> <span style="color: #000080;">=</span> Property<span style="color: #F78811;">&#40;</span><span style="color: #F78811;">73.2</span><span style="color: #F78811;">&#41;</span></pre></div></div>

<p>The important thing to note is that you don&#8217;t have to have data.  Or you can have lots of data.  Or whatever you want.  The responsibility for data is all back to the watcher, and off the shoulders of the watchable.  This seems (to me) to be the correct division of responsibility.</p>
<p>To sum up: Functional Programming + Objects = Good.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fstacyprowell.com%2Fblog%2F2010%2F04%2F27%2Fwatched-properties-in-scala%2F&amp;linkname=Watched%20Properties%20in%20Scala"><img src="http://stacyprowell.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://stacyprowell.com/blog/2010/04/27/watched-properties-in-scala/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Silly Scala Tricks</title>
		<link>http://stacyprowell.com/blog/2009/11/12/silly-scala-tricks/</link>
		<comments>http://stacyprowell.com/blog/2009/11/12/silly-scala-tricks/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 04:53:10 +0000</pubDate>
		<dc:creator>stacy</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Scala]]></category>
		<category><![CDATA[linkedin]]></category>

		<guid isPermaLink="false">http://stacyprowell.com/blog/?p=449</guid>
		<description><![CDATA[One of the things I have in my Scala startup file is the following.

def show&#91;T&#93;&#40;implicit thetype:scala.reflect.Manifest&#91;T&#93;&#41; &#123;
  thetype.erasure.getMethods&#40;&#41; foreach println
&#125;
def help&#40;x:AnyRef&#41; &#123;
  x.getClass&#40;&#41;.getMethods&#40;&#41; foreach println
&#125;

These silly little functions are useful &#8211; at least, to me. Now when I can&#8217;t remember the name of a method I can type something like the following at [...]]]></description>
			<content:encoded><![CDATA[<p>One of the things I have in my Scala startup file is the following.</p>

<div class="wp_syntax"><div class="code"><pre class="scala" style="font-family:monospace;"><span style="color: #0000ff; font-weight: bold;">def</span> show<span style="color: #F78811;">&#91;</span>T<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#40;</span><span style="color: #0000ff; font-weight: bold;">implicit</span> thetype<span style="color: #000080;">:</span>scala.<span style="color: #000000;">reflect</span>.<span style="color: #000000;">Manifest</span><span style="color: #F78811;">&#91;</span>T<span style="color: #F78811;">&#93;</span><span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#123;</span>
  thetype.<span style="color: #000000;">erasure</span>.<span style="color: #000000;">getMethods</span><span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#41;</span> foreach println
<span style="color: #F78811;">&#125;</span>
<span style="color: #0000ff; font-weight: bold;">def</span> help<span style="color: #F78811;">&#40;</span>x<span style="color: #000080;">:</span>AnyRef<span style="color: #F78811;">&#41;</span> <span style="color: #F78811;">&#123;</span>
  x.<span style="color: #000000;">getClass</span><span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#41;</span>.<span style="color: #000000;">getMethods</span><span style="color: #F78811;">&#40;</span><span style="color: #F78811;">&#41;</span> foreach println
<span style="color: #F78811;">&#125;</span></pre></div></div>

<p>These silly little functions are useful &#8211; at least, to me. Now when I can&#8217;t remember the name of a method I can type something like the following at the Scala prompt.<span id="more-449"></span></p>
<pre>scala&gt; help(Map())
public scala.Option scala.collection.immutable.EmptyMap.get(java.lang.Object)
public int scala.collection.immutable.EmptyMap.hashCode()
public boolean scala.collection.immutable.EmptyMap.equals(java.lang.Object)
...</pre>
<p>The output isn&#8217;t very Scala-ish, but I could format it if I weren&#8217;t so lazy.</p>
<pre>scala&gt; help(scala.runtime.RichString)
public int scala.runtime.RichString$.$tag() throws java.rmi.RemoteException
public final boolean scala.runtime.RichString$.scala$runtime$RichString$$parseBoolean(java.lang.String)
public final char scala.runtime.RichString$.scala$runtime$RichString$$LF()
public final char scala.runtime.RichString$.scala$runtime$RichString$$CR()
public final char scala.runtime.RichString$.scala$runtime$RichString$$FF()
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public boolean java.lang.Object.equals(java.lang.Object)
public java.lang.String java.lang.Object.toString()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()</pre>
<p>These functions aren&#8217;t in any way brilliant, or even clever, but they are short and ridiculously trivial to write.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fstacyprowell.com%2Fblog%2F2009%2F11%2F12%2Fsilly-scala-tricks%2F&amp;linkname=Silly%20Scala%20Tricks"><img src="http://stacyprowell.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://stacyprowell.com/blog/2009/11/12/silly-scala-tricks/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>And Another Thing That Bugs Me About Java&#8230;</title>
		<link>http://stacyprowell.com/blog/2009/09/30/and-another-thing-that-bugs-me-about-java/</link>
		<comments>http://stacyprowell.com/blog/2009/09/30/and-another-thing-that-bugs-me-about-java/#comments</comments>
		<pubDate>Wed, 30 Sep 2009 03:05:15 +0000</pubDate>
		<dc:creator>stacy</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Nuisances]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[const]]></category>
		<category><![CDATA[immutable]]></category>
		<category><![CDATA[linkedin]]></category>
		<category><![CDATA[reference]]></category>

		<guid isPermaLink="false">http://stacyprowell.com/blog/?p=415</guid>
		<description><![CDATA[Just a short note on an item that bugs me about Java.  In C++, I tend to use exactly three kinds of method parameters.

A const reference.  I don&#8217;t want to copy it, but I promise not to modify it, either.
A reference.  I might modify it.
A copy.  I might modify my local copy, but not the [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-thumbnail wp-image-116" title="java_logo_2" src="http://stacyprowell.com/blog/wp-content/uploads/2008/07/java_logo_2-150x150.png" alt="java_logo_2" width="120" height="120" />Just a short note on an item that bugs me about Java.  In C++, I tend to use exactly three kinds of method parameters.</p>
<ul>
<li>A const reference.  I don&#8217;t want to copy it, but I promise not to modify it, either.</li>
<li>A reference.  I might modify it.</li>
<li>A copy.  I might modify my local copy, but not the original.  I&#8217;m getting a copy, after all.</li>
</ul>
<p>Easy peasy in C++.  In Java?  Uh, I pass all objects by reference.<span id="more-415"></span> The interface says nothing about modification.  Pass me a Map and maybe I&#8217;ll modify it, maybe not.  You don&#8217;t know, and you can&#8217;t enforce it.  Unless you pass me a Collections.unmodifiableMap().  Then my code might break!  There might be some odd little case left over where I do modify it, in spite of documentation comments to the contrary.  C++?  I declare it to be a const reference, and now the compiler will prevent me from modifying it.  I like that quite a bit.</p>
<p>I also like const methods, and you really can&#8217;t have const without const methods.  The Java way it to throw exceptions.  I&#8217;d rather have the compiler tell me something at compile-time than have the runtime system fail at runtime.  But I&#8217;m weird, I suppose.</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fstacyprowell.com%2Fblog%2F2009%2F09%2F30%2Fand-another-thing-that-bugs-me-about-java%2F&amp;linkname=And%20Another%20Thing%20That%20Bugs%20Me%20About%20Java%26%238230%3B"><img src="http://stacyprowell.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://stacyprowell.com/blog/2009/09/30/and-another-thing-that-bugs-me-about-java/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Good Idea / Bad Idea</title>
		<link>http://stacyprowell.com/blog/2009/08/21/good-idea-bad-idea/</link>
		<comments>http://stacyprowell.com/blog/2009/08/21/good-idea-bad-idea/#comments</comments>
		<pubDate>Fri, 21 Aug 2009 17:52:04 +0000</pubDate>
		<dc:creator>stacy</dc:creator>
				<category><![CDATA[Nuisances]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Computers]]></category>
		<category><![CDATA[language]]></category>
		<category><![CDATA[linkedin]]></category>

		<guid isPermaLink="false">http://stacyprowell.com/blog/?p=350</guid>
		<description><![CDATA[I spend my time (recently) writing a mishmash of Python, C++, and Java.  It&#8217;s interesting to switch back and forth.
What&#8217;s a good idea and what&#8217;s a bad (or dangerous) idea in computer language design?  We&#8217;ve got a lot of candidates, and a lot of opinions.
I&#8217;ll list a few here, along with a few [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_235" class="wp-caption alignright" style="width: 160px"><img class="size-full wp-image-235" title="programming" src="http://stacyprowell.com/blog/wp-content/uploads/2009/05/1ebeb1d2f212046a4e47fcd414dbad9b1-150x150.jpg" alt="Programming" width="150" height="150" /><p class="wp-caption-text">Programming</p></div>
<p>I spend my time (recently) writing a mishmash of Python, C++, and Java.  It&#8217;s interesting to switch back and forth.</p>
<p>What&#8217;s a good idea and what&#8217;s a bad (or dangerous) idea in computer language design?  We&#8217;ve got a lot of candidates, and a lot of opinions.</p>
<p>I&#8217;ll list a few here, along with a few places where they show up.<span id="more-350"></span> I&#8217;m not saying C macros are the same as, or even similar to, Lisp macros.  Just trying to clarify the spectrum.</p>
<p>I&#8217;ve heard someone, at some point, say each one of the items below is a good idea / bad idea.  Dangerous in the hands of a novice?  Yes, but then so is any computer with a network connection.</p>
<ul>
<li>Preprocessors (C, C++)</li>
<li>Macros (C, Lisp)</li>
<li>Multiple Inheritance (C++, Smalltalk)</li>
<li>Operator Overloading (C++, Python)</li>
<li>Closures (Lisp, Haskell)</li>
<li>Generics (Java, Ada)</li>
<li>Template Metaprogramming (C++)</li>
<li>Casts (C, C++)</li>
<li>Strong or Weak Typing (Scala, Lisp, Python, ML)</li>
<li>Fixed-Point Math (C# and COBOL)</li>
<li>Fixed Integer Types vs. &#8220;Numbers&#8221; (C, Lisp, Python)</li>
<li>Garbage Collection (Java, Lisp, ML)</li>
<li>Manual Allocation / Deallocation (C, C++)</li>
<li>Everything is an Object / Some Things are Primitives (Smalltalk, Java)</li>
<li>Auto-(Un)Boxing (Java, C#)</li>
<li>Indentation is Significant (Python)</li>
<li>First-Order Functions (ML, Lisp)</li>
<li>Lambdas (ML, Lisp, Python)</li>
<li>Type Erasure (Java)</li>
</ul>
<p>Did I leave out your favorite / most reviled language feature?  Complain below.  I included type erasure at the end of the list.  Does <em>anyone</em> think this was a good idea for Java???</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fstacyprowell.com%2Fblog%2F2009%2F08%2F21%2Fgood-idea-bad-idea%2F&amp;linkname=Good%20Idea%20%2F%20Bad%20Idea"><img src="http://stacyprowell.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://stacyprowell.com/blog/2009/08/21/good-idea-bad-idea/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Car Talk and the Longest Word</title>
		<link>http://stacyprowell.com/blog/2009/06/14/car-talk-and-the-longest-word/</link>
		<comments>http://stacyprowell.com/blog/2009/06/14/car-talk-and-the-longest-word/#comments</comments>
		<pubDate>Sun, 14 Jun 2009 02:50:47 +0000</pubDate>
		<dc:creator>stacy</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[linkedin]]></category>
		<category><![CDATA[puzzler]]></category>

		<guid isPermaLink="false">http://stacyprowell.com/blog/?p=284</guid>
		<description><![CDATA[I recently heard about a Car Talk puzzler.  I don&#8217;t listen to Car Talk as much as I used to.  Anyway, you can read about the puzzler and the fellow who solved it here.  This is an excerpt.
During Christmas week on the popular National Public Radio show Car Talk, the weekly puzzler required listeners to [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_235" class="wp-caption alignright" style="width: 160px"><img class="size-full wp-image-235" title="programming" src="http://stacyprowell.com/blog/wp-content/uploads/2009/05/1ebeb1d2f212046a4e47fcd414dbad9b1-150x150.jpg" alt="Programming" width="150" height="150" /><p class="wp-caption-text">Programming</p></div>
<p>I recently heard about a <a href="http://www.cartalk.com/" target="_blank">Car Talk</a> puzzler.  I don&#8217;t listen to Car Talk as much as I used to.  Anyway, you can read about the puzzler and the fellow who solved it <a href="http://www.hmc.edu/newsandevents/thomasbarr.html" target="_blank">here</a>.  This is an excerpt.</p>
<blockquote><p>During Christmas week on the popular National Public Radio show Car Talk, the weekly puzzler required listeners to find the longest English word that remains a valid English word as you remove its letters one at a time, but without rearranging any of the letters. For example: sprite, spit, pit, it, I. There are many such words, but, as Barr discovered, only one with 11 letters.</p></blockquote>
<p>So, only one word with eleven letters: <em>complecting</em>.  Maybe.  I&#8217;m not convinced, but finding out is easy.<br />
<span id="more-284"></span></p>
<h2>Recursion</h2>
<p>Okay, so how would you know?  Well, suppose you had a list of valid words.  The statement of the problem suggests a simple recursive algorithm to find a solution.</p>
<ul>
<li>Put the words in a heap, ordered longest to shortest.</li>
<li>Iterate until the heap is empty.
<ul>
<li>Take the next word $w$ from the heap, and perform $\mbox{search}(w)$</li>
</ul>
</li>
</ul>
<p>The procedure $\mbox{search}(w)$ works as follows.  It returns true if it finds a solution.</p>
<ul>
<li>If $w$ is the empty string, then return true.</li>
<li>For each letter $l$ of $w$, do the following.
<ul>
<li>Drop $l$ from $w$, generating the candidate word $v$.</li>
<li>If $v$ is in the dictionary, then execute $r=\mbox{search}(v)$.
<ul>
<li>If $r$ is true, then write out $w$ and return true.</li>
</ul>
</li>
</ul>
</li>
<li>The word $w$ is a dead end; drop it from the dictionary and return false.</li>
</ul>
<p>Dropping the words from the dictionary, or otherwise marking them as dead ends in some other way is necessary to avoid re-searching them later.  The time complexity is roughly $O(n)$, where $n$ is the size of the dictionary to search.  If the average length of a word is $k$, then we can be more specific, and say the complexity is $O(kn)$, but $k$ is very small with respect to $n$, and does not vary much with the data size, so it can be safely ignored.</p>
<h2>Iteration</h2>
<p>The problem was explained to me in the reverse fashion.  Given a letter, generate words by adding a single letter at a time.  Every word must be in the dictionary.  Find the longest word you can generate from a single letter.  This suggests a different algorithm.</p>
<ul>
<li>Put the words in a heap, ordered shortest to longest.</li>
<li>Mark the empty string as reachable and set $long$ to the empty string.</li>
<li>Iterate through the heap, considering each word $w$.
<ul>
<li>For each position $i$ of $w$, do the following.
<ul>
<li>Drop the $i$th letter from $w$, generating the candidate word $v$.
<ul>
<li>If $v$ is marked as reachable, then mark $w$ as reachable by omitting $i$, and set $long=w$.</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li>While $long$ is not the empty string, do the following.
<ul>
<li>Write $long$.</li>
<li>Omit the character $i$ by which $long$ was reached, and set $long$ equal to the new word.</li>
</ul>
</li>
</ul>
<p>We can improve this by checking against the length of the longest word reached.  If we ever have $|w|&gt;|longest|+1$, then we can stop the loop immediately, since we cannot reach any further words.  We can&#8217;t do that with the prior algorithm.</p>
<h2>So&#8230; What&#8217;s the Longest Word?</h2>
<p>The solution given was <em>complecting</em>, at 11 letters.  When I download the <a href="http://aspell.net/" target="_blank">aspell</a> dictionaries, and run the algorithm (the iterative one), I find the following derivation.</p>
<p>-&gt; a<br />
-&gt; ah<br />
-&gt; ach<br />
-&gt; bach<br />
-&gt; banch<br />
-&gt; banchi<br />
-&gt; branchi<br />
-&gt; branchia<br />
-&gt; branchiae<br />
-&gt; branchiate<br />
-&gt; abranchiate<br />
-&gt; abranchiates</p>
<p>Ooh.  12 letters.  But, it&#8217;s a plural.  Does that count?  Well, complecting is a participle, so it seems it should.  Time to send a note to Tom and Ray?</p>
<h2>So&#8230; Which Algorithm?</h2>
<p>Well, I coded up the iterative one in Java, since originally I was asked how I would code it in Java.  Again, the question suggesting the solution.  I suspect there are a lot of long words that are not reachable, so it seemed better to use the trick to terminate the search when the current word is longer than the longest found (so far) plus one.  Plus, it isn&#8217;t recursive, and I don&#8217;t have to modify the data structure by deleting an item from the heap.</p>
<h2>The Java</h2>
<p>So&#8230; here&#8217;s the Java source.  Enjoy!</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * Given some iterable object that provides strings, find the longest
 * string in the collection that can be reached from the empty string
 * by adding one character at a time such that every intermediate step
 * is also in the collection.
 *
&nbsp;
 * For example, if the collection is {@code {@literal {}a,
 * at, cat, chat, chart, cart, car{@literal }}},
 * then the longst word is {@code chart}, and it's derivation is:
 * {@code a =&amp;gt; at =&amp;gt; cat =&amp;gt; cart =&amp;gt; chart}.  If there are multiple
 * longest words, then only one is detected.
 *
&nbsp;
 * Note that if single letters are not in the collection, then no words
 * can be derived, and only the empty derivation is returned.
 *
 * @param strings    An iterable providing the strings.
 * @return    The derivation of the longest, from the shortest word to the
 *             longest.  If there is no longest word, then the empty
 *             derivation is returned.
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">List</span> search<span style="color: #009900;">&#40;</span>Iterable strings<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>strings <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">NullPointerException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;The string iterator is null.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Read each string from the iterable.  The strings assumed to be</span>
    <span style="color: #666666; font-style: italic;">// single words, and the words are not assumed to occur in any</span>
    <span style="color: #666666; font-style: italic;">// particular order.  We put the words we read into a heap, ordered</span>
    <span style="color: #666666; font-style: italic;">// by length.  Our &quot;heap&quot; is a sorted map.</span>
    <span style="color: #666666; font-style: italic;">//</span>
    <span style="color: #666666; font-style: italic;">// Every entry in the map has an associated integer value, which</span>
    <span style="color: #666666; font-style: italic;">// tells us the position of the last inserted character.  This can</span>
    <span style="color: #666666; font-style: italic;">// be used to &quot;unwind&quot; the derivation of the word.  If there is not</span>
    <span style="color: #666666; font-style: italic;">// (yet) any way to reach the word, then the word is mapped to -1.</span>
    <span style="color: #003399;">TreeMap</span> heap <span style="color: #339933;">=</span>
        <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">TreeMap</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">Comparator</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> compare<span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> first, <span style="color: #003399;">String</span> second<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #666666; font-style: italic;">// Okay, we sort first by length, and then alphabetically.</span>
                <span style="color: #666666; font-style: italic;">// This is necessary because of the way TreeMap tests</span>
                <span style="color: #666666; font-style: italic;">// equality; it uses the comparator.  Thus we must only</span>
                <span style="color: #666666; font-style: italic;">// return zero if the two are actually equal.  So, we</span>
                <span style="color: #666666; font-style: italic;">// first order by length, and then for items of the same</span>
                <span style="color: #666666; font-style: italic;">// length, we order using the natural comparator for</span>
                <span style="color: #666666; font-style: italic;">// strings.</span>
                <span style="color: #000066; font-weight: bold;">int</span> order <span style="color: #339933;">=</span> first.<span style="color: #006633;">length</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">-</span> second.<span style="color: #006633;">length</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>order <span style="color: #339933;">==</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                    order <span style="color: #339933;">=</span> first.<span style="color: #006633;">compareToIgnoreCase</span><span style="color: #009900;">&#40;</span>second<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
                <span style="color: #009900;">&#125;</span>
                <span style="color: #000000; font-weight: bold;">return</span> order<span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> str <span style="color: #339933;">:</span> strings<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        heap.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>str,<span style="color: #339933;">-</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// Add all strings to the heap.</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Prime the pump by adding the empty string as &quot;reachable.&quot;</span>
    <span style="color: #003399;">String</span> longest <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span>
    <span style="color: #000066; font-weight: bold;">int</span> length <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span>
    heap.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;&quot;</span>, <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// At this point the heap is constructed.  We now iterate over the</span>
    <span style="color: #666666; font-style: italic;">// heap looking for connected words.  If we find one, we mark it.</span>
    <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #003399;">String</span> str <span style="color: #339933;">:</span> heap.<span style="color: #006633;">keySet</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// Watch for a case where we skip a length.  If we do, we're done.</span>
        <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>str.<span style="color: #006633;">length</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> length<span style="color: #339933;">+</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        length <span style="color: #339933;">=</span> str.<span style="color: #006633;">length</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #666666; font-style: italic;">// Now we have a string, we need to find out if the string is</span>
        <span style="color: #666666; font-style: italic;">// reachable from a previously-reached string.  We drop each</span>
        <span style="color: #666666; font-style: italic;">// character, and then check if the resulting string is</span>
        <span style="color: #666666; font-style: italic;">// present in the heap and is marked.</span>
        <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">int</span> index <span style="color: #339933;">=</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span> index <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> str.<span style="color: #006633;">length</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> index<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #666666; font-style: italic;">// Omit the character at position index.</span>
            <span style="color: #003399;">String</span> test <span style="color: #339933;">=</span> str.<span style="color: #006633;">substring</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>,index<span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> str.<span style="color: #006633;">substring</span><span style="color: #009900;">&#40;</span>index<span style="color: #339933;">+</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #666666; font-style: italic;">// See if the resulting test string is in the heap.</span>
            <span style="color: #003399;">Integer</span> pos <span style="color: #339933;">=</span> heap.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>test<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
            <span style="color: #666666; font-style: italic;">// Now there are three cases:</span>
            <span style="color: #666666; font-style: italic;">// (1) The test string is not in the heap.</span>
            <span style="color: #666666; font-style: italic;">// (2) The test string is in the heap, but not reachable.</span>
            <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>pos <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span> <span style="color: #339933;">||</span> pos <span style="color: #339933;">&amp;</span>lt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">continue</span><span style="color: #339933;">;</span>
            <span style="color: #009900;">&#125;</span>
            <span style="color: #666666; font-style: italic;">// (3) The test string is in the heap, and is reachable.</span>
            <span style="color: #666666; font-style: italic;">// In this last case we know we can reach the current string</span>
            <span style="color: #666666; font-style: italic;">// from the test string by adding the character at position</span>
            <span style="color: #666666; font-style: italic;">// index, so put this in the heap.</span>
            heap.<span style="color: #006633;">put</span><span style="color: #009900;">&#40;</span>str, index<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
            <span style="color: #666666; font-style: italic;">// Note that whenever this happens, we might have just found</span>
            <span style="color: #666666; font-style: italic;">// (one of) the longest words, so save it.</span>
            longest <span style="color: #339933;">=</span> str<span style="color: #339933;">;</span>
            <span style="color: #666666; font-style: italic;">// We don't need to test any other positions.</span>
            <span style="color: #000000; font-weight: bold;">break</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// Construct new words by omitting each character.</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// Search the heap for words.</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Now we have (hopefully) found a long word.  We need to generate</span>
    <span style="color: #666666; font-style: italic;">// the derivation and return it.</span>
    <span style="color: #003399;">List</span> derivation <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">LinkedList</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span>longest.<span style="color: #006633;">length</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #666666; font-style: italic;">// Get the insertion position from the heap.</span>
        <span style="color: #000066; font-weight: bold;">int</span> pos <span style="color: #339933;">=</span> heap.<span style="color: #006633;">get</span><span style="color: #009900;">&#40;</span>longest<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #666666; font-style: italic;">// Add the word to the derivation.</span>
        derivation.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>, longest<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #666666; font-style: italic;">// Generate the prior string in the derivation.</span>
        longest <span style="color: #339933;">=</span> longest.<span style="color: #006633;">substring</span><span style="color: #009900;">&#40;</span><span style="color: #cc66cc;">0</span>, pos<span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> longest.<span style="color: #006633;">substring</span><span style="color: #009900;">&#40;</span>pos<span style="color: #339933;">+</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">// Build the derivation.</span>
&nbsp;
    <span style="color: #666666; font-style: italic;">// Done!  Return the derivation.</span>
    <span style="color: #000000; font-weight: bold;">return</span> derivation<span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>The code isn&#8217;t optimal, but it is commented.  I assume you are all capable of putting this in a class and feeding it a dictionary.  Have fun!</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fstacyprowell.com%2Fblog%2F2009%2F06%2F14%2Fcar-talk-and-the-longest-word%2F&amp;linkname=Car%20Talk%20and%20the%20Longest%20Word"><img src="http://stacyprowell.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://stacyprowell.com/blog/2009/06/14/car-talk-and-the-longest-word/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Handling multipart/form-data in Python</title>
		<link>http://stacyprowell.com/blog/2009/05/29/handling-multipartform-data-in-python/</link>
		<comments>http://stacyprowell.com/blog/2009/05/29/handling-multipartform-data-in-python/#comments</comments>
		<pubDate>Fri, 29 May 2009 14:43:35 +0000</pubDate>
		<dc:creator>stacy</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[linkedin]]></category>
		<category><![CDATA[multipart]]></category>
		<category><![CDATA[multipart/form-data]]></category>

		<guid isPermaLink="false">http://stacyprowell.com/blog/?p=225</guid>
		<description><![CDATA[I need to generate multipart/form-data (see here) messages from Python.  Never mind why.  I dug around in the documentation for httplib, urllib, and urllib2, but it seems this is not currently supported (it&#8217;s Issue 3244).  I didn&#8217;t like the code I found on the web to do it, because I needed to [...]]]></description>
			<content:encoded><![CDATA[<div id="attachment_235" class="wp-caption alignright" style="width: 160px"><img class="size-full wp-image-235" title="programming" src="http://stacyprowell.com/blog/wp-content/uploads/2009/05/1ebeb1d2f212046a4e47fcd414dbad9b1-150x150.jpg" alt="Programming" width="150" height="150" /><p class="wp-caption-text">Programming</p></div>
<p>I need to generate <tt>multipart/form-data</tt> (see <a href="http://www.w3.org/TR/html401/interact/forms.html">here</a>) messages from Python.  Never mind why.  I dug around in the documentation for httplib, urllib, and urllib2, but it seems this is not currently supported (it&#8217;s <a href="http://bugs.python.org/issue3244">Issue 3244</a>).  I didn&#8217;t like the code I found on the web to do it, because I needed to set additional headers on each piece.  So&#8230; I wrote something.  Here it is.  If it&#8217;s useful to you, great!  If you find bugs in it, please let me know.  I think this is pretty easy to use.<br />
<span id="more-225"></span><br />
Make an instance of Multipart, and then add parts using the field and file methods.</p>

<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">&gt;&gt;&gt; from multipart import Multipart
&gt;&gt;&gt; m = Multipart()
&gt;&gt;&gt; m.field('search','searchish term')
&gt;&gt;&gt; m.file('greet','greet.txt','Hello multipart world!',{'Content-Type':'text/text'})
&gt;&gt;&gt; ct,body = m.get()
&gt;&gt;&gt; print ct
multipart/form-data; boundary=----------AaB03x
&gt;&gt;&gt; print body
------------AaB03x
Content-Type: application/octet-stream
Content-Disposition: form-data; name=&quot;search&quot;
&nbsp;
searchish term
------------AaB03x
Content-Type: text/text
Content-Disposition: form-data; name=&quot;greet&quot;; filename=&quot;greet.txt&quot;
&nbsp;
Hello multipart world!
------------AaB03x--</pre></div></div>

<p>If no content type is specified for a value, then the default of application/octet-stream is chosen.  If none is specified for a file, then the mime libraries are consulted to guess one based on the filename, and again the default is application/octet-stream if none can be guessed.</p>
<p>If you want to specify the content type, make sure to use the string &#8216;Content-Type&#8217; (note the caps) or it will be ignored.  I&#8217;ve seen the capitalization all over the map, but needed to choose one to use in the case-sensitive dict.  If you don&#8217;t like my choice&#8230; change the code.  See the constants at the start of the Client class.</p>
<p>Here&#8217;s how you might continue the above example to send this out in an HTTP request.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;">request = <span style="color: #dc143c;">urllib2</span>.<span style="color: black;">Request</span><span style="color: black;">&#40;</span>url=<span style="color: #483d8b;">'http://my.fake.server'</span>,
    headers=<span style="color: black;">&#123;</span><span style="color: #483d8b;">'Content-Type'</span>:ct<span style="color: black;">&#125;</span>,
    data=body<span style="color: black;">&#41;</span>
reply = <span style="color: #dc143c;">urllib2</span>.<span style="color: black;">urlopen</span><span style="color: black;">&#40;</span>request<span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">print</span> reply.<span style="color: black;">read</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>Finally, here&#8217;s the code.  Enjoy!  This comes, of course, with <em>no warranty</em>, use at your own risk, etc.</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">#!/usr/bin/python</span>
<span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
Classes for using multipart form data from Python, which does not (at the
time of writing) support this directly.
&nbsp;
To use this, make an instance of Multipart and add parts to it via the factory
methods field and file.  When you are done, get the content via the get method.
&nbsp;
@author: Stacy Prowell (http://stacyprowell.com)
'</span><span style="color: #483d8b;">''</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">mimetypes</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> Part<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
    Class holding a single part of the form.  You should never need to use
    this class directly; instead, use the factory methods in Multipart:
    field and file.
    '</span><span style="color: #483d8b;">''</span>
&nbsp;
    <span style="color: #808080; font-style: italic;"># The boundary to use.  This is shamelessly taken from the standard.</span>
    BOUNDARY = <span style="color: #483d8b;">'----------AaB03x'</span>
    CRLF = <span style="color: #483d8b;">'<span style="color: #000099; font-weight: bold;">\r</span><span style="color: #000099; font-weight: bold;">\n</span>'</span>
    <span style="color: #808080; font-style: italic;"># Common headers.</span>
    CONTENT_TYPE = <span style="color: #483d8b;">'Content-Type'</span>
    CONTENT_DISPOSITION = <span style="color: #483d8b;">'Content-Disposition'</span>
    <span style="color: #808080; font-style: italic;"># The default content type for parts.</span>
    DEFAULT_CONTENT_TYPE = <span style="color: #483d8b;">'application/octet-stream'</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, name, filename, body, headers<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
        Make a new part.  The part will have the given headers added initially.
&nbsp;
        @param name: The part name.
        @type name: str
        @param filename: If this is a file, the name of the file.  Otherwise
                        None.
        @type filename: str
        @param body: The body of the part.
        @type body: str
        @param headers: Additional headers, or overrides, for this part.
                        You can override Content-Type here.
        @type headers: dict
        '</span><span style="color: #483d8b;">''</span>
        <span style="color: #008000;">self</span>._headers = headers.<span style="color: #dc143c;">copy</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">self</span>._name = name
        <span style="color: #008000;">self</span>._filename = filename
        <span style="color: #008000;">self</span>._body = body
        <span style="color: #808080; font-style: italic;"># We respect any content type passed in, but otherwise set it here.</span>
        <span style="color: #808080; font-style: italic;"># We set the content disposition now, overwriting any prior value.</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #008000;">self</span>._filename == <span style="color: #008000;">None</span>:
            <span style="color: #008000;">self</span>._headers<span style="color: black;">&#91;</span>Part.<span style="color: black;">CONTENT_DISPOSITION</span><span style="color: black;">&#93;</span> = \
                <span style="color: black;">&#40;</span><span style="color: #483d8b;">'form-data; name=&quot;%s&quot;'</span> <span style="color: #66cc66;">%</span> <span style="color: #008000;">self</span>._name<span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>._headers.<span style="color: black;">setdefault</span><span style="color: black;">&#40;</span>Part.<span style="color: black;">CONTENT_TYPE</span>,
                                     Part.<span style="color: black;">DEFAULT_CONTENT_TYPE</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">else</span>:
            <span style="color: #008000;">self</span>._headers<span style="color: black;">&#91;</span>Part.<span style="color: black;">CONTENT_DISPOSITION</span><span style="color: black;">&#93;</span> = \
                <span style="color: black;">&#40;</span><span style="color: #483d8b;">'form-data; name=&quot;%s&quot;; filename=&quot;%s&quot;'</span> <span style="color: #66cc66;">%</span>
                 <span style="color: black;">&#40;</span><span style="color: #008000;">self</span>._name, <span style="color: #008000;">self</span>._filename<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>._headers.<span style="color: black;">setdefault</span><span style="color: black;">&#40;</span>Part.<span style="color: black;">CONTENT_TYPE</span>,
                                     <span style="color: #dc143c;">mimetypes</span>.<span style="color: black;">guess_type</span><span style="color: black;">&#40;</span>filename<span style="color: black;">&#41;</span><span style="color: black;">&#91;</span><span style="color: #ff4500;">0</span><span style="color: black;">&#93;</span>
                                     <span style="color: #ff7700;font-weight:bold;">or</span> Part.<span style="color: black;">DEFAULT_CONTENT_TYPE</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> get<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
        Convert the part into a list of lines for output.  This includes
        the boundary lines, part header lines, and the part itself.  A
        blank line is included between the header and the body.
&nbsp;
        @return: Lines of this part.
        @rtype: list
        '</span><span style="color: #483d8b;">''</span>
        lines = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
        lines.<span style="color: black;">append</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'--'</span> + Part.<span style="color: black;">BOUNDARY</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">for</span> <span style="color: black;">&#40;</span>key, val<span style="color: black;">&#41;</span> <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">self</span>._headers.<span style="color: black;">items</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>:
            lines.<span style="color: black;">append</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'%s: %s'</span> <span style="color: #66cc66;">%</span> <span style="color: black;">&#40;</span>key, val<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        lines.<span style="color: black;">append</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">''</span><span style="color: black;">&#41;</span>
        lines.<span style="color: black;">append</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>._body<span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> lines
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> Multipart<span style="color: black;">&#40;</span><span style="color: #008000;">object</span><span style="color: black;">&#41;</span>:
    <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
    Encapsulate multipart form data.  To use this, make an instance and then
    add parts to it via the two methods (field and file).  When done, you can
    get the result via the get method.
&nbsp;
    See http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2 for
    details on multipart/form-data.
&nbsp;
    Watch http://bugs.python.org/issue3244 to see if this is fixed in the
    Python libraries.
&nbsp;
    @return: content type, body
    @rtype: tuple
    '</span><span style="color: #483d8b;">''</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #008000;">self</span>.<span style="color: black;">parts</span> = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> field<span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, name, value, headers=<span style="color: black;">&#123;</span><span style="color: black;">&#125;</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
        Create and append a field part.  This kind of part has a field name
        and value.
&nbsp;
        @param name: The field name.
        @type name: str
        @param value: The field value.
        @type value: str
        @param headers: Headers to set in addition to disposition.
        @type headers: dict
        '</span><span style="color: #483d8b;">''</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">parts</span>.<span style="color: black;">append</span><span style="color: black;">&#40;</span>Part<span style="color: black;">&#40;</span>name, <span style="color: #008000;">None</span>, value, headers<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #008000;">file</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, name, filename, value, headers=<span style="color: black;">&#123;</span><span style="color: black;">&#125;</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
        Create and append a file part.  THis kind of part has a field name,
        a filename, and a value.
&nbsp;
        @param name: The field name.
        @type name: str
        @param value: The field value.
        @type value: str
        @param headers: Headers to set in addition to disposition.
        @type headers: dict
        '</span><span style="color: #483d8b;">''</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">parts</span>.<span style="color: black;">append</span><span style="color: black;">&#40;</span>Part<span style="color: black;">&#40;</span>name, filename, value, headers<span style="color: black;">&#41;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> get<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
        Get the multipart form data.  This returns the content type, which
        specifies the boundary marker, and also returns the body containing
        all parts and bondary markers.
&nbsp;
        @return: content type, body
        @rtype: tuple
        '</span><span style="color: #483d8b;">''</span>
        <span style="color: #008000;">all</span> = <span style="color: black;">&#91;</span><span style="color: black;">&#93;</span>
        <span style="color: #ff7700;font-weight:bold;">for</span> part <span style="color: #ff7700;font-weight:bold;">in</span> <span style="color: #008000;">self</span>.<span style="color: black;">parts</span>:
            <span style="color: #008000;">all</span> += part.<span style="color: black;">get</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">all</span>.<span style="color: black;">append</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">'--'</span> + Part.<span style="color: black;">BOUNDARY</span> + <span style="color: #483d8b;">'--'</span><span style="color: black;">&#41;</span>
        <span style="color: #008000;">all</span>.<span style="color: black;">append</span><span style="color: black;">&#40;</span><span style="color: #483d8b;">''</span><span style="color: black;">&#41;</span>
        <span style="color: #808080; font-style: italic;"># We have to return the content type, since it specifies the boundary.</span>
        content_type = <span style="color: #483d8b;">'multipart/form-data; boundary=%s'</span> <span style="color: #66cc66;">%</span> Part.<span style="color: black;">BOUNDARY</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> content_type, Part.<span style="color: black;">CRLF</span>.<span style="color: black;">join</span><span style="color: black;">&#40;</span><span style="color: #008000;">all</span><span style="color: black;">&#41;</span></pre></div></div>

<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fstacyprowell.com%2Fblog%2F2009%2F05%2F29%2Fhandling-multipartform-data-in-python%2F&amp;linkname=Handling%20multipart%2Fform-data%20in%20Python"><img src="http://stacyprowell.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://stacyprowell.com/blog/2009/05/29/handling-multipartform-data-in-python/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Cleanroom and Unit Testing</title>
		<link>http://stacyprowell.com/blog/2009/05/25/cleanroom-and-unit-testing/</link>
		<comments>http://stacyprowell.com/blog/2009/05/25/cleanroom-and-unit-testing/#comments</comments>
		<pubDate>Mon, 25 May 2009 01:00:45 +0000</pubDate>
		<dc:creator>stacy</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[cleanroom software engineering]]></category>
		<category><![CDATA[inspection]]></category>
		<category><![CDATA[linkedin]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[unit test]]></category>
		<category><![CDATA[verification]]></category>

		<guid isPermaLink="false">http://stacyprowell.com/blog/?p=215</guid>
		<description><![CDATA[In &#8220;Embracing Change with Extreme Programming&#8221; (IEEE Computer, 1999), Kent Beck writes:
Some methodologies, like Cleanroom, prohibit programmers testing or in some cases even compiling their own programs.
As evidence of this he cites the text Cleanroom Software Engineering: Technology and Process, by, among others, yours truly.  I for one have never said that people should not [...]]]></description>
			<content:encoded><![CDATA[<p>In &#8220;Embracing Change with Extreme Programming&#8221; (<em>IEEE Computer</em>, 1999), Kent Beck writes:</p>
<blockquote><p>Some methodologies, like Cleanroom, prohibit programmers testing or in some cases even compiling their own programs.</p></blockquote>
<p>As evidence of this he cites the text <em>Cleanroom Software Engineering: Technology and Process</em>, by, among others, yours truly.  I for one have never said that people should not run unit tests, nor does the above text say that.  I emailed Mr. Beck about it, and he confirmed that he did <em>not</em> get this from the cited text.  Whew!</p>
<p>Just to be clear, here is my position.  <strong>I would never tell anyone <em>not</em> to run a test they felt was necessary.</strong> I may personally believe there are efficient and inefficient ways to test, but I&#8217;m not an expert in every domain.  The people who create a product are responsible for the consequences of release of that product, and should act accordingly.<span id="more-215"></span></p>
<h1>The Purpose of Testing</h1>
<p>The following is my philosophical position on software testing.</p>
<blockquote><p>The purpose of software testing is to gain evidence that software release will not be harmful.</p></blockquote>
<p>In particular, I believe it is impractical and inefficient to take the position that the purpose of testing is to find bugs.  It leads to poor practice, and information that isn&#8217;t really &#8220;actionable.&#8221;</p>
<p>Some may insist that the purpose of testing is specifically to find bugs, but they&#8217;re misguided.  If you want to find bugs, testing is a poor way to do it.  Use inspections or verification.  But more on that later.</p>
<h1>Cleanroom</h1>
<p>I&#8217;m a late-comer to Cleanroom.  Since Harlan Mills introduced the notion to the world in the 1980&#8217;s, it&#8217;s been an ever-evolving set of practices.  I&#8217;d say the following are the essential elements of Cleanroom software engineering.</p>
<ul>
<li>Emphasize defect prevention rather than defect correction.  I&#8217;d say this is the <em>fundmental characteristic</em> of Cleanroom.</li>
<li>Statistical certification of software quality.</li>
<li>Iterative and incremental development under statistical process control.</li>
<li>Formal or rigorous specification.</li>
<li>Stepwise refinement with verification.</li>
</ul>
<p>Okay, I cheated.  Here&#8217;s what Harlan Mills, Mike Dyer, and Rick Linger have to say on the subject in &#8220;Cleanroom Software Engineering,&#8221; <em>IEEE Software</em>, 14(2), 1987.</p>
<blockquote><p>With the Cleanroom process, you can engineer software under statistical quality control.  As with cleanroom hardware development, the process&#8217;s first priority is defect prevention rather than defect removal (of course, any defects not prevented should be removed).  This first priority is achieved by using human mathematical verification in place of program debugging to prepare software for system test.</p>
<p>Its next priority is to provide valid, statistical certification of the software&#8217;s quality through representative-user testing at the system level.  The measure of quality is the mean time to failure in appropriate units of time (real or processor time) of the desired product.  The certification takes into account the growth of reliability achieved during system testing before delivery.</p>
<p>To gain the benefits of quality control during development, Cleanroom software engineering requires a development cycle of concurrent fabrication and certification of product increments that accumulate into the system to be delivered.  This lets the fabrication process be altered on the basis of early certification results to achieve the quality desired.</p></blockquote>
<p>Unit testing is not mentioned in the article, because the emphasis is on breaking the code-compile-debug cycle.</p>
<h1>Prohibiting Unit Testing</h1>
<p>So, unit testing.  Phil Hausler, Rick Linger, and Carmen Trammell have this to say in &#8220;Adopting Cleanroom Software Engineering With a Phased Approach,&#8221; <em>IBM Systems Journal</em>, March 1994.  (Read it <a href="http://findarticles.com/p/articles/mi_m0ISJ/is_n1_v33/ai_15103441/">here</a>.)</p>
<blockquote><p>In traditional, craft-based software development errors were accepted as inevitable, and programmers were encouraged to get software into testing quickly in oder to begin debugging. Programs were subjected to unit testing and debugging by their authors, then integrated into components, subsystems, and systems for more debugging. Product use by customers resulted in still more debugging to correct errors discovered in operational use. The most virulent errors were often the result of fixes to other error, and it was not unusua for software products to reach a steady-state error population, with new errors introduced as fast as old ones were fixed. Today, however, craft-based processes that dependent on testing and debugging to improve reliability are understood to be inefficient and ineffective. Experience has shown that craft-based processes often fail to achieve the level of reliability essential to a society dependent on software for the conduct of human affairs.</p></blockquote>
<p>They cite the Adams data in support of the above.  (E. N. Adams, &#8220;Optimizing Preventive Service of Software Products,&#8221; <em>IBM Journal of Research and Development</em>, 28(1):2-14, 1984.)</p>
<p>I believe it is clear from the above what sort of practices they are targeting.  They go on to write the following.</p>
<blockquote><p>In the Cleanroom process, correctness is built into the software by development teams through a rigorous engineering process of specification, design, and verification. The more powerful process of team correctness verification replaces unit testing and debugging, and software enters system testing directly, with no execution by development teams. All errors are accounted for from first execution on, with no private unit testing necessary or permitted.</p></blockquote>
<p>So there you have it; the prohibition against unit testing.  This is done to break the cycle of code-compile-test by taking the test and possibly compile phases out of the hands of the developers.  And I agree, up to a point.  I would even go so far as to claim that Kent Beck might agree, but break the cycle in a different way.  He requires you to write the tests <em>first</em>.  Then you write the code that passes these tests.</p>
<h1>Inspection is Insufficient</h1>
<p>Software inspection is the most effective means to find and remove defects.  I can say this because the studies all support this.  Even informal code reviews are far more effective than testing, when both are done properly.</p>
<p>The fact is that inspections are not enough.  Nobody understands the semantics of modern high-level languages.  I&#8217;m serious; you do not.  You may think you do, in which case you are dangerously deluded.</p>
<p>There are three primary reasons for this.</p>
<ol>
<li>Language standards are seldom complete or consistent.  It is possible, for instance, to have legally constructed C programs whose meaning is not specified by the C standard.  Compiler writers are free to make their own decisions.</li>
<li>Compiler writers make mistakes.  Library writers make mistakes.</li>
<li>Computers are <em>weird</em>.  Can you explain the IEEE-754 standard to me, along with the details of the particular implementation you are using?  How about the fact that there is one more negative number than positive numbers in the two&#8217;s-complement world?</li>
</ol>
<p>The short of this is that you have to execute the code.  You have to run tests.  I see nothing wrong with test early, test often.  Is the library documentation insufficient?  Then you&#8217;re going to code up and run some tests, aren&#8217;t you?</p>
<p>Even if you work at the assembly level, and don&#8217;t worry with compilers and high-level languages, computers are still a bit dodgy.  Are &#8220;add eax,dword 1&#8243; and &#8220;inc eax&#8221; the same?  Many emulators assume they are, but they differ in one particular way.  Do you know what it is?  The people who write malicious code do.</p>
<h1>Verification</h1>
<p>Testing is insufficient, since you cannot prove the absence of defects, bad behavior, or malicious code by testing.  Inspection, as I just argued, is insufficient for a number of reasons.</p>
<p>The answer is verification.  Verification is challenging, mathematical, and requires a precise model of the system.  Fortunately, automated verification is on its way.  By creating a formal model of the processor, warts and all, and then by computing the functional behavior of code, one can achieve results that cannot be achieved by either testing or inspection.</p>
<p><em>Automated</em> verification is essential.  Manual verification is simply not practical, thanks to the complexity of modern processors.  I am capable of proving the correctness of an algorithm, but then it is implemented on a finite precision machine with lots of non-linear and discontinuous behavior, and all bets are off.  I would argue that humans are simply not good enough at the bookkeeping to do the job for large software systems.  Computers are.</p>
<p>Projects like CERT&#8217;s Function Extraction (FX) effort may finally deliver on the promise of software verification.  Until then, you&#8217;ll just have to run your tests.</p>
<h1>Do It Correctly</h1>
<p>Here&#8217;s my advice on unit testing.  It&#8217;s short.  Feel free to extend and revise it as necessary.</p>
<ul>
<li>Have someone <em>other</em> than the programmer write the unit test.</li>
<li>Test the <em>interface</em>.  That is, write the test as a user of the module, not the developer.  The same could be said for documentation.</li>
<li>Test the <em>GUI</em>.  It isn&#8217;t as hard as you think it is.</li>
<li>Write your tests to generate <em>random</em> values and also test <em>boundary</em> values.</li>
<li>For stateful modules, write tests that generate <em>sequences</em> of inputs.</li>
</ul>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fstacyprowell.com%2Fblog%2F2009%2F05%2F25%2Fcleanroom-and-unit-testing%2F&amp;linkname=Cleanroom%20and%20Unit%20Testing"><img src="http://stacyprowell.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://stacyprowell.com/blog/2009/05/25/cleanroom-and-unit-testing/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Java Generics&#8230;</title>
		<link>http://stacyprowell.com/blog/2009/04/14/java-generics/</link>
		<comments>http://stacyprowell.com/blog/2009/04/14/java-generics/#comments</comments>
		<pubDate>Tue, 14 Apr 2009 16:07:11 +0000</pubDate>
		<dc:creator>stacy</dc:creator>
				<category><![CDATA[Java]]></category>
		<category><![CDATA[Nuisances]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[linkedin]]></category>

		<guid isPermaLink="false">http://stacyprowell.com/blog/?p=137</guid>
		<description><![CDATA[Grrr.  I really wish Java had either:

Reified generics or
Closures

In the interim, I offer the following Java code to the world.  Does it help?  Use at your own risk.
This is a class that wraps the collections interface to provide for recovery of the type parameter.  To use it, make a new instance and pass the class [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-full wp-image-176" title="java_logo_21" src="http://stacyprowell.com/blog/wp-content/uploads/2009/04/java_logo_21.png" alt="java_logo_21" width="105" height="139" />Grrr.  I really wish Java had either:</p>
<ul>
<li>Reified generics or</li>
<li>Closures</li>
</ul>
<p>In the interim, I offer the following Java code to the world.  Does it help?  Use at your own risk.</p>
<p><span id="more-137"></span>This is a class that wraps the collections interface to provide for recovery of the type parameter.  To use it, make a new instance and pass the class object for the parameter to the constructor, along with the original collection.</p>

<div class="wp_syntax"><div class="code"><pre class="java" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">package</span> <span style="color: #006699;">gypsum.util</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.Collection</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #006699;">java.util.Iterator</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #008000; font-style: italic; font-weight: bold;">/**
 * This class packages some implementation of {@link Collection} along with
 * the class object for the type parameter of the collection.  This allows
 * getting the type of objects in the collection using the {@link #getType()}
 * method, and then using the resulting class to perform casts.  This basically
 * creates a &quot;reified&quot; generic collection (of sorts).
 *
 * @param    Class of data held in this collection.
 * @author sprowell
 * @version $Revision$ $Date$
 */</span>
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">class</span> TypedCollection <span style="color: #000000; font-weight: bold;">implements</span> <span style="color: #003399;">Collection</span> <span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000000; font-weight: bold;">Class</span> type<span style="color: #339933;">;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #003399;">Collection</span> implementation<span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * Make a new instance.
     * @param type              The class object for the type of elements.
     * @param implementation    The implementation.
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> TypedCollection<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> type, <span style="color: #003399;">Collection</span> implementation<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>type <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">NullPointerException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;The type is null.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>implementation <span style="color: #339933;">==</span> <span style="color: #000066; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">NullPointerException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;The implementation is null.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">type</span> <span style="color: #339933;">=</span> type<span style="color: #339933;">;</span>
        <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006633;">implementation</span> <span style="color: #339933;">=</span> implementation<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * Get the type held in this collection.
     * @return  The type held in this collection.
     */</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">Class</span> getType<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> type<span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * Recover the original typed collection.  In order for this to work,
     * the correct class must be supplied; otherwise you will get a
     * {@link ClassCastException}.  Use this as follows.
     *
&lt;pre&gt;     * TypedCollection&amp;lt;Foo&amp;gt; coll = oldcoll.recover(oldcoll.getType());
     *
     *
&nbsp;
     * This converts from {@code TypedCollection&amp;lt;?&amp;gt;} to
     * {@code TypedCollection&amp;amp;ltT&amp;gt;}, so you recover the generic type
     * parameter.
     *
&nbsp;
     * This may seem backward, or even a little contrived.  Blame it on
     * the Java generics system.  The reason you must pass the class
     * object &lt;em&gt;in&lt;/em&gt;, even though it is maintained here, is that
     * the compiler must know the type of the object &lt;em&gt;at the point
     * you use this method&lt;/em&gt;.  Thus you can do the following.
     *
&lt;pre&gt;     * public void print(TypedCollection&amp;lt;?&amp;gt; coll) {
     *   if (coll.getType() == String.class) {
     *     TypedCollection&amp;lt;String&amp;gt; coll = coll.recover(String.class);
     *     for (String str : coll) {
     *       System.out.println(str);
     *     }
     *   }
     * }
     * &amp;lt;/pre&amp;gt;
     *
     * @param    The type of the desired collection.
     * @param kind  The class object for type T.
     * @return  The correctly cast generic collection.
     * @throws  ClassCastException
     *          This instance is &lt;em&gt;not&lt;/em&gt; the type desired.
     */</span>
    @SuppressWarnings<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;unchecked&quot;</span><span style="color: #009900;">&#41;</span>
    <span style="color: #000000; font-weight: bold;">public</span>  TypedCollection recover<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">Class</span> kind<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>kind <span style="color: #339933;">==</span> type<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #009900;">&#40;</span>TypedCollection<span style="color: #009900;">&#41;</span> <span style="color: #000000; font-weight: bold;">this</span><span style="color: #339933;">;</span>
        <span style="color: #009900;">&#125;</span>
        <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #003399;">ClassCastException</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Incorrect cast.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * {@inheritDoc}
     * @see java.util.Collection#add(java.lang.Object)
     */</span>
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> add<span style="color: #009900;">&#40;</span>E arg<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> implementation.<span style="color: #006633;">add</span><span style="color: #009900;">&#40;</span>arg<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * {@inheritDoc}
     * @see java.util.Collection#addAll(java.util.Collection)
     */</span>
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> addAll<span style="color: #009900;">&#40;</span><span style="color: #003399;">Collection</span> arg<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> implementation.<span style="color: #006633;">addAll</span><span style="color: #009900;">&#40;</span>arg<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * {@inheritDoc}
     * @see java.util.Collection#clear()
     */</span>
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">void</span> clear<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        implementation.<span style="color: #006633;">clear</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * {@inheritDoc}
     * @see java.util.Collection#contains(java.lang.Object)
     */</span>
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> contains<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> arg<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> implementation.<span style="color: #006633;">contains</span><span style="color: #009900;">&#40;</span>arg<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * {@inheritDoc}
     * @see java.util.Collection#containsAll(java.util.Collection)
     */</span>
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> containsAll<span style="color: #009900;">&#40;</span><span style="color: #003399;">Collection</span> c<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> implementation.<span style="color: #006633;">containsAll</span><span style="color: #009900;">&#40;</span>c<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * {@inheritDoc}
     * @see java.util.Collection#isEmpty()
     */</span>
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> isEmpty<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> implementation.<span style="color: #006633;">isEmpty</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * {@inheritDoc}
     * @see java.util.Collection#iterator()
     */</span>
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Iterator</span> iterator<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> implementation.<span style="color: #006633;">iterator</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * {@inheritDoc}
     * @see java.util.Collection#remove(java.lang.Object)
     */</span>
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> remove<span style="color: #009900;">&#40;</span><span style="color: #003399;">Object</span> o<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> implementation.<span style="color: #006633;">remove</span><span style="color: #009900;">&#40;</span>o<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * {@inheritDoc}
     * @see java.util.Collection#removeAll(java.util.Collection)
     */</span>
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> removeAll<span style="color: #009900;">&#40;</span><span style="color: #003399;">Collection</span> c<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> implementation.<span style="color: #006633;">removeAll</span><span style="color: #009900;">&#40;</span>c<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * {@inheritDoc}
     * @see java.util.Collection#retainAll(java.util.Collection)
     */</span>
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">boolean</span> retainAll<span style="color: #009900;">&#40;</span><span style="color: #003399;">Collection</span> c<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> implementation.<span style="color: #006633;">retainAll</span><span style="color: #009900;">&#40;</span>c<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * {@inheritDoc}
     * @see java.util.Collection#size()
     */</span>
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000066; font-weight: bold;">int</span> size<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> implementation.<span style="color: #006633;">size</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * {@inheritDoc}
     * @see java.util.Collection#toArray()
     */</span>
    @Override
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #003399;">Object</span><span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> toArray<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> implementation.<span style="color: #006633;">toArray</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
&nbsp;
    <span style="color: #008000; font-style: italic; font-weight: bold;">/**
     * {@inheritDoc}
     * @see java.util.Collection#toArray(T[])
     */</span>
    @Override
    <span style="color: #000000; font-weight: bold;">public</span>  T<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> toArray<span style="color: #009900;">&#40;</span>T<span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span> a<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> implementation.<span style="color: #006633;">toArray</span><span style="color: #009900;">&#40;</span>a<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

</pre>
</pre>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fstacyprowell.com%2Fblog%2F2009%2F04%2F14%2Fjava-generics%2F&amp;linkname=Java%20Generics%26%238230%3B"><img src="http://stacyprowell.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://stacyprowell.com/blog/2009/04/14/java-generics/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Trapping CTRL+C in Python</title>
		<link>http://stacyprowell.com/blog/2009/03/30/trapping-ctrlc-in-python/</link>
		<comments>http://stacyprowell.com/blog/2009/03/30/trapping-ctrlc-in-python/#comments</comments>
		<pubDate>Mon, 30 Mar 2009 18:12:30 +0000</pubDate>
		<dc:creator>stacy</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[break]]></category>
		<category><![CDATA[ctrl+c]]></category>
		<category><![CDATA[interrupt]]></category>
		<category><![CDATA[linkedin]]></category>

		<guid isPermaLink="false">http://stacyprowell.com/blog/?p=123</guid>
		<description><![CDATA[I&#8217;ve been doing some nasty database work with Python and MySQL.  Specifically, I&#8217;ve got long programs that run eight to ten hours, and sometimes I need to kill them and restart them later.
So&#8230; I wanted a way to trap CTRL+C and clean up.  That is, I wanted to have transactions without actually having to use [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-thumbnail wp-image-126" title="1ebeb1d2f212046a4e47fcd414dbad9b1" src="http://stacyprowell.com/blog/wp-content/uploads/2009/03/1ebeb1d2f212046a4e47fcd414dbad9b1-150x150.jpg" alt="1ebeb1d2f212046a4e47fcd414dbad9b1" width="150" height="150" />I&#8217;ve been doing some nasty database work with Python and MySQL.  Specifically, I&#8217;ve got long programs that run eight to ten hours, and sometimes I need to kill them and restart them later.</p>
<p>So&#8230; I wanted a way to trap CTRL+C and clean up.  That is, I wanted to have transactions without actually having to use transactions.  I&#8217;m funny that way.  (In other news, I&#8217;m probably moving to PostgreSQL at some point.)</p>
<p>Anyway, here&#8217;s what I came up with.  You might find it useful, too.<span id="more-123"></span></p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">#!/usr/bin/python -i</span>
&nbsp;
<span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
Trap keyboard interrupts.  No rights reserved; use at your own risk.
&nbsp;
@author: Stacy Prowell (http://stacyprowell.com)
'</span><span style="color: #483d8b;">''</span>
<span style="color: #ff7700;font-weight:bold;">import</span> <span style="color: #dc143c;">signal</span>
&nbsp;
<span style="color: #ff7700;font-weight:bold;">class</span> BreakHandler:
    <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
    Trap CTRL-C, set a flag, and keep going.  This is very useful for
    gracefully exiting database loops while simulating transactions.
&nbsp;
    To use this, make an instance and then enable it.  You can check
    whether a break was trapped using the trapped property.
&nbsp;
    # Create and enable a break handler.
    ih = BreakHandler()
    ih.enable()
    for x in big_set:
        complex_operation_1()
        complex_operation_2()
        complex_operation_3()
        # Check whether there was a break.
        if ih.trapped:
            # Stop the loop.
            break
    ih.disable()
    # Back to usual operation...
    '</span><span style="color: #483d8b;">''</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__init__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, emphatic=<span style="color: #ff4500;">9</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
        Create a new break handler.
&nbsp;
        @param emphatic: This is the number of times that the user must
                    press break to *disable* the handler.  If you press
                    break this number of times, the handler is automagically
                    disabled, and one more break will trigger an old
                    style keyboard interrupt.  The default is nine.  This
                    is a Good Idea, since if you happen to lose your
                    connection to the handler you can *still* disable it.
        '</span><span style="color: #483d8b;">''</span>
        <span style="color: #008000;">self</span>._count = <span style="color: #ff4500;">0</span>
        <span style="color: #008000;">self</span>._enabled = <span style="color: #008000;">False</span>
        <span style="color: #008000;">self</span>._emphatic = emphatic
        <span style="color: #008000;">self</span>._oldhandler = <span style="color: #008000;">None</span>
        <span style="color: #ff7700;font-weight:bold;">return</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> _reset<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
        Reset the trapped status and count.  You should not need to use this
        directly; instead you can disable the handler and then re-enable it.
        This is better, in case someone presses CTRL-C during this operation.
        '</span><span style="color: #483d8b;">''</span>
        <span style="color: #008000;">self</span>._count = <span style="color: #ff4500;">0</span>
        <span style="color: #ff7700;font-weight:bold;">return</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> enable<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
        Enable trapping of the break.  This action also resets the
        handler count and trapped properties.
        '</span><span style="color: #483d8b;">''</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #ff7700;font-weight:bold;">not</span> <span style="color: #008000;">self</span>._enabled:
            <span style="color: #008000;">self</span>._reset<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>._enabled = <span style="color: #008000;">True</span>
            <span style="color: #008000;">self</span>._oldhandler = <span style="color: #dc143c;">signal</span>.<span style="color: #dc143c;">signal</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">signal</span>.<span style="color: black;">SIGINT</span>, <span style="color: #008000;">self</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> disable<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
        Disable trapping the break.  You can check whether a break
        was trapped using the count and trapped properties.
        '</span><span style="color: #483d8b;">''</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #008000;">self</span>._enabled:
            <span style="color: #008000;">self</span>._enabled = <span style="color: #008000;">False</span>
            <span style="color: #dc143c;">signal</span>.<span style="color: #dc143c;">signal</span><span style="color: black;">&#40;</span><span style="color: #dc143c;">signal</span>.<span style="color: black;">SIGINT</span>, <span style="color: #008000;">self</span>._oldhandler<span style="color: black;">&#41;</span>
            <span style="color: #008000;">self</span>._oldhandler = <span style="color: #008000;">None</span>
        <span style="color: #ff7700;font-weight:bold;">return</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__call__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span>, signame, sf<span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
        An break just occurred.  Save information about it and keep
        going.
        '</span><span style="color: #483d8b;">''</span>
        <span style="color: #008000;">self</span>._count += <span style="color: #ff4500;">1</span>
        <span style="color: #808080; font-style: italic;"># If we've exceeded the &quot;emphatic&quot; count disable this handler.</span>
        <span style="color: #ff7700;font-weight:bold;">if</span> <span style="color: #008000;">self</span>._count <span style="color: #66cc66;">&gt;</span>= <span style="color: #008000;">self</span>._emphatic:
            <span style="color: #008000;">self</span>.<span style="color: black;">disable</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span>
&nbsp;
    <span style="color: #ff7700;font-weight:bold;">def</span> <span style="color: #0000cd;">__del__</span><span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
        Python is reclaiming this object, so make sure we are disabled.
        '</span><span style="color: #483d8b;">''</span>
        <span style="color: #008000;">self</span>.<span style="color: black;">disable</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
        <span style="color: #ff7700;font-weight:bold;">return</span>
&nbsp;
    @<span style="color: #008000;">property</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> count<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
        The number of breaks trapped.
        '</span><span style="color: #483d8b;">''</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>._count
&nbsp;
    @<span style="color: #008000;">property</span>
    <span style="color: #ff7700;font-weight:bold;">def</span> trapped<span style="color: black;">&#40;</span><span style="color: #008000;">self</span><span style="color: black;">&#41;</span>:
        <span style="color: #483d8b;">''</span><span style="color: #483d8b;">'
        Whether a break was trapped.
        '</span><span style="color: #483d8b;">''</span>
        <span style="color: #ff7700;font-weight:bold;">return</span> <span style="color: #008000;">self</span>._count <span style="color: #66cc66;">&gt;</span> <span style="color: #ff4500;">0</span></pre></div></div>

<p>To use this, make an instance and then enable the instance.  If you repeatedly hit CTRL+C you will eventually disable it (see <tt>emphatic</tt> in the <tt>__init__</tt>).</p>

<div class="wp_syntax"><div class="code"><pre class="python" style="font-family:monospace;"><span style="color: #808080; font-style: italic;"># Trap break.</span>
bh = BreakHandler<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
bh.<span style="color: black;">enable</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
<span style="color: #ff7700;font-weight:bold;">for</span> item <span style="color: #ff7700;font-weight:bold;">in</span> big_set:
    <span style="color: #ff7700;font-weight:bold;">if</span> bh.<span style="color: black;">trapped</span>:
        <span style="color: #ff7700;font-weight:bold;">print</span> <span style="color: #483d8b;">'Stopping at user request (keyboard interrupt)...'</span>
        <span style="color: #ff7700;font-weight:bold;">break</span>
    do_thing_1<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    do_thing_2<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
    do_thing_3<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
do_cleanup<span style="color: black;">&#40;</span><span style="color: black;">&#41;</span>
bh.<span style="color: black;">disable</span><span style="color: black;">&#40;</span><span style="color: black;">&#41;</span></pre></div></div>

<p>If you press CTRL+C, it is detected at the <em>start</em> of the loop, and break is called.  Then <tt>do_cleanup()</tt> runs, and the break handler is disabled, returning things to normal.  The idea is that <tt>do_thing_1()</tt>, <tt>do_thing_2()</tt>, and <tt>do_thing_3()</tt> all run to completion, even when the user presses CTRL+C, and <tt>do_cleanup()</tt> always runs when the loop is exited.</p>
<p>I consider this public domain; if you like it, use it. If you don&#8217;t like it, don&#8217;t use it. If you have suggestions, please leave me a comment.<!--more--></p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fstacyprowell.com%2Fblog%2F2009%2F03%2F30%2Ftrapping-ctrlc-in-python%2F&amp;linkname=Trapping%20CTRL%2BC%20in%20Python"><img src="http://stacyprowell.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://stacyprowell.com/blog/2009/03/30/trapping-ctrlc-in-python/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Gibberish</title>
		<link>http://stacyprowell.com/blog/2009/03/17/gibberish/</link>
		<comments>http://stacyprowell.com/blog/2009/03/17/gibberish/#comments</comments>
		<pubDate>Tue, 17 Mar 2009 20:49:57 +0000</pubDate>
		<dc:creator>stacy</dc:creator>
				<category><![CDATA[Nuisances]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[linkedin]]></category>

		<guid isPermaLink="false">http://stacyprowell.com/blog/?p=24</guid>
		<description><![CDATA[The field of computer science is probably the area of knowledge that is closest to pure gibberish.]]></description>
			<content:encoded><![CDATA[<blockquote><p><strong>computer science</strong>: <em>n.</em> a study akin to numerology and astrology, but lacking the precision of the former and the success of the latter.</p>
<p style="text-align: right;">&#8211; Stan Kelly-Bootle, <em>The Devil&#8217;s DP Dictionary</em></p>
</blockquote>
<p style="text-align: left;">I&#8217;d say the above is no longer true: computer science is successful.  But it really isn&#8217;t very precise.</p>
<p style="text-align: left;">The field of computer science is probably the area of knowledge that is closest to pure gibberish. <span id="more-24"></span>On my shelf are books with the titles <em>Python in a Nutshell</em>, <em>Enterprise Java Beans</em>, and <em>MySQL &amp; mSQL</em>.  A random passage reads:</p>
<blockquote>
<p style="text-align: left;">In this example, gmpy manages to compensate for the float&#8217;s &#8220;representation error&#8221; and emit the exact fraction that you presumably meant rather than the mathematically exact one, which tends to be less useful.</p>
<p style="text-align: right;">&#8211; <em>Python in a Nutshell</em>, p. 374</p>
</blockquote>
<p style="text-align: left;">You get the point.</p>
<p>This is because where other fields invent new names for new concepts, computer science tends to borrow old names for new concepts. Thus &#8220;bean&#8221; and &#8220;object&#8221; take on new meanings. Even mathematics tends to coin terms carefully, and use names for specific concepts, such as &#8220;Jacobi identity.&#8221;  You won&#8217;t confuse that with a desert topping, and other mathematicians will typically know what you mean.</p>
<p>Sometimes things get really confusing as perfectly good words get used up.  Like the word <em>word</em>, which means 16 bits (bits?) on most computers.  Wouldn&#8217;t want to confuse that with a <em>dword</em>, or <em>double word</em>.  You get the confusion of the specific versus the general, when words like <em>object</em>, <em>entity</em>, and <em>attribute</em> get used up.  Then you get text like the following (I plead the Fifth on where this originates):</p>
<blockquote><p>If the entity is a class object then the collection of known object classes is updated with the provided class object.  Otherwise the object&#8217;s class is declared to the container manager prior to being serialized.</p></blockquote>
<p>Fred Brooks pointed out that most fields study what&#8217;s out there; natural phenomena, if you will. Computer science studies its own invented concepts, and they could have been implemented in different ways and often are; there are many competing ways of doing things.</p>
<p>All this is relatively important. Computer scientists, programmers, and others who work in the field develop an affinity for this sort of silliness and help perpetuate it, often just for fun.  Need a name for your just-in-time compiler?  How about ElectricalFire?  (Apparently the other name proposed was, famously, &#8220;sexual chocolate.&#8221;)</p>
<p>The goal isn&#8217;t to be perspicuous (or I wouldn&#8217;t have used that word, after all), but to have fun.  And in the end, isn&#8217;t that what computer science really should be all about?</p>
<a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save?linkurl=http%3A%2F%2Fstacyprowell.com%2Fblog%2F2009%2F03%2F17%2Fgibberish%2F&amp;linkname=Gibberish"><img src="http://stacyprowell.com/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a>]]></content:encoded>
			<wfw:commentRss>http://stacyprowell.com/blog/2009/03/17/gibberish/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
