<?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/"
	>

<channel>
	<title>For.example &#187; Smalltalk</title>
	<atom:link href="http://www.iam.unibe.ch/~akuhn/blog/category/smalltalk/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.iam.unibe.ch/~akuhn/blog</link>
	<description>Random notes on software, programming and languages.</description>
	<pubDate>Tue, 08 May 2012 02:10:00 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Pharo Superpower: Respond to any Message</title>
		<link>http://www.iam.unibe.ch/~akuhn/blog/2010/pharo-superpower-respond-to-any-message/</link>
		<comments>http://www.iam.unibe.ch/~akuhn/blog/2010/pharo-superpower-respond-to-any-message/#comments</comments>
		<pubDate>Tue, 19 Jan 2010 07:38:58 +0000</pubDate>
		<dc:creator>akuhn</dc:creator>
		
		<category><![CDATA[Smalltalk]]></category>

		<category><![CDATA[Superpowers]]></category>

		<guid isPermaLink="false">http://www.iam.unibe.ch/~akuhn/blog/?p=597</guid>
		<description><![CDATA[
For the fifth week in a row we’re stepping into the Pharo superpowers booth. Today we shall learn how to create objects that respond to any message. That is, objects that respond to a message without implementing a corresponding method. Again, as with sending any message, this superpower can be used for the good (if [...]]]></description>
			<content:encoded><![CDATA[<div style="float:right;margin-left:1em;margin-top:-1ex"><a href="http://pharo-project.org/"><img style="border:none;margin:0px" title="Logo of the Pharo Smalltalk programming languages." src="http://www.iam.unibe.ch/~akuhn/blog/wp-content/uploads/2010/01/pharo-logo-200px.png" alt="" width="194" height="194" /></a></div>
<p>For the fifth week in a row we’re stepping into the Pharo <a href="http://www.iam.unibe.ch/~akuhn/blog/category/superpowers/">superpowers</a> booth. Today we shall learn how to create objects that respond to any message. That is, objects that respond to a message without implementing a corresponding method. Again, as with <a href="http://www.iam.unibe.ch/~akuhn/blog/2010/pharo-superpower-send-any-messag/">sending any message</a>, this superpower can be used for the good (if used with care) and I will thus discuss an example that I consider good use below.</p>
<p>When a message is sent to a Smalltalk object, the message name is looked up in the method dictionary of the object’s class and its superclasses. If a method whose name matches the message is found, that method is executed. However, if no matching method is found a special message is sent to the object, which is</p>
<pre><code>#doesNotUnderstand:</code></pre>
<p>By default, the implementation of <code>#doesNotUnderstand:</code> opens a debugger (or more precise, the pre-debugger dialog that we all know from test-driven development). However, we are free to override <code>#doesNotUnderstand:</code> and thus respond to any unknown message.</p>
<p>As a (dadaistic) example, let’s implement a Lorem ipsum object</p>
<pre><code>Object subclass: #Lorem instanceVariableNames: 'expects'
</code></pre>
<p>with an <code>ipsum</code> constructor</p>
<pre><code>Lorem class &gt;&gt; ispum
    ^ self new
</code></pre>
<p>and the following two methods</p>
<pre><code>Lorem &gt;&gt; initialize
    expects := #(dolor sit amet "to be continued ad nauseam..." nil)

Lorem &gt;&gt; doesNotUnderstand: aMessage
    ^ aMessage selector == expects first
        ifTrue: [ expects := expects allButFirst. self ]
        ifFalse: [ super doesNotUnderstand: aMessage ]
</code></pre>
<p>So, if you ever doubted that <em>virtually any</em> English sentence is valid Smalltalk, here is your proof :)</p>
<pre><code>Lorem ipsum dolor sit amet.
</code></pre>
<p>This executes as valid Smalltalk code, without ever having implement any <code>#dolor</code> , <code>#sit</code> or <code>#amet</code> method! If however, we deviate from the canonical Lorem ipsum sequence we’ll get the usual <code>MessageNotUnderstood</code> error.</p>
<pre><code>[ Lorem ipsum dolor zork ] should signal: MessageNotUnderstood.
</code></pre>
<p>As a more sensible examples let’s consider a list that responds to any messages understood by all its elements.</p>
<pre><code>OrderedCollection subclass: #Group.

Group &gt;&gt; eachRespondsTo: aSelector
    ^ self allSatisfy: [ :each | each respondsTo: aSelector ]

Group &gt;&gt; doesNotUnderstand: aMessage
    ^ (self eachRespondsTo: aMessage selector)
        ifTrue: [ self collect: [ :each | aMessage sendTo: each ] ]
        ifFalse: [ super doesNotUnderstand: aMessage ]
</code></pre>
<p>As you can see, the implementation of <code>#doesNotUnderstand:</code> follows the same pattern as above. We check whether we want to handle the message, and if not, we delegate to the default implementation in object (which will open a pre-debugger dialog).</p>
<p>Keen readers might have already noted a limitation of above approach: when you override <code>#doesNotUnderstand:</code> but not <code>#respondsTo:</code> your object will respond to a new message (through the means of <code>#doesNotUnderstand:</code>) but still insists that it does not respond to that message when queried with <code>#respondsTo:</code>.</p>
<p>So we’ll have to override <code>#respondsTo:</code> as well</p>
<pre><code>Group &gt;&gt; respondsTo: aSelector
    ^ (super respondsTo: aSelector) or: [ self eachRespondsTo: aSelector ]
</code></pre>
<p>It is a sad but true fact, that over 90% of all <code>#doesNotUnderstand:</code> overriders that you’ll find out there do not override <code>#respondsTo:</code> as well—even though they should!</p>
<p>So now our new class is ready for a bunch of expectations (please refer to <a href="http://www.squeaksource.com/phexample.html">Phexample</a> for more details on expectation matchers)</p>
<pre><code>g := Group new.
g should not respondTo: #x.
[ g x ] should raise: MessageNotUnderstood.
g add: 2 @ 3.
g add: 3 @ 4.
g add: 1 @ 2.
g should respondTo: #x.
g x should beSameSequence: #(2 3 1).
g y should beSameSequence: #(3 4 2).
</code></pre>
<p>BTW, <em>if you are an OSX user and looking for a language that provides this feature by default, take a look at <a href="http://www.fscript.org">F-Script</a> by Philippe Mougin. F-Script also offers a plethora of awesome features beyond projection of messages, for example it allows you to manipulate the Cocoa objects of any OSX application—at runtime!</em></p>
<p>As a best practice, you should only override <code>#doesNotUnderstand:</code> and <code>#respondsTo:</code> on your own classes. Just imagine what might happen when two or more stakeholders attempt to override <code>#doesNotUnderstand:</code> in, for example, <code>Collection</code>, only one of the extensions will eventually remain and thus leave the system in an undefined state with overloaded extensions.</p>
<p>If you know more good (or evil, <em>uoarharhar</em>) uses of <code>#doesNotUnderstand:</code> share them in the comments.</p>
<p>Hackety hacking!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iam.unibe.ch/~akuhn/blog/2010/pharo-superpower-respond-to-any-message/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Pharo Superpower: Send Any Message</title>
		<link>http://www.iam.unibe.ch/~akuhn/blog/2010/pharo-superpower-send-any-messag/</link>
		<comments>http://www.iam.unibe.ch/~akuhn/blog/2010/pharo-superpower-send-any-messag/#comments</comments>
		<pubDate>Tue, 12 Jan 2010 10:20:55 +0000</pubDate>
		<dc:creator>akuhn</dc:creator>
		
		<category><![CDATA[Smalltalk]]></category>

		<category><![CDATA[Superpowers]]></category>

		<guid isPermaLink="false">http://www.iam.unibe.ch/~akuhn/blog/?p=579</guid>
		<description><![CDATA[
In Pharo Smalltalk you may send any message even if it&#8217;s name is not known at compile time. Sending any message is one of the superpowers that can be used for the good, even when doing application programming, therefore I will discuss best practices in the end.
First of all, recall that &#8220;sending a message&#8221; is [...]]]></description>
			<content:encoded><![CDATA[<div style="float:right;margin-left:1em;margin-top:-1ex"><a href="http://pharo-project.org/"><img style="border:none;margin:0px" src="http://www.iam.unibe.ch/~akuhn/blog/wp-content/uploads/2010/01/pharo-logo-200px.png" title="Logo of the Pharo Smalltalk programming languages." width="194" height="194" /></a></div>
<p>In <a href="http://pharo-project.org/">Pharo Smalltalk</a> you may send any message even if it&#8217;s name is not known at compile time. Sending any message is one of the superpowers that can be used for the good, even when doing application programming, therefore I will discuss best practices in the end.</p>
<p>First of all, recall that &#8220;sending a message&#8221; is Smalltalk jargon for calling a method. Since sending a message is synchronous in Smalltalk, <em>ie</em> it blocks until the receiver returns, it is basically the same as a method call and the actual difference thus of philosophical nature only. (There is an implementation difference deep down at the language&#8217;s core, but that shall not be discussed today as it does not matter to programmers.)</p>
<p>BTW, <em>this is the fourth post in the <a href="http://www.iam.unibe.ch/~akuhn/blog/category/superpowers/">Superpower</a> series.</em></p>
<p>There are many ways to send any message, mainly due to optional and variable arguments which are not well supported by Smalltalk syntax. The most basic form is </p>
<pre><code>object perform: #symbol withArguments: anArray
</code></pre>
<p>Let&#8217;s consider a real example</p>
<pre><code>string = 'Lorem'.
string perform: #size. "=&gt; 5"
string perform: #at: with: 1. "=&gt; $L"
string perform: #copyFrom:to: with: 2 with: 4. "=&gt; 'ore'"
</code></pre>
<p>If the number of arguments is not known at compile time, we may use</p>
<pre><code>string perform: aSymbol withArguments: anArray.
string perform: aSymbol withEnoughArguments: anArray.
</code></pre>
<p>the first expects that the array matches the arity (number of arguments) of the target method, the latter will just use as many arguments are required. This is most useful to send a message with optional arguments.</p>
<p>So when is sending any message for the good or for the evil?</p>
<p>Whenever possible, try to avoid using <code>#perform:</code> because it is less readable. When a reader of your program looks at the a <code>#perform:</code> it is not obvious which message is being sent at runtime. Also, messages that are sent with <code>#perform:</code> will not be shown when browsing all senders of a message. There is one subtle difference here: If the dynamically sent message is stored somewhere as symbols, at least that symbols will show up when looking for senders. If however, the dynamically sent message is composed using string concatenation, it wont show up at all. It might even seem as if its implementers are never used, which can be very confusing to the reader.</p>
<p>For all above reasons you should only use <code>#perform:</code> when you have good reason to do so. And <em>if</em> you use it, make sure that the dynamically sent messages are all stored as a symbol somewhere else. Best of all, make sure that <em>all</em> code involved into dynamically sending message is encapsulated by one single class.</p>
<p>I will provide an example from <a href="http://scg.unibe.ch/staff/adriankuhn/hapax">Hapax</a>&#8217;s clustering algorithm. When you do hierarchical clustering, there are different ways to link small clusters into large clusters. The call to this linkage method is buried deep down in the internals of the clustering algorithm, so the <code>ClusteringEngine</code> class uses a strategy pattern to pick the right linkage method. The choice of strategy is stored as a symbol in an instance variable and then used as follows </p>
<pre><code>Object subclass: #ClusteringEngine
    instanceVariableNames: 'distanceMatrix dendrogram linkage'
    classVariableNames: ''

ClusteringEngine &gt;&gt; linkage: aSelector
    linkage := aSelector

ClusteringEngine &gt;&gt; linkage
    ^ linkage

ClusteringEngine &gt;&gt; allLinkageSelectors
    ^ #( averageLinkage centroid completeLinkage meanLinkage singleLinkeage wardsMethod )

ClusteringEngine &gt;&gt; run
    (distanceMatrix size - 1) timesRepeat:
        [self findMinimum.
        self perform: linkage].

ClusteringEngine &gt;&gt; averageLinkage
    "implementation omitted..."

"et cetera..."
</code></pre>
<p>All code is encapsulated with one class such that a reader can find it all in one place when browsing the source code.</p>
<p>Any other use of <code>#perform:</code>, in particular when string concatenation of selectors is involved, is evil and <a href="http://www.iam.unibe.ch/~akuhn/blog/2009/superpowers-in-library-design/">should be limited to library design</a>, if used at all.</p>
<p>A note regarding performance. Using <code>#perform:</code> is as fast as sending a message the normal way. So contrary to popular believe there is not performance penalty&mdash;at least not in Pharo Smalltalk, in other dialects that do use JIT compilation there might be severe performance penalties though).</p>
<p>Hackety hacking!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iam.unibe.ch/~akuhn/blog/2010/pharo-superpower-send-any-messag/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Imagine, IDE search so faaaaast that&#8230;</title>
		<link>http://www.iam.unibe.ch/~akuhn/blog/2010/imagine-ide-search-so-faaaaast-that/</link>
		<comments>http://www.iam.unibe.ch/~akuhn/blog/2010/imagine-ide-search-so-faaaaast-that/#comments</comments>
		<pubDate>Fri, 08 Jan 2010 23:33:36 +0000</pubDate>
		<dc:creator>akuhn</dc:creator>
		
		<category><![CDATA[SUITE]]></category>

		<category><![CDATA[SUITE 2010]]></category>

		<category><![CDATA[Smalltalk]]></category>

		<guid isPermaLink="false">http://www.iam.unibe.ch/~akuhn/blog/?p=545</guid>
		<description><![CDATA[Imagine an IDE where search were so fast that it became the sole means of navigation.
In such a system, one would not write //TODO but just this.todo() since browsing the callers of todo is so fast that is it faster than using a dedicated task view. The system might even be hidden to your Yahoogle [...]]]></description>
			<content:encoded><![CDATA[<p>Imagine an IDE where search were so fast that it became the sole means of navigation.</p>
<p>In such a system, one would not write <code>//TODO</code> but just <code>this.todo()</code> since browsing the callers of <code>todo</code> is so fast that is it faster than using a dedicated task view. The system might even be hidden to your Yahoogle query for &#8220;fast search in IDE&#8221; since in such a system search is so fast and ease-to-use that its ceases to be used as a verb. For example, the devs might speak of “browse callers” rather than “search callers” since no intermediate search step is between them and their need.</p>
<p>I can see some of my readers smile now :) …because…</p>
<p>There is such a system. It is little known since it predates the invention of today’s filesystems and has never made the transition to file based software development itself. It is <a href="http://www.pharobyexample.org/">Smalltalk</a>, the old lady of dynamic programming languages.</p>
<p>In the IDE of Smalltalk “browse callers of” and “browse implements of” are the main means of navigation. Executing these actions opens&ndash;in the same instant&ndash;a new editor window with all callers (or implementers) of a given method. No spinning wheel, no tree list of search results, no browsing of results even, you are right there and can start editing.</p>
<p>NB: <em>in fact, seasoned Smalltalk devs even omit “browse” and just say “senders’of” (in message-oriented languages such as Smalltalk and Ruby, objects don’t call methods but send each other messages) and “implementers’of” instead of a proper verbs.</em></p>
<p>For the alert reader: yes, graphical UIs predate hierarchical file systems. And even better, Smalltalk invented graphical windows. But we’ll stop the children’s games here. It does not matter who was first, but who makes the best out of it. And there, the winner is obvious.</p>
<p>The point I want to make is rather that there is a system out there with a 30-year head start in IDE search. So as researchers we can go and learn from the experience of that community, and then used what we learned to advance the state of current IDEs beyond it. Breakpoints, for example, are also just another method call in Smalltalk. You insert a call to <code>#halt()</code> where ever you want, and to view the list of current break points you browse all callers of halt. Again, no need for a dedicated view. As you see, search-driven development simplifies your tool set.</p>
<p>Of course, not all your navigation needs can be satisfied by hyperjumping. Sometimes you need to drill down from top-levels packages to methods. To do so Eclipse offers the code browsing perspective, which is however never used because the package explorer view offers the same drill-down capabilities without change of perspective. In Smalltalk we get a code browsing interface as well. In fact, Eclipse inherited that perspective from its predecessor VisualAge which was IBM’s prime Smalltalk IDE before they switched to Java.</p>
<p>So before I start to tell the story of how Eclipse’s elimination of the compilation step was inherited from VisualAge as well, lemme summarize this post.</p>
<ul>
<li>Search so fast that is disappears from the list of “verbs” in your IDE.</li>
<li>Search so fast that it is called “browse code” instead.</li>
<li>Search so fast that developers, for example, us method calls as <code>TODO</code> markers.</li>
<li>Plus a drill-down interface for the remaining navigation needs that are not covered by hyperjumping.</li>
</ul>
<p>The comparison with compilation is actually quite nice: With Eclipse “compile” and “build” ceased to be used as verbs in Java development. Now devs just execute code, done. This feature was brought to Java from Smalltalk. It would be awesome if we could achieve the same kind of “knowledge transfer” for IDE search. </p>
<p>I&#8217;d say that our job as providers of IDE search is only done when search ceases to be used as a verb in software development.</p>
<p>&mdash; that said, <a href="http://scg.unibe.ch/wiki/events/suite2010">paper submission for SUITE</a> is open until January 19, 2010.</p>
<p>&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iam.unibe.ch/~akuhn/blog/2010/imagine-ide-search-so-faaaaast-that/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Pharo Superpower: Change of Class</title>
		<link>http://www.iam.unibe.ch/~akuhn/blog/2010/pharo-superpower-change-of-class/</link>
		<comments>http://www.iam.unibe.ch/~akuhn/blog/2010/pharo-superpower-change-of-class/#comments</comments>
		<pubDate>Tue, 05 Jan 2010 13:49:54 +0000</pubDate>
		<dc:creator>akuhn</dc:creator>
		
		<category><![CDATA[Smalltalk]]></category>

		<category><![CDATA[Superpowers]]></category>

		<guid isPermaLink="false">http://www.iam.unibe.ch/~akuhn/blog/?p=482</guid>
		<description><![CDATA[
Smalltalk objects are ordered by classes hierarchies. But still, an object may change its class membership! Objects are able to move between classes and hierarchies at runtime.
In this post I shall show how to transform a rabbit into a light house!
First let us create two classes Rabbit and Lighthouse with the same format. We use [...]]]></description>
			<content:encoded><![CDATA[<div style="float:right;margin-left:1em;margin-top:-1ex"><a href="http://pharo-project.org/"><img style="border:none;margin:0px" src="http://www.iam.unibe.ch/~akuhn/blog/wp-content/uploads/2010/01/pharo-logo-200px.png" title="Logo of the Pharo Smalltalk programming languages." width="194" height="194" /></a></div>
<p>Smalltalk objects are ordered by classes hierarchies. But still, an object may change its class membership! Objects are able to move between classes and hierarchies at runtime.</p>
<p>In this post I shall show how to transform a rabbit into a light house!</p>
<p>First let us create two classes <code>Rabbit</code> and <code>Lighthouse</code> with the same format. We use Pharo’s public API to do so.</p>
<pre><code>Object subclass: #Rabbit instanceVariableNames: 'age size'.
Object subclass: #Lighthouse instanceVariableNames: 'latitude longitude'.
</code></pre>
<p>Lets check that both classes are of the same format, but neither is a subclass of the other. (Please refer to <a href="http://www.squeaksource.com/phexample.html">Phexample</a> for more information on expectation matchers.)</p>
<pre><code>Rabbit format should = Lighthouse format.
Rabbit should not beKindOf: Lighthouse.
Lighthouse should not beKindOf: Rabbit.
</code></pre>
<p>Now, lets create a rabbit and transform it into an instance of a light house.</p>
<pre><code>r := Rabbit new.
r class should beKindOf: Rabbit.
r primitiveChangeClassTo: Lighthouse new.
r class should beKindOf: Lighthouse.
</code></pre>
<p>And, <em>abra cadabra</em>, we&#8217;ve turned <code>r</code> from a <code>Rabbit</code> into a <code>Lighthouse</code>!</p>
<p>To do so we use the <code>#primitiveChangeClassTo:</code> method. This method expects an instance of the target class as argument. However this instance is only used to determine the target class of the receiver. (In other Smalltalk dialects, as for example <a href="http://www.cincomsmalltalk.com/">Cincom Smalltalk</a>, <code>#changeClassTo:</code> expects a class rather than an instance. We can only guess why Pharo and its sibling <a href="http://www.squeak.org/">Squeak</a> require an instance of the target class. My guess is that this required as proof that the target class is a valid class, since otherwise it would not have been possible to create an instance of itself.)</p>
<p>Hackety hacking!</p>
<p>Post scriptum: <em>please note that it is not possible to change the class of a point to that of an associations even though both got two instance variables. This is because both are so called “compact” classes with a smaller header. We’ll cover that in another superpowers issue.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.iam.unibe.ch/~akuhn/blog/2010/pharo-superpower-change-of-class/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Dependency Injection vs. Virtual Classes</title>
		<link>http://www.iam.unibe.ch/~akuhn/blog/2009/dependency-injection-vs-virtual-classes/</link>
		<comments>http://www.iam.unibe.ch/~akuhn/blog/2009/dependency-injection-vs-virtual-classes/#comments</comments>
		<pubDate>Wed, 30 Dec 2009 17:45:43 +0000</pubDate>
		<dc:creator>akuhn</dc:creator>
		
		<category><![CDATA[Java]]></category>

		<category><![CDATA[Programming Languages]]></category>

		<category><![CDATA[Smalltalk]]></category>

		<guid isPermaLink="false">http://www.iam.unibe.ch/~akuhn/blog/?p=459</guid>
		<description><![CDATA[Every time you create an instance of a class by using the new keyword, you tightly couple your code to that class, and you will not be able to substitute that particularly implementation with a different one (at least not without recompiling the code).
Taken from an answer on stackoverflow that motivates dependency injection. Dependency injection [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>Every time you create an instance of a class by using the <code>new</code> keyword, you tightly couple your code to that class, and you will not be able to substitute that particularly implementation with a different one (at least not without recompiling the code).</p></blockquote>
<p>Taken from <a href="http://stackoverflow.com/questions/1980182/what-are-dependency-injection-spring-framework-about/1980243#1980243">an answer on stackoverflow</a> that motivates dependency injection. Dependency injection however is not the real solution, it is rather a workaround for missing <em>virtual classes</em>. In this post I will show you why.</p>
<p>For example in</p>
<pre><code>public class MyClass {
  public string sendMessage(String contents) {
    return new MailService().sendMessage(contents);
  }
}
</code></pre>
<p>you cannot use a different MessageService. This might not seem limiting at first sight, but think for example of testing. Your tests might be better off using a stub service that does not send actual emails.</p>
<p>This can and is being solved with dependency injection, yes. But the actual problem is rather a language problem: Classes are not virtual. While methods are virtual and thus looked up at runtime, classes are not.</p>
<p>In the following example, we can change the mail service by subclassing and overriding a method. This works because methods are virtual and thus late bound.</p>
<pre><code>public class MyClass {
  public string sendMessage(String contents) {
    return newMailService().sendMessage(contents);
  }
  public MailService newMailService() {
    return new MailService();
  }
}
</code></pre>
<p>What a difference a single whitespace can make!</p>
<p>When <code>newMailService</code> is called, that method name is looked up in the context of the calling method. The context of the calling method is its class. Therefore, by subclassing the containing class we can provide a different mail service.</p>
<p>Imagine the same would happen with class names. Whenever we call <code>new MailService()</code> then the class name would be looked up in the containing context. Imagine further the lookup would not stop with the class but bubble up to the containing package. Then, by “subclassing” that package we might provide a different mail service.</p>
<p>Subclassing a package is nonsense terminology, let’s rather say that we instantiate a package … and let’s further assume that packages and classes are the same, and that our system is built of nested classes.</p>
<pre><code>public class MyApplication {
  public class MyClass {
    public string sendMessage(String contents) {
      return new "MailService"().sendMessage(contents);
    }
  }
}
</code></pre>
<p>I have put the class name of <code>MailService</code> in quotes to remind you that it is the name of a virtual class name and thus looked up in the containing context.</p>
<p>Imagine further that we could pass the binding of classes to a class when creating it, then we could instantiate two versions of our application: one for real, and one for testing.</p>
<pre><code>Application forTesting = new Application(MailService = TestMailer);
Application forReal = new Application(MailService = InterwebMailer);
</code></pre>
<p>Testing and production are not the only possible contexts. Imagine for example an XML parser. Typically it creates DOM nodes, but maybe you would prefer you own implementation of nodes. Maybe even the DAO objects of your application? There we go</p>
<pre><code>XMLParser custom = new XMLParser(Node = Application.DAO);
XMLDocument doc = custom.new XMLDocument("example.xml");
</code></pre>
<p><small>
<p>NB, the second line is actually valid Java syntax: this is how you create an instance of an inner class when you are not in the same file as its outer class.</p>
<p></small></p>
<p>— So this is how dependency injection should <em>really</em> work!</p>
<p>And it is even not that far from reality. Both <a href="http://www.daimi.au.dk/~beta/">Beta</a> and <a href="http://newspeaklanguage.org/">Newspeak</a> (the new language by <a href="http://gbracha.blogspot.com/">Gilad Bracha</a>) do have virtual classes and both do have nested classes, and in both classes what I just described is how you decouple your packages in these languages.</p>
<p>And, <em>hup hup hup</em>, another design pattern has been disguised as a missing language feature :)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iam.unibe.ch/~akuhn/blog/2009/dependency-injection-vs-virtual-classes/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Pharo Superpower: Use Anything as Class</title>
		<link>http://www.iam.unibe.ch/~akuhn/blog/2009/pharo-superpower-use-anything-as-class/</link>
		<comments>http://www.iam.unibe.ch/~akuhn/blog/2009/pharo-superpower-use-anything-as-class/#comments</comments>
		<pubDate>Mon, 28 Dec 2009 13:18:34 +0000</pubDate>
		<dc:creator>akuhn</dc:creator>
		
		<category><![CDATA[Smalltalk]]></category>

		<category><![CDATA[Superpowers]]></category>

		<guid isPermaLink="false">http://www.iam.unibe.ch/~akuhn/blog/?p=441</guid>
		<description><![CDATA[
In Pharo Smalltalk, not only can you create anonymous classes at runtime, you can use anything as a class. You can create objects whose class is not a class. Mind boggling, ain’t it?
So if an object&#8217;s class is not a class, what is it then? Recall that in Smalltalk all classes are objects, thus if [...]]]></description>
			<content:encoded><![CDATA[<div style="float:right;margin-left:1em;margin-top:-1ex"><a href="http://pharo-project.org/"><img style="border:none;margin:0px" src="http://www.iam.unibe.ch/~akuhn/blog/wp-content/uploads/2010/01/pharo-logo-200px.png" title="Logo of the Pharo Smalltalk programming languages." width="194" height="194" /></a></div>
<p>In <a href="http://pharo-project.org/">Pharo</a> Smalltalk, not only can you <a href="http://www.iam.unibe.ch/~akuhn/blog/2009/pharo-superpower-create-anonymous-class/">create anonymous classes</a> at runtime, you can <em>use anything as a class</em>. You can create objects whose class is not a class. Mind boggling, ain’t it?</p>
<p>So if an object&#8217;s class is not a class, what is it then? Recall that in Smalltalk all classes are objects, thus if a class is not a class it is at least an object. When I first discovered this superpower I though “this must be a bug in the virtual machine”. However, the <a href="http://www.librarything.com/work/9105316">Blue Book of Smalltak-80</a> confirms that this is by design. The virtual machine of Smalltalk does not require that classes should inherit from <code>Behavior</code>.</p>
<p>In this post, I shall use an instance of <code>Interval</code> to create a new object whose class is … well, an instance of interval rather than a proper class.</p>
<p>The choice of interval is not a coincidence. In fact, we may only use objects as classes that have at least three instance variables. The first instance variable must refer to the superclass (which neither must be a class, but to keep things simple we’ll use <code>Object</code> in our example), the second instance variable must refer to a method dictionary, and the third instance variable must encode a magic number that specified the class format.</p>
<pre><code>g := Interval basicNew.
g instVarAt: 1 put: Object.
g instVarAt: 2 put: MethodDictionary new.
g instVarAt: 3 put: Object format.
</code></pre>
<p>Next we compile a method that implements primitive #70 into interval. Primitive #70 can be used to create new instances. So we can use primitive #70 to create an instance of <code>g</code>.</p>
<pre><code>Interval compile: 'primitive70 &lt;primitive: 70&gt;'.
gg := g primitive70.
</code></pre>
<p>Let’s verify that <code>gg</code> is really an instance of <code>g</code>. (Please refer to <a href="http://www.squeaksource.com/phexample.html">Phexample</a> for more information on expectation matchers.)</p>
<pre><code>gg class should beSameAs: g.
gg class should not beKindOf: Behavior.
</code></pre>
<p>Now we can add methods to the dictionary in <code>g</code>’s second instance variable and they become available on <code>gg</code>. We’ll add a method <code>#zork</code> that returns self.</p>
<pre><code>methods := g instVarAt: 2.
methods at: #zork put: CompiledMethod toReturnSelf.
gg zork should = gg.
</code></pre>
<p>Unfortunately we cannot write <code>gg should respondTo: #zork</code> since <code>g</code> is not a real class and thus <code>gg</code> cannot send <code>#canUnderstand:</code> to <code>g</code>. Also you might not be able to print or inspect <code>gg</code> for the same reason, depending on the version of Pharo you are using.</p>
<p>Hackety hacking!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iam.unibe.ch/~akuhn/blog/2009/pharo-superpower-use-anything-as-class/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Pharo Superpower: Create Anonymous Class</title>
		<link>http://www.iam.unibe.ch/~akuhn/blog/2009/pharo-superpower-create-anonymous-class/</link>
		<comments>http://www.iam.unibe.ch/~akuhn/blog/2009/pharo-superpower-create-anonymous-class/#comments</comments>
		<pubDate>Mon, 21 Dec 2009 21:25:33 +0000</pubDate>
		<dc:creator>akuhn</dc:creator>
		
		<category><![CDATA[Smalltalk]]></category>

		<category><![CDATA[Superpowers]]></category>

		<guid isPermaLink="false">http://www.iam.unibe.ch/~akuhn/blog/?p=433</guid>
		<description><![CDATA[
One of the superpowers in Pharo Smalltalk is to create new classes at runtime. Actually, whenever you accept a class definition in the class browser that very definition is evaluated to create a new class. And since all development in Smalltalk happens eo ipso at runtime the accpeted class definition creates a class at runtime. [...]]]></description>
			<content:encoded><![CDATA[<div style="float:right;margin-left:1em;margin-top:-1ex"><a href="http://pharo-project.org/"><img style="border:none;margin:0px" src="http://www.iam.unibe.ch/~akuhn/blog/wp-content/uploads/2010/01/pharo-logo-200px.png" title="Logo of the Pharo Smalltalk programming languages." width="194" height="194" /></a></div>
<p>One of the superpowers in <a href="http://pharo-project.org/">Pharo Smalltalk</a> is to create new classes at runtime. Actually, whenever you accept a class definition in the class browser that very definition is evaluated to create a new class. And since all development in Smalltalk happens <em>eo ipso</em> at runtime the accpeted class definition creates a class at runtime. Superpower for the masses, it can be done.</p>
<p>In this post, I shall cover how to create <em>anonymous</em> classes at runtime. As an example, we’ll create an anonymous subclass of point that extends <code>Point</code> with a color attribute.</p>
<p>To create an anonymous class, you’ll first need to create an anonymous metaclass. (Hey, nobody said superpowers ain’t confusing!) The newly created metaclass needs a superclass, a method dictionary and a magic format number. Computation of format numbers is explained later.</p>
<pre><code>m := Metaclass new.
m superclass: Point class.
m methodDict: MethodDictionary new.
m setFormat: 156.
</code></pre>
<p>Now we can create the actual anonymous class. Classes are instances of their metaclass. For each metaclass there is only one instance, thus if you send <code>#new</code> twice an error is thrown. As above, the newly created class needs a superclass, a method dictionary and a magic format number.</p>
<pre><code>c := m new.
c superclass: Point.
c methodDict: MethodDictionary new.
c setFormat: 136.
</code></pre>
<p>Now we can create an instance of the anonymous class. We’ll verify the new instance to check that it actually meets our expectations. (Please refer to <a href="http://www.squeaksource.com/phexample.html">Phexample</a> for more information on expectation matchers.)</p>
<pre><code>p := c x: 3 y: 4.
p asString should = '3@4'.
p class should = c.
p class class should = m.
p should beKindOf: Point.
</code></pre>
<p>Next we’ll create accessors for the additional instance variable of <code>c</code>, which shall be named <code>color</code>. And we’ll also override <code>#printOn:</code> to report the color.</p>
<pre><code>c setInstVarNames: { 'color' }.
c compile: 'color
    ^color'.
c compile: 'color: aString
    color := aString'.
c compile: 'printOn: out
    super printOn: out.
    out nextPutAll: '' is ''.
    out nextPutAll: color'.
</code></pre>
<p>Again, we’ll verify our instance.</p>
<pre><code>p color should = nil.
p color: #yellow.
p color should = #yellow.
p asString should = '3@4 is yellow'.
</code></pre>
<p>I promised to explain how to compute the magic numbers above. The format number encodes both the number of instance variables and the type of an object. For example, an object can be indexable or not. All this is stuffed into a 32-bit number. To compute the format number, we’ll use a method in <code>ClassBuilder</code> that does the bit-fiddling for us.</p>
<pre><code>metaformat := ClassBuilder new
    computeFormat: #normal instSize: 0
    forSuper: Point class ccIndex: 0.
format := ClassBuilder new
    computeFormat: #normal instSize: 1
    forSuper: Point ccIndex: 0.
</code></pre>
<p>Important for us are the parameters <code>instSize:</code> and <code>forSuper:</code> which expect the number of instance variables and the superclass of the to be created class. Please note, the number of instance variables should not include inherited instance variables, but only the number of to be added instance variables: which is zero for our metaclass, and one for our colored point class.</p>
<p>Hackety hacking!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iam.unibe.ch/~akuhn/blog/2009/pharo-superpower-create-anonymous-class/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Superpowers in Library Design</title>
		<link>http://www.iam.unibe.ch/~akuhn/blog/2009/superpowers-in-library-design/</link>
		<comments>http://www.iam.unibe.ch/~akuhn/blog/2009/superpowers-in-library-design/#comments</comments>
		<pubDate>Wed, 25 Nov 2009 08:04:35 +0000</pubDate>
		<dc:creator>akuhn</dc:creator>
		
		<category><![CDATA[Smalltalk]]></category>

		<category><![CDATA[Superpowers]]></category>

		<guid isPermaLink="false">http://www.iam.unibe.ch/~akuhn/blog/?p=395</guid>
		<description><![CDATA[When designing libraries, using superpowers can be for the good.
Superpowers are language features, so powerful that even seasoned developers are likely to used them for the evil … wreaking havoc on maintainers and co-workers alike. Just think of hooking into calls to missing methods, modifying classes at runtime, or even rewriting the call stack of [...]]]></description>
			<content:encoded><![CDATA[<p>When designing libraries, using superpowers can be for the good.</p>
<p>Superpowers are language features, so powerful that even seasoned developers are likely to used them for the evil … wreaking havoc on maintainers and co-workers alike. Just think of hooking into calls to missing methods, modifying classes at runtime, or even rewriting the call stack of a runnning program!</p>
<p>I have first heard the term superpowers being used in 2008, at an OOPSLA workshop by Martin McClure and Travis Griggs. In a room full of hackers and language designers, everyone would tell about their most spectacular use of obscure languages features and then get voted whether their use was for the good or for the evil—most were voted for the evil!</p>
<p>Some languages ship without superpowers at all. The fear that programmers are gonna use these superpowers for the evil is understandable. However, excluding superpowers from a language may fatally limit the power of library features.</p>
<p>Just think of object serialization: deserialized objects from a binary stream would be impossible without the superpowers to allocate objects without calling any constructor, to call private methods, and to change the value of final fields. And in fact, even Java’s <code>ObjectInputStream</code> wouldn’t get along without exactly these superpowers. They are all available to Sun’s engineers (and everyone aware of <code>sun.misc.Unsafe</code>, go figure) but not to Joe Average programmer.</p>
<p>In this post, I’ll show how <a href="http://smalltalkthoughts.blogspot.com">Niko</a> and me are using Smalltalk’s superpowers for the good of <a href="http://www.squeaksource.com/phexample.html">Phexample</a> users.</p>
<p>The initial design of Phexample, boolean <a href="http://www.iam.unibe.ch/~akuhn/blog/2009/shoulda-use-this-in-pharo">expectation matchers</a> had a somewhat awkward syntax, which got soon nicknamed <a href="http://smalltalkthoughts.blogspot.com/2009/11/phexamples-lolcats-syntax.html">“lolcat syntax”</a> by users</p>
<pre><code>#(Lorem ipsum dolor) should be isEmpty.
</code></pre>
<p>the rational for this design was that we saw no other way to provide users with an error message whose text refers to <code>#isEmpty</code> by name! If we change the syntax to <code>#() isEmpty should be true</code> the name of the boolean property is out of reach (ie, not on the stack) when the matcher fails.</p>
<p><a href="http://rspec.info/">RSpec</a>, by the way, does not suffer from lolcat syntax because Ruby&#8217;s boolean properties use a question mark rather than starting with a verb. Users can write <code>%w{Lorem ipsum dolor} should be empty?</code> without getting caught in the <a href="http://en.wikipedia.org/wiki/Uncanny_valley">uncanny valley</a> of DSL design.</p>
<p>The way out of the uncanny valley is to allow user to put the boolean property first, as in</p>
<pre><code>#(Lorem ipsum dolor) isEmpty should be true.
</code></pre>
<p>and then, whenever an expectation fails, walk back in both stack and bytecode to recover the property name. There is two challenges here,</p>
<ul>
<li>to walk back in the stack, from where the expectation fails internally to the method’s stack frame where <code>should be true</code> was sent,</li>
<li>to walk back in the bytecode, from the current program counter to the call-site that is lexically before the initial <code>#should</code> call.</li>
</ul>
<p>To make things more complicated, there can be an arbitrary number of domain messages between <code>#true</code> and <code>#should</code>, as for example in negated exceptions.</p>
<p>The first challenge, ie getting back to the stack frame of the DSL call, is solved by walking back the stack until we are outside of the current matcher instance</p>
<pre><code>frame := thisContext.
[ frame := frame sender.
  frame receiver == self ] whileTrue.
</code></pre>
<p><code>thisContext</code> is a pseudovariable, like <code>this</code> and <code>super</code>, that provides access to the current stack frame. That is the stack frame of the above code snipped. Then, we use <code>#sender</code> to walk up the stack until we reach the latest frame outside of the current matcher instance. In the above comparison <code>frame receiver</code> refers to the value of the “self” of the stack frame, and <code>self</code> to the value of the “self” of the code snippet itself. No one said Superpowers ain’t confusing.</p>
<p>The second challenge, ie recovering the property name, is solved by recovering all message sends (ie method call-sites) from the bydecode of the method where <code>should be true</code> was sent</p>
<pre><code>scanner := InstructionStream on: frame method.
sent := Stack new.
scanner scanFor: [ :bytecode |
    sent push: scanner selectorToSendOrSelf.
    (frame pc - 1) &lt;= scanner pc ].
</code></pre>
<p>So, <code>frame method</code> now refers to the method where <code>should be true</code> was sent. In this method, we scan from the begin of the bytecode up to where we are, and push all sent messages (ie method names) on a stack. As Niko already mentioned in his <a href="http://smalltalkthoughts.blogspot.com/2009/11/and-its-done-phexample-has-no-more.html">“no more lolcats”</a> post: bytecodes in Smalltalk have different sizes, thus we cannot just walk backwards from where we are.</p>
<p>Scanning bytecodes with <code>#scanFor:</code> stops when the last line of the block evaluates to true. Since the current program counter points to the bytecode <em>just after</em> the send-site of <code>true</code>, with subtract minus one when comparing the counter of where we are and the scanner’s counter.</p>
<p>So now we’ve got all message sends on a stack up to <code>true</code>. We keep dropping messages names from the stack, up to and including <code>#should</code></p>
<pre><code>[ sent isEmpty ifTrue: [ ^'&lt;unknown&gt;' ].
  sent pop == #should ] whileFalse.
sent top isSymbol ifFalse: [ ^'&lt;unknown&gt;' ]
^sent top
</code></pre>
<p>which leaves us with the name of the boolean property that was sent before the <code>should be true</code> sequence. Of course, we guard against running out of stack elements while doing so.</p>
<p>Thus now, when executing</p>
<pre><code>#(Lorem ipsum dolor) isEmpty shoud be true.
</code></pre>
<p>we get the message text</p>
<pre><code>TestFailure: expected #isEmpty to be true
</code></pre>
<p>IM OUTTA YR LIBRARY.ST<br />
KTHXBYE</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iam.unibe.ch/~akuhn/blog/2009/superpowers-in-library-design/feed/</wfw:commentRss>
		</item>
		<item>
		<title>One-letter method names, good design?</title>
		<link>http://www.iam.unibe.ch/~akuhn/blog/2009/one-letter-method-names/</link>
		<comments>http://www.iam.unibe.ch/~akuhn/blog/2009/one-letter-method-names/#comments</comments>
		<pubDate>Fri, 20 Nov 2009 19:14:51 +0000</pubDate>
		<dc:creator>akuhn</dc:creator>
		
		<category><![CDATA[Smalltalk]]></category>

		<category><![CDATA[Spartan programming]]></category>

		<guid isPermaLink="false">http://www.iam.unibe.ch/~akuhn/blog/?p=381</guid>
		<description><![CDATA[Sometime short one-letter names are to be preferred as method names.
Don’t get me wrong. Naming conventions are one of the most important achievements of programming culture in the recent decade. No doubt, generalMatrixMultiplication is more readable than dgemm, but sometimes a simple p just beats the hell out of clumsy System.out.println and friends.
Akira Tanaka refers [...]]]></description>
			<content:encoded><![CDATA[<p>Sometime short one-letter names are to be preferred as method names.</p>
<p>Don’t get me wrong. Naming conventions are one of the most important achievements of programming culture in the recent decade. No doubt, <code>generalMatrixMultiplication</code> is more readable than <code>dgemm</code>, but sometimes a simple <code>p</code> just beats the hell out of clumsy <code>System.out.println</code> and friends.</p>
<p>Akira Tanaka refers to this as the “Huffman coding” of API design.</p>
<blockquote><p>The library design also utilize the usage frequency. For<br />
example, Ruby deﬁnes <code>p</code> method which is usable anywhere.<br />
It prints arguments for debugging purpose which is easy to<br />
understand for programmers. The method name <code>p</code> is inconsistent<br />
with other methods because it is too short in the sense<br />
of Ruby naming convention. It is intentional because debug<br />
printings are very common. In general, too short names are<br />
incomprehensible and tends to conflict. But <code>p</code> has no such<br />
problem because almost all Ruby programmers knows it.</p>
<p>This kind of naming convention, assigning short names<br />
for features frequently used, are called “Huffman coding”<br />
which term is borrowed from data compression.</p></blockquote>
<p>He goes on to provide more example. In particular he proposes an API design life cycle, where method names start with full-length English terms and get shortened as they raise in popularity. There is two ways to shorten method names, either down to a single letter, or even more powerful, to pick an operator as its name.</p>
<p>I’ll gonna apply the same to Smalltalk now. For the full story of Ruby’s core API design, please refer to Akira Tanaka’s recent paper <a href="http://www.citeulike.org/article/6174874">“Language and Library API Design for Usability of Ruby”</a> from the <a href="http://ecs.victoria.ac.nz/Events/PLATEAU">PLATEAU workshop</a> at this year’s OOPSLA.</p>
<p>First we define <code>p</code> as follows</p>
<pre><code>Object &gt;&gt; p
    Transcript show: self; cr.
    ^self
</code></pre>
<p>the implementation is taken from <a href="http://www.cincomsmalltalk.com/userblogs/travis/blogView">Travis Griggs</a>’s <code>Out</code> package. Now we can insert a <code>p</code>rint statement wherever we need debug output.</p>
<p>Printing is not the pinnacle of debugging, so let’s do the same with breakpoints</p>
<pre><code>Object &gt;&gt; h
    self halt
</code></pre>
<p>If you are using Pharo, add <code>h</code> to the methods listed in <code>OBInheritanceFilter &gt;&gt; icon:forNode:</code> to make sure our new breakpoint command is marked with a red flag in the class browser.</p>
<p>Next let’s rename <code>OrderedCollection</code> to <code>List</code></p>
<pre><code>Smalltalk at: #List put: OrderedCollection.
</code></pre>
<p>And introduce the <code>&lt;&lt;</code> operator for addition</p>
<pre><code>OrderedCollection &gt;&gt; &lt;&lt; element
    self add: element.
    ^self
</code></pre>
<p>which allows us to write concise code such as</p>
<pre><code>List new &lt;&lt; 'Lorem' &lt;&lt; 'ipsum' &lt;&lt; 'dolor
</code></pre>
<p>Next is string concatenation. Such a basic feature that many languages include string interpolation at their very core. Alas, Smalltalk is a bit dated to that regard (at least unless Pharo includes Lukas’s awesome <a href="http://scg.unibe.ch/research/helvetia">Helvetia</a> one day) and we are left with <code>String &gt;&gt; #expandMacrosWithArguments:</code>, which shall be Huffman encoded to</p>
<pre><code>String &gt;&gt; e: argument
    ^self expandMacrosWith: argument
String &gt;&gt; e: first e: second
    ^self expandMacrosWith: first with: second
String &gt;&gt; e: first e: second e: third
    ^self expandMacrosWith: first with: second with: third
String &gt;&gt; e: first e: second e: third e: fourth
    ^self expandMacrosWith: first with: second with: third with: fourth
</code></pre>
<p>And welcome to <a href="http://www.squeaksource.com/phexample">Phexample</a>’s expectation failure message</p>
<pre><code>'Expected &lt;1p&gt; but got &lt;2p&gt; (using &lt;3s&gt;)' e: value e: expected e: symbol
</code></pre>
<p>And eventually, regular expressions. Again such a basic feature that most languages include regex literals at their very core, and again we have to wait for Lukas’s <a href="http://scg.unibe.ch/research/helvetia">Helvetia</a> until we get the same awesomeness in Pharo. Until then, let’s pirate Groovy&#8217;s <code>r</code> syntax</p>
<pre><code>String &gt;&gt; r
    ^self asRegex
String &gt;&gt; =~ regex
    ^self matchesRegex: regex
RmMatcher &gt;&gt; asRegex
    ^self
</code></pre>
<p>And, “Hup hup hup, barbatruc”</p>
<pre><code>| regex |
regex := 'a*wesome'r
'Regex are aaaaaaaaaawesome!' =~ regex
</code></pre>
<p>Well then</p>
<pre><code>Gofer new
    squeaksource: 'akuhn';
    addPackage: 'Akuhn-Huffman';
    load
</code></pre>
<p>Gofer it!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.iam.unibe.ch/~akuhn/blog/2009/one-letter-method-names/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Shoulda use this in Pharo</title>
		<link>http://www.iam.unibe.ch/~akuhn/blog/2009/shoulda-use-this-in-pharo/</link>
		<comments>http://www.iam.unibe.ch/~akuhn/blog/2009/shoulda-use-this-in-pharo/#comments</comments>
		<pubDate>Wed, 11 Nov 2009 14:22:33 +0000</pubDate>
		<dc:creator>akuhn</dc:creator>
		
		<category><![CDATA[JExample]]></category>

		<category><![CDATA[Smalltalk]]></category>

		<guid isPermaLink="false">http://www.iam.unibe.ch/~akuhn/blog/?p=340</guid>
		<description><![CDATA[Phexample is the new black in unit testing for Smalltalk. It extends SUnit with two features: test dependencies, and RSpec-like expectation matchers. Test dependencies are covered on Niko’s blog, who’s developing Phexample with me, as well as on the JExample website. I shall thus focus on expectation matchers here.
Expectation matchers let you set expectations on [...]]]></description>
			<content:encoded><![CDATA[<p>Phexample is the new black in unit testing for Smalltalk. It extends SUnit with two features: test dependencies, and <a href="http://rspec.rubyforge.org/rspec/1.2.9/classes/Spec/Expectations.html">RSpec-like expectation matchers</a>. Test dependencies <a href="http://smalltalkthoughts.blogspot.com/2009/11/phexample-because-examples-expand-on.html">are covered on Niko’s blog</a>, who’s developing Phexample with me, as well as on the <a href="http://scg.unibe.ch/research/jexample">JExample website</a>. I shall thus focus on expectation matchers here.</p>
<p>Expectation matchers let you set expectations on your object. Expectations are also useful if you just use plain old SUnit test cases. They throw the same test failure as SUnit’s assertion, but are more readable in the source code as well as throw more readable failures messages.</p>
<p>Let’s start with an example.</p>
<p>Get yourself <a href="http://pharo-project.org/pharo-download">the latest Pharo image</a> and</p>
<pre><code>Gofer it
    squeaksource: 'phexample';
    addPackage: 'Phexample;
    load
</code></pre>
<p>then open a workspace and evaluate</p>
<pre><code>stack := Stack new.
stack size should = 0.
</code></pre>
<p>this creates a new stack and asserts that its size should be zero. For the sake of the example, let’s evaluate a failing expectation</p>
<pre><code>stack push: 42.
stack top should = 4711.
</code></pre>
<p>which raises <code>TestFailure: expected 4711 but got 42 (using =)</code>.</p>
<p>There are expectation matchers for all basic comparisons: greater than, less than, et cetera. If you need to negate a comparison just write</p>
<pre><code>stack top should not = 4711.
</code></pre>
<p>There are special matchers to set expectations on boolean return values.</p>
<pre><code>stack isEmpty should be true.
</code></pre>
<p>alternatively you can write</p>
<pre><code>stack should be isEmpty.
</code></pre>
<p>which often reads like LOLCAT SPEAK, but works quite nice with selectors that do not include a verb such as</p>
<pre><code>42 should be even.
</code></pre>
<p><em>Note:</em> matching of boolean expectations is an open issue. We would love to allow you to write <code>stack should be empty</code>, which is not only be more readable but would also allow us to provide better failure messages since we know that you wanted to test <code>isEmpty</code>. However, we fear that breaking Pharo’s senders-of feature as well as rename and other refactorings might not be worth the added value in reabability.</p>
<p>We welcome your feedback on this issue. For example, <a href="http://twitter.com/onierstrasz">Oscar</a> suggested to use</p>
<pre><code>stack isEmpty wouldyaknow
</code></pre>
<p>however, we are not sure how serious this suggestion is to be taken :)</p>
<p>Back on topic.</p>
<p>If you expect some code to raise an error, just write</p>
<pre><code>stack := Stack new.
[ stack pop ] should signal: Error
</code></pre>
<p>and to check the error message</p>
<pre><code>[ stack pop ] should signal: Error withMessageText: 'this stack is empty'.
</code></pre>
<p>or even</p>
<pre><code>[ stack pop ] should signal: Error withMessageText: [ :m |
    m should beKindOf: String.
    m isEmpty should not be true.
    m should endWith: 'is empty' ]
</code></pre>
<p>which leads us to more matchers, such as</p>
<pre><code>stack should beKindOf: Collection.
</code></pre>
<p>which sets an expectation on the type of an object.</p>
<p><em>Note:</em> it seems sensible to add more expectations that match the dynamic type of objects, such as duck typing and responds-to. We plan on doing this, please let us know if you have a specific use case.</p>
<pre><code>string should startWith: prefix.
string should endWith: prefix.
string should matchRegex: regexString.
</code></pre>
<p>are some expectations that you can set on strings.</p>
<p>Certainly there are more common expectations on basic types such as strings and collections. Again, please let us know if you have a specific use case. One of the things we want to do with Phexample is to be driven by user needs rather than planning upfront which features you might need (and nevertheless always guessing wrong…)</p>
<p>A last one, suggest by <a href="http://twitter.com/renggli">Lukas</a>. If you expect some code to run within a given duration, just write</p>
<pre><code>[ ... ] should runWithin: 20 milliSeconds.
</code></pre>
<p>which aborts with a failure if the given code takes longer than 20 milliseconds to run.</p>
<p>You can find the full list of expectation matchers in the <code>expecting</code> protocols of the <code>PhexMatcher</code> class. All matchers are well covered with tests, thus for plenty examples of their use just refer to the <code>ForExampleMatcher</code> class (which, of course, sublcasses the <code>Phexample</code> class, thus all its test methods start with <code>should..</code>).<small>
<p>PS: current versions of Omnibrowser do not display a test icon for Phexample test methods. This bug <a href="http://code.google.com/p/pharo/issues/detail?id=1373">has been reported and a fix provided</a> and will thus soon be fixed in your Pharo.</p>
<p></small></p>
]]></content:encoded>
			<wfw:commentRss>http://www.iam.unibe.ch/~akuhn/blog/2009/shoulda-use-this-in-pharo/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>

