<?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>www.hans-eric.com &#187; opinion</title>
	<atom:link href="http://www.hans-eric.com/category/opinion/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.hans-eric.com</link>
	<description>Hans-Eric Grönlund on software development</description>
	<lastBuildDate>Thu, 29 Jul 2010 17:32:29 +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>Generics are Litter</title>
		<link>http://www.hans-eric.com/2010/07/28/generics-are-litter/</link>
		<comments>http://www.hans-eric.com/2010/07/28/generics-are-litter/#comments</comments>
		<pubDate>Wed, 28 Jul 2010 17:52:20 +0000</pubDate>
		<dc:creator>Hans-Eric</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[opinion]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[constructed types]]></category>
		<category><![CDATA[generics]]></category>

		<guid isPermaLink="false">http://www.hans-eric.com/?p=411</guid>
		<description><![CDATA[The short version of this post:
Do not spread generic types around. They are ugly and primitive.
Allow me to elaborate.
Generics are great
Before we got Generics (2004 in Java, 2005 in C#, and 2009 in Delphi) the way to enforce type safety on a collection type was to encapsulate it and use delegation.

class OrderList
{
  private ArrayList items = new [...]]]></description>
			<content:encoded><![CDATA[<p>The short version of this post:</p>
<p><em>Do not spread generic types around. They are ugly and primitive.</em></p>
<p>Allow me to elaborate.</p>
<h3>Generics are great</h3>
<p>Before we got <a title="Wikipedia: Generic Programming" href="http://en.wikipedia.org/wiki/Generic_programming">Generics</a> (2004 in Java, 2005 in C#, and 2009 in Delphi) the way to enforce type safety on a collection type was to encapsulate it and use delegation.</p>
<pre class="brush: csharp;">
class OrderList
{
  private ArrayList items = new ArrayList();

  public void Add(OrderItem item)
  {
    items.Add(item);
  }

  // Plus lots of more delegation code
  // to implement Remove, foreach, etc.
}
</pre>
<p>Nowadays, we can construct our own type safe collection types with a single line of code.</p>
<pre class="brush: csharp;">
List&lt;OrderItem&gt; orders = new List&lt;OrderItem&gt;();
</pre>
<p>That alone is good reason to love generics, and there lies the problem; many developers have come to love their generics a little too much.</p>
<h3>Generics are ugly</h3>
<p>The expressiveness of generics comes at a price, the price of syntactic noise. That&#8217;s natural. We must specify the parameterized types somehow, and the current syntax for doing so is probably as good as anything else.</p>
<p>Still, my feeling when I look at code with generics is that the constructed types don’t harmonize with the rest of the language. They kind of stand out, and are slightly negative for code readability.</p>
<pre class="brush: csharp;">
OrderList orders = new OrderList();
// as compared to
List&lt;OrderItem&gt; orders = new List&lt;OrderItem&gt;();
</pre>
<p>This might not be so bad, but when we start to pass the constructed types around they become more and more like litter.</p>
<pre class="brush: csharp;">
List&lt;OrderItem&gt; FetchOrders()
{
  //…
}

double CalculateTotalSum(List&lt;OrderItem&gt; orders)
{
  //…
}

void PrintOrders(List&lt;OrderItem&gt; orders)
{
  //…
}
</pre>
<p>Besides being noisy, the constructed types expose implementation decisions. In our case the list of orders is implemented as a straight list. What if we found out that using a hash table implementation for performance reasons <a href="http://softscenario.blogspot.com/2009/05/performance-testing-of-dictionary-list.html">would be better?</a> Then we’d have to change the declaration in all those places.</p>
<pre class="brush: csharp;">
Dictionary&lt;OrderItem, OrderItem&gt; FetchOrders()
{
  //…
}

double CalculateTotalSum(Dictionary&lt;OrderItem, OrderItem&gt; orders)
{
  //…
}

void PrintOrders(Dictionary&lt;OrderItem, OrderItem&gt; orders)
{
  //…
}
</pre>
<p>Comments redundant.</p>
<h3>Generics are primitive</h3>
<p>A related problem is that the constructed generic types encourage design that is more procedural than object-oriented. As an example, consider the CalculateTotalSum method again.</p>
<pre class="brush: csharp;">
double CalculateTotalSum(List&lt;OrderItem&gt; orders)
{
  //…
}
</pre>
<p>Clearly, this method belongs in the <em>List&lt;OrderItem&gt;</em> type. Ideally, we should be able to invoke it using the dot operator.</p>
<pre class="brush: csharp;">
orders.TotalSum();
// instead of
CalculateTotalSum(orders);
</pre>
<p>But we cannot make that refactoring. We cannot add a TotalSum method to the <em>List&lt;OrderItem&gt;</em> type. (Well maybe we can if we make it an <a href="http://en.wikipedia.org/wiki/Extension_method">extension method</a>, but I wouldn’t go there.) In that sense, constructed generic types are primitive types, closed and out of our control.</p>
<h3>So we should hide them</h3>
<p>Don’t get me wrong. I use generics a lot. But for the previously given reasons I do my best to hide them. I do that using the same encapsulation technique as before, or – at the very least – by inheriting the constructed types.</p>
<pre class="brush: csharp;">
class OrderList : List&lt;OrderItem&gt;
{
  double TotalSum()
  {
    //…
  }
}
</pre>
<p>So, the rule I go by to mitigate the downsides of generics, is this:</p>
<p><strong>Constructed types should always stay encapsulated. Never let them leak through any abstraction layers, be it methods, interfaces or classes.</strong></p>
<p>That is my view on Generics. What is yours?</p>
<p>Cheers!</p>
<p>P.S.</p>
<p>Just to be clear, the beef I have with Generics is with <a href="http://en.csharp-online.net/ECMA-334:_25.5_Constructed_types">constructed types</a> alone. I have nothing against using open generic types in public interfaces, although that is more likely to be a tool of library and framework developers.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hans-eric.com/2010/07/28/generics-are-litter/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>The Boy Scout Rule</title>
		<link>http://www.hans-eric.com/2010/07/26/the-boy-scout-rule/</link>
		<comments>http://www.hans-eric.com/2010/07/26/the-boy-scout-rule/#comments</comments>
		<pubDate>Mon, 26 Jul 2010 15:27:57 +0000</pubDate>
		<dc:creator>Hans-Eric</dc:creator>
				<category><![CDATA[opinion]]></category>
		<category><![CDATA[project management]]></category>
		<category><![CDATA[software development]]></category>

		<guid isPermaLink="false">http://www.hans-eric.com/?p=405</guid>
		<description><![CDATA[You may have heard of The Boy Scout Rule. (I hadn’t until I watched a recorded presentation by “Uncle Bob”.)
You should always leave the camp ground cleaner than you found it.
Applied to programming, it means we should have the ambition of always leaving the code cleaner than we found it. Sounds great, but before we [...]]]></description>
			<content:encoded><![CDATA[<p>You may have heard of The Boy Scout Rule. (I hadn’t until I watched <a title="InfoQ: Robert C. Martin on Bad Code" href="http://www.infoq.com/presentations/Robert-C.-Martin-Bad-Code">a recorded presentation by “Uncle Bob”</a>.)</p>
<blockquote><p>You should always leave the camp ground cleaner than you found it.</p></blockquote>
<p>Applied to programming, it means we should have the ambition of always leaving the code cleaner than we found it. Sounds great, but before we set ourselves to the mission we might benefit from asking a couple of questions.</p>
<p>1. What is clean code?<br />
2. When and what should we clean?</p>
<h3>Clean Code</h3>
<p>What is clean code? <a title="Definition: Clean Code" href="http://en.wiktionary.org/wiki/clean_code">Wictionary defines it</a> like so:</p>
<blockquote><p>software code that is formatted correctly and in an organized manner so that another coder can easily read or modify it</p></blockquote>
<p>That, by necessity, is a rather vague definition. The goal of being readable and modifiable to another programmer, although highly subjective, is pretty clear. But what is a correct format? What does an organised manner look like in code? Let’s see if we can make it a little more explicit.</p>
<h3>Code Readability</h3>
<p>The easiest way to mess up otherwise good code is to make it inconsistent. For me, it really doesn’t matter where we put brackets, if we use camelCase or PascalCase for variable names, spaces or tabs as indentations, etc. It’s when we mix the different styles that we end up with sloppy code.</p>
<p>Another way to make code difficult to take in is to make it compact. Just like any other type of text, code gets more readable if it contains some space.</p>
<p>Although the previous definition mentions nothing about it, good naming of methods, classes, variables, etc, is at the essence of readable code. Code with poorly named abstractions is not clean code.</p>
<h3>Organized for Reusability</h3>
<p>Formatting code is easy. Designing for readability, on the other hand, is harder. How do we organize the code so that it is easily read and modifiable?</p>
<p>One thing we know, is that long chunks of code is more difficult to read and harder to reuse. So, one goal should be to have small methods. But to what cost? For instance, should we refactor code like this?</p>
<pre class="brush: csharp;">
SomeInterface si = (SomeInterface)someObject;
doSomething(si);
</pre>
<p>Into this?</p>
<pre class="brush: csharp;">
doSomething((SomeInterface)someObject);
</pre>
<p>What about code like this?</p>
<pre class="brush: csharp;">
string someString;
if (a &gt;= b)
  someString = “a is bigger or equal to b”;
else
  someString = “b is bigger”;
</pre>
<p>Into this?</p>
<pre class="brush: csharp;">
string someString = a &gt;= b ? “a is bigger or equal to b” : “b is bigger”;
</pre>
<p>In my opinion, the readability gains of the above refactorings are questionable. Better than reducing the number of rows in more or less clever ways, is to focus on improving abstractions.</p>
<h3>Extract &#8217;til you drop</h3>
<p>Abstractions are things with names, like methods or classes. You use them to separate the whats from the hows. They are your best weapons in the fight for readability, reusability and flexibility.</p>
<p>A good way to improve abstractions in existing code is to extract methods from big methods, and classes from bulky classes. You can do this until there is nothing more to extract. As Robert C. Martin puts it, extract until you drop.</p>
<p>That leads me to my own definition of clean code.</p>
<p>• It is readable.<br />
• It is consistent.<br />
• It consists of fine grained, reusable abstractions with helpful names.</p>
<h3>When to clean</h3>
<p>Changing code is always associated with risk and “cleaning” is no exception. You could:</p>
<p>• Introduce bugs<br />
• Cause build breaks<br />
• Create merge conflicts</p>
<p>So, there are good reasons not to be carried away. A great enabling factor is how well your code is covered by automatic tests. Higher code coverage enables more brutal cleaning. A team with no automatic testing should be more careful, though, about what kind of cleaning they should do.</p>
<p>Also, to avoid annoying your fellow programmers it’s best to avoid sweeping changes that may result in check-in conflicts for others. Restrict your cleaning to the camp ground, the part of the code that you’re currently working on. Don’t venture out on forest-wide cleaning missions.</p>
<p>If the team does not share common coding rules, there&#8217;s a risk that you end up in &#8220;Curly Brace Wars&#8221;, or other <a title="On Religious Wars in Software" href="http://haacked.com/archive/2006/02/08/OnReligiousWarsinSoftware.aspx">religious software wars</a> driven by team members&#8217; individual preferences. This leads to inconsistency, annoyance and loss of energy. The only way to avoid it is to agree upon a common set of code rules.</p>
<p>With all that said, I have never imposed “cleaning” restrictions on my teams. They are allowed to do whatever refactorings they find necessary. If they are actively “cleaning” the code it means they care about quality, and that’s the way I like it. In the rare cases excessive cleaning cause problems, most teams will handle it and change their processes accordingly.</p>
<p>Cheers!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hans-eric.com/2010/07/26/the-boy-scout-rule/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>The King is Challenged &#8211; By the Uncle</title>
		<link>http://www.hans-eric.com/2010/04/09/the-king-is-challenged-by-the-uncle/</link>
		<comments>http://www.hans-eric.com/2010/04/09/the-king-is-challenged-by-the-uncle/#comments</comments>
		<pubDate>Fri, 09 Apr 2010 12:51:44 +0000</pubDate>
		<dc:creator>Hans-Eric</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[opinion]]></category>

		<guid isPermaLink="false">http://www.hans-eric.com/?p=298</guid>
		<description><![CDATA[According to Tiobe Programming Community Index as of April 2010, Java is no longer the most popular programming language. C is; Not due to a sudden increase in popularity of C, but rather a cause of Java&#8217;s ongoing decline.
After more than 4 years C is back at position number 1 in the TIOBE index. The [...]]]></description>
			<content:encoded><![CDATA[<p>According to <a href="http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html">Tiobe Programming Community Index</a> as of April 2010, Java is no longer the most popular programming language. C is; Not due to a sudden increase in popularity of C, but rather a cause of Java&#8217;s ongoing decline.</p>
<blockquote><p>After more than 4 years C is back at position number 1 in the TIOBE index. The scores for C have been pretty constant through the years, varying between the 15% and 20% market share for almost 10 years. So the main reason for C&#8217;s number 1 position is not C&#8217;s uprise, but the decline of its competitor Java. Java has a long-term downward trend. It is losing ground to other languages running on the JVM. An example of such a language is JavaFX script that is now approaching the top 20.</p></blockquote>
<p>It&#8217;s important to point out, thought, that only the language part of Java is losing ground. As Tiobe Software indicates in their comment, the JVM is as hot as ever with all kinds of <a title="The Scala Programming Language" href="http://www.scala-lang.org/">cool</a> <a title="Clojure" href="http://clojure.org/">language</a> <a title="JRuby" href="http://jruby.org/">evolution</a> <a title="JavaFX" href="http://javafx.com/">occurring</a>.</p>
<p>Another interesting note to make about the april index is that Delphi is once again among the top ten. I&#8217;m really happy about that, although it means <a href="http://www.hans-eric.com/2007/09/02/rest-in-peace-delphi/">my old prophecy of a hasty decline</a> kind of puts me in the corner (although <a title="Welcome Back Delphi" href="http://www.hans-eric.com/2009/02/09/welcome-back-delphi/">I&#8217;ve already taken it back</a>).</p>
<p>A third point is the giant leap of Objective-C, from 42:nd to 11:th most popular language. This is a combination of iPhone&#8217;s popularity and the fact that Objective-C is <a title="iPhone PL lockdown" href="http://lambda-the-ultimate.org/node/3905">the only OO alternative allowed on that platform</a>, besides C++.</p>
<p><a href="http://www.hans-eric.com/wp-content/uploads/2010/04/tiobe-1004.png"><img class="alignnone size-medium wp-image-301" title="Tiobe Programming Language Community Index - april 2010" src="http://www.hans-eric.com/wp-content/uploads/2010/04/tiobe-1004-300x300.png" alt="The Tiobe Programming Language Community Index chart of april 2010" width="300" height="300" /></a></p>
<p>Cheers!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hans-eric.com/2010/04/09/the-king-is-challenged-by-the-uncle/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Method Reference Events? Nah, Not Yet.</title>
		<link>http://www.hans-eric.com/2009/06/05/method-reference-events-nah-not-yet/</link>
		<comments>http://www.hans-eric.com/2009/06/05/method-reference-events-nah-not-yet/#comments</comments>
		<pubDate>Fri, 05 Jun 2009 11:59:41 +0000</pubDate>
		<dc:creator>Hans-Eric</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[opinion]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.hans-eric.com/?p=150</guid>
		<description><![CDATA[In my previous post I discussed the problem that method pointers aren’t able to store references to anonymous methods. Unfortunately that limitation makes anonymous methods less useful since they can’t be used to set up event handlers on the fly, like so:

// Wouldn't it be great
// if we could do something
// like this?

Memo1.OnKeyPress :=
  [...]]]></description>
			<content:encoded><![CDATA[<p>In <a title="CodeGear, Please Fix the Anonymous Method Asymmetry" href="http://www.hans-eric.com/2009/06/03/codegear-please-fix-the-anonymous-method-assymetry/">my previous post</a> I discussed the problem that method pointers aren’t able to store references to anonymous methods. Unfortunately that limitation makes anonymous methods less useful since they can’t be used to set up event handlers on the fly, like so:</p>
<pre class="brush: delphi;">
// Wouldn't it be great
// if we could do something
// like this?

Memo1.OnKeyPress :=
  procedure(Sender: TObject; var Key: Char)
  begin
    Key := Chr(Ord(Key) + 1);
  end;
</pre>
<p>One thing I wasn’t aware of when I wrote that previous post is that while method pointers can’t be used to store anonymous methods, the opposite is true: Method references can indeed store both anonymous methods and instance methods. Many thanks to <a href="http://barrkel.blogspot.com/">Barry Kelly</a> who pointed it out to me in <a href="http://www.hans-eric.com/2009/06/03/codegear-please-fix-the-anonymous-method-assymetry/#comment-32280">a comment</a>.</p>
<p>Could this be the way to go? Shall we all start using method references instead of method pointers when we declare the events of our components from now on? Let’s take a look shall we? But just so that we’re clear with what we mean – there are many ways to say the same thing &#8211; here are the definitions I’m using in this post.</p>
<p>First of all, when I say method I mean either a function or a procedure, and it can be any of the types below. This is different from <a title="Wikipedia: Definition of Method" href="http://en.wikipedia.org/wiki/Method_(computer_science)">the common definition</a> stating that methods are subroutines associated with either a class or an object.</p>
<h3>Plain methods</h3>
<p>These are functions and procedures declared outside the context of a class.</p>
<pre class="brush: delphi;">
procedure PlainProcedure;
begin
  // Has no Self pointer
end;
</pre>
<h3>Instance methods</h3>
<p>Functions or procedures associated to an object instance</p>
<pre class="brush: delphi;">
Procedure TSomeClass.InstanceProcedure;
begin
  // Self is an instance of TSomeClass
end;
</pre>
<h3>Class methods</h3>
<p>Functions or procedures associated to a class. In other languages also called static methods.</p>
<pre class="brush: delphi;">
class procedure TSomeClass.ClassProcedure;
begin
  // Self is TSomeClass
end;
</pre>
<h3>Anonymous methods</h3>
<p>Functions or procedures declared as they are assigned in an execution context. These methods capture the surrounding context and may use local variables and arguments even if they’re out of execution scope.</p>
<pre class="brush: delphi;">
SomeItems.Sort(
  function(Item1, Item2: TSomeItem): Integer;
  begin
    if Item1.Value &amp;gt; Item2.Value then
      Result := 1
    else if Item1.Value &amp;lt; Item2.Value then
      Result :=  -1
    else
      Result := 0;
    end
  );
</pre>
<p>For these four types of methods there are <em>three reference types</em> to store pointers for later invocation of the methods.</p>
<h3>Plain method pointer</h3>
<pre class="brush: delphi;">
type TPlainMethodPointer =
  procedure(ASender: TObject);
</pre>
<h3>Method pointers</h3>
<pre class="brush: delphi;">
type TMethodPointer =
  procedure(ASender: TObject) of object;
</pre>
<h3>Method references</h3>
<pre class="brush: delphi;">
type TMethodReference =
  reference to procedure(ASender: TObject);
</pre>
<p>This compatibility graph shows what method types can be stored with the respective reference type.</p>
<table border="1">
<tbody>
<tr>
<th></th>
<th>Plain</th>
<th>Instance</th>
<th>Class</th>
<th>Anonymous</th>
</tr>
<tr>
<th>Plain method pointer</th>
<td>YES</td>
<td>no</td>
<td>no</td>
<td>no</td>
</tr>
<tr>
<th>Method pointer</th>
<td>no</td>
<td>YES</td>
<td>YES</td>
<td>no</td>
</tr>
<tr>
<th>Method reference</th>
<td>YES</td>
<td>YES</td>
<td>YES</td>
<td>YES</td>
</tr>
</tbody>
</table>
<p>From this graph we can see that the Method reference type is the unifying type that can store all types of method references. It seems like the way to go is to embrace Method references and render the other reference types obsolete. Is it possible? The answer is yes but no.</p>
<p>Take the event example of my last post. The VCL can not be changed to utilize Method pointers for backward compatibility reasons (like the widespread use of TMethod casts) so there’s nothing to do about it there. But what about our own components, and components created from now on?</p>
<pre class="brush: delphi;">
type
  TNotifyMethod = reference to procedure(Sender: TObject);

  TMyComponent = class(TComponent)
    ...
  published
    property OnChange: TNotifyMethod read FOnChange write FOnChange;
  end;
</pre>
<p>Well, it works fine as long as you set up the event handlers (OnChange in the above example) dynamically, but the method reference type events do not play well with the Delphi 2009 IDE. The object inspector doesn’t recognize possible event handlers and won’t create one automatically I you double click the event property. If you try to force the assignment by giving the name of an existing event handler method explicitly, the IDE throws an ugly Invalid Property Error Dialog.</p>
<p><img class="alignnone size-medium wp-image-151" title="Invalid property error" src="http://www.hans-eric.com/wp-content/uploads/2009/06/error-300x145.png" alt="Invalid property error" width="300" height="145" /></p>
<p>As much as I’d like to be able to assign anonymous methods as event handlers to my components’, I’m not prepared to sacrifice the IDE integration. Hopefully CodeGear will fix this issue in future releases but until then anonymous methods will remain less useful than they could be.</p>
<p>Cheers!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hans-eric.com/2009/06/05/method-reference-events-nah-not-yet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CodeGear, Please Fix the Anonymous Method Assymetry</title>
		<link>http://www.hans-eric.com/2009/06/03/codegear-please-fix-the-anonymous-method-assymetry/</link>
		<comments>http://www.hans-eric.com/2009/06/03/codegear-please-fix-the-anonymous-method-assymetry/#comments</comments>
		<pubDate>Wed, 03 Jun 2009 20:25:08 +0000</pubDate>
		<dc:creator>Hans-Eric</dc:creator>
				<category><![CDATA[Delphi]]></category>
		<category><![CDATA[opinion]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[software development]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://www.hans-eric.com/?p=135</guid>
		<description><![CDATA[As I noted in my previous post, anonymous methods is a big new feature in Delphi 2009 for the Win32 platform. While “closures” is natural and much appreciated in other languages, most notably Ruby, the Delphi community is still a bit reluctant and hesitant. Segunda Feira put words on it in his post on the [...]]]></description>
			<content:encoded><![CDATA[<p>As I noted <a title="Welcome Back Delphi" href="http://www.hans-eric.com/2009/02/09/welcome-back-delphi/">in my previous post</a>, anonymous methods is a big new feature in Delphi 2009 for the Win32 platform. While “closures” is natural and much appreciated in other languages, most notably Ruby, the Delphi community is still a bit reluctant and hesitant. Segunda Feira put words on it in <a title="Anonymous methods - when should they be used?" href="http://delphidicas.blogspot.com/2008/08/anonymous-methods-when-should-they-be.html">his post on the subject</a>.</p>
<blockquote><p>I am still not convinced that this convenience is worth getting all that excited about &#8211; It has not enabled anything that was previously impossible, nor even especially difficult either to implement or to understand</p>
<p>[...]</p>
<p>anonymous methods should be used <em>only</em> when you absolutely have to, and so far I have not yet seen an example where anonymous methods are the only way to achieve anything</p></blockquote>
<p>I agree that more often than not a problem can be solved with equal elegance using a pure object orientated approach, but there are situations where anonymous methods may actually be the better alternative. One situation that comes to mind is the setting up of test fixtures.<br />
Say, for instance, that we want to test the event firing mechanism of a component. An easy way to set this up could be like the following.</p>
<pre class="brush: delphi;">
procedure TestSomeComponent.TestOnChange;
var
  SUT: TSomeComponent;
  OnChangeFired: Boolean;
begin
  OnChangeFired := False;
  // Set up the fixture
  SUT := CreateTheComponentToTest;
  SUT.OnChange :=
    procedure(ASender: TObject)
    begin
      OnChangeFired := True;
      CheckSame(SUT, ASender, 'The Sender event argument should be set');
    end;
  // Perform operation
  SUT.Text := 'Some text';
  // Check the result
  CheckTrue(OnChangeFired, 'Setting the Text property should fire the OnChange event');
end;
</pre>
<p>The above code checks that the component’s OnChange event is fired when the Text property is set, and that the component is set as the Sender reference to the event handler. Except for being more compact, the biggest advantage to using anonymous methods in this scenario is that we avoid <a href="http://xunitpatterns.com/Obscure%20Test.html">the obscure test smell</a> and that we don’t have to clutter our test class with an instance variable (like FOnChangeFired) to identify if the event was really fired or not.</p>
<p><strong>The only problem is: it doesn’t work</strong>. Why? Well, because the OnChange property is most likely of an instance method reference type (i.e. TNotifyEvent), meaning it doesn&#8217;t accept a references to an anonymous method even if it has the same signature.</p>
<pre class="brush: delphi;">
type TNotifyEvent = procedure(ASender: TObject) &lt;strong&gt;of object&lt;/strong&gt;;
</pre>
<p>For our code to compile we need to redeclare TNotifyEvent and remove the “of object” keywords and instead use the method reference type.</p>
<pre class="brush: delphi;">
type TNotifyEvent = &lt;strong&gt;reference to&lt;/strong&gt; procedure(ASender: TObject);
</pre>
<p>But of course, that’s not an option. It would mean that the traditional way of setting up an event handler (by using an instance method) would not work.</p>
<p>I see a definite problem with how the Delphi language explicitly forces you to distinguish between instance methods (and class methods for that matter) and anonymous method references, even though they share the same signature.<br />
This is most unfortunate since I feel that the situations where we’d like to support both kinds of event handlers are quite common. And with the current semantics we have to use code duplication in order to achieve that. Like the two Synchronize methods of the built in TThread class.</p>
<p>In Delphi 2009 an overloaded variant of the TThread.Synchronize method was introduced, one that make use of anonymous methods. Here are snippets from that code:</p>
<pre class="brush: delphi;">
type
  TThreadMethod = procedure of object;
  TThreadProcedure = reference to procedure;
...
  class TThread = class
    …
    procedure Synchronize(AMethod: TThreadMethod); overload;
    procedure Synchronize(AThreadProc: TThreadProcedure); overload;
    ...
  end;
</pre>
<p>The two methods have almost identical implementations. The only real difference is the type of the argument.</p>
<pre class="brush: delphi;">
procedure TThread.Synchronize(AMethod: TThreadMethod);
begin
  FSynchronize.FThread := Self;
  FSynchronize.FSynchronizeException := nil;
  FSynchronize.FMethod := AMethod;
  FSynchronize.FProcedure := nil;
  Synchronize(@FSynchronize);
end;

procedure TThread.Synchronize(AThreadProc: TThreadProcedure);
begin
  FSynchronize.FThread := Self;
  FSynchronize.FSynchronizeException := nil;
  FSynchronize.FMethod := nil;
  FSynchronize.FProcedure := AThreadProc;
  Synchronize(@FSynchronize);
end;
</pre>
<p>I may be overly sensitive, but code like that really disturbs me. Unfortunately it gets worse. If we follow the execution chain down into the Synchronize class method that is invoked by the two, we find this.</p>
<pre class="brush: delphi; highlight: [8,9,10,11];">
class procedure TThread.Synchronize(ASyncRec: PSynchronizeRecord; QueueEvent: Boolean = False);
var
  SyncProc: TSyncProc;
  SyncProcPtr: PSyncProc;
begin
  if GetCurrentThreadID = MainThreadID then
  begin
    if Assigned(ASyncRec.FMethod) then
      ASyncRec.FMethod()
    else if Assigned(ASyncRec.FProcedure) then
      ASyncRec.FProcedure();
    end else
      …
end;
</pre>
<p>It would be a lot nicer if the two reference types were joined under a common reference type. And I can’t see why it couldn’t be done. When I look at the “of object” keywords I get a feeling that <em>the language is leaking compiler implementation</em> through the language interface; information that is indifferent to the developer. What matters from a callers’ perspective is the method signature, not whether the method has a self pointer or not.</p>
<p>I hope CodeGear recognizes this problem and find a way to clean this assymetry from the language. Anonymous methods would be so much more useful if they do.</p>
<p>Cheers!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hans-eric.com/2009/06/03/codegear-please-fix-the-anonymous-method-assymetry/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Don&#8217;t touch my Alt Gr Button</title>
		<link>http://www.hans-eric.com/2008/10/07/dont-touch-my-alt-gr-button/</link>
		<comments>http://www.hans-eric.com/2008/10/07/dont-touch-my-alt-gr-button/#comments</comments>
		<pubDate>Tue, 07 Oct 2008 08:23:38 +0000</pubDate>
		<dc:creator>Hans-Eric</dc:creator>
				<category><![CDATA[opinion]]></category>

		<guid isPermaLink="false">http://www.hans-eric.com/?p=125</guid>
		<description><![CDATA[I just downloaded and installed the HTML-Kit editor to see if it can help me in the WordPress Theme development projects I just started. Until now I&#8217;ve been relying upon the built in editor of the admin interface, handy for small changes but not for building themes from scratch.
Anyway, HTML-Kit was supposedly an excellent HTML [...]]]></description>
			<content:encoded><![CDATA[<p>I just downloaded and installed the <a href="http://www.htmlkit.com/">HTML-Kit editor</a> to see if it can help me in the WordPress Theme development projects I just started. Until now I&#8217;ve been relying upon the built in editor of the admin interface, handy for small changes but not for building themes from scratch.</p>
<p>Anyway, HTML-Kit was supposedly an excellent HTML editor and at a first glance it seemed good enough. That was until I tried to hit the &#8221; (double quotation marks) key. Instead of inserting the expected character into the html document I was currently editing, HTML-Kit threw me a new MDI window containing a fresh HTML document. As if I&#8217;d pressed Ctrl-N(ew) or something.</p>
<p>What was going on? Well, it turned out that the default shortcuts of HTML-Kit was interfering with <a title="Tools of the Effective Developer: Touch Typing" href="http://www.hans-eric.com/2007/12/06/tools-of-the-effective-developer-touch-typing/">my custom keyboard layout</a>. (This has happened to me with other editors as well.) My layout takes advantage of the Alt Gr button to move common special characters, like the &#8221; character, from the top row to the base row, all for the sake of speed and ergonomy.</p>
<p>On my keyboard, to strike the &#8221; key I have to press Alt Gr + L, which is actually Alt Gr + N since I base my layout on Dvorak, and since pressing Alt Gr is the same as pressing Alt + Ctrl this combination was coming in the way of the built in Alt + Ctrl + N, which means New HTML document i HTML-Kit. (Do you follow?)</p>
<p><a href="http://www.hans-eric.com/wp-content/uploads/2008/10/my_dvorak.png"><img class="alignnone size-full wp-image-126" title="My custom keyboard layout" src="http://www.hans-eric.com/wp-content/uploads/2008/10/my_dvorak.png" alt="" width="500" height="170" /></a></p>
<p>The fact that HTML-Kit didn&#8217;t allow me to type a common HTML character made the editor seemingly useless. But, that happened to not be the case. HTML-Kit has a great feature that allows you to define your own shortcuts. So, I did just that: define a new Alt + Ctrl + N to just output my double-quote. (I had to do the same for right brackets, } )</p>
<p><a href="http://www.hans-eric.com/wp-content/uploads/2008/10/shortcuts.png"><img class="alignnone size-medium wp-image-127" title="HTML-Kit lets you customize shortcuts" src="http://www.hans-eric.com/wp-content/uploads/2008/10/shortcuts-300x244.png" alt="" width="300" height="244" /></a></p>
<p>I&#8217;d much prefer it if application creators wouldn&#8217;t define Alt + Ctrl shortcuts at all, for the reasons given above, but if they absolutely have to, HTML-Kit&#8217;s level of customizability is the next best thing.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hans-eric.com/2008/10/07/dont-touch-my-alt-gr-button/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Hacker or Developer?</title>
		<link>http://www.hans-eric.com/2008/07/29/123/</link>
		<comments>http://www.hans-eric.com/2008/07/29/123/#comments</comments>
		<pubDate>Tue, 29 Jul 2008 11:02:43 +0000</pubDate>
		<dc:creator>Hans-Eric</dc:creator>
				<category><![CDATA[opinion]]></category>
		<category><![CDATA[software development]]></category>
		<category><![CDATA[Definition]]></category>
		<category><![CDATA[Developer]]></category>
		<category><![CDATA[Hacker]]></category>
		<category><![CDATA[Programmer]]></category>

		<guid isPermaLink="false">http://www.hans-eric.com/?p=123</guid>
		<description><![CDATA[Jay Fields has a post up today where he makes a distinction between Developers and Hackers.
Time after time I see requirements gathered and presented in a way that is totally disconnected from the business problem that&#8217;s being addressed. There are two ways to handle the situation.

Write the best code you can.
Talk to the business.

Hackers generally [...]]]></description>
			<content:encoded><![CDATA[<p>Jay Fields has a post up today where he makes <a title="Developers needed; Hackers need not apply" href="http://blog.jayfields.com/2008/07/developers-needed-hackers-need-not.html">a distinction between Developers and Hackers</a>.</p>
<blockquote><p>Time after time I see requirements gathered and presented in a way that is totally disconnected from the business problem that&#8217;s being addressed. There are two ways to handle the situation.</p>
<ol>
<li>Write the best code you can.</li>
<li>Talk to the business.</li>
</ol>
<p>Hackers generally go for the first choice, which doesn&#8217;t guarantee failure. In fact, a good hacker can still deliver code quickly enough that the business will be happy. Often, he gets it right on the 2nd or 3rd try.</p>
<p>But, a developer can deliver what the business is looking for the first time. A(n often) quick conversation with the business ensures that the developer knows what to work on and how it will benefit the business. This dialog often leads to a superior solution implementation where the business gets what it wants and the developer is able to do it in the most efficient way (e.g. I don&#8217;t need a beautiful website, I need a command line application).</p></blockquote>
<p>It&#8217;s essentially <a title="Programmer or Developer?" href="http://www.hans-eric.com/2007/09/04/programmer-or-developer/">the same distinction I tried to make</a> a while ago, although I used the term Programmer instead of Hacker. Maybe if I&#8217;d used the term Hacker as well, I might have avoided some of the heat I took for those definitions <img src='http://www.hans-eric.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>Interestingly Jay too suggests &#8212; although he doesn&#8217;t say it outright &#8212; a definition where human interaction and <a title="Tools of the Effective Developer: Customev View" href="http://www.hans-eric.com/2007/09/27/tools-of-the-effective-developer-customer-view/">taking the Customer&#8217;s view</a> is what distinguishes a developer, rather than coding skills.</p>
<p>Cheers!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hans-eric.com/2008/07/29/123/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Alan Cooper: Open-Source is a Sign of Failure</title>
		<link>http://www.hans-eric.com/2008/04/28/alan-cooper-open-source-is-a-sign-of-failure/</link>
		<comments>http://www.hans-eric.com/2008/04/28/alan-cooper-open-source-is-a-sign-of-failure/#comments</comments>
		<pubDate>Mon, 28 Apr 2008 10:45:47 +0000</pubDate>
		<dc:creator>Hans-Eric</dc:creator>
				<category><![CDATA[opinion]]></category>

		<guid isPermaLink="false">http://www.hans-eric.com/2008/04/28/alan-cooper-open-source-is-a-sign-of-failure/</guid>
		<description><![CDATA[In the keynote where Alan Cooper proclaimed that Agile processes are bad for developing quality software, he made another provoking statement: that Open-Source is ultimately a symptom of management failure. His point is that with the right enthusiasm and commitment to your products, why would anyone go and work in an Open-Source project on their [...]]]></description>
			<content:encoded><![CDATA[<p>In the keynote where <a href="http://www.hans-eric.com/2008/03/28/is-agile-only-for-elites/" title="Is Agile Only For Elites?">Alan Cooper proclaimed</a> that Agile processes are bad for developing quality software, he made another provoking statement: that Open-Source is ultimately a symptom of management failure. His point is that with the right enthusiasm and commitment to <em>your</em> products, why would anyone go and work in an Open-Source project on their spare time?</p>
<p>Well, there are plenty of good reasons for doing Open-Source pro bono work; it&#8217;s a great way to get experience and widen perspectives for instance, but still, Alan has a point. Many of us are not as content as we could be with our regular work. Instead we&#8217;re seeking satisfaction elsewhere.</p>
<p>So, what should our employers do to get our full attention? Here&#8217;s my list.</p>
<ul>
<li><strong>Creative freedom</strong><br />
Give me a chance to contribute, to be innovative and creative. Let me spend a part of my time doing research and follow paths that interest and inspires me. Google is <a href="http://www.hans-eric.com/2007/09/19/the-google-example/" title="The Google Example">a great example</a> of a company that understands the importance of this.</li>
<li><strong>Personal Development</strong><br />
As <a href="http://www.xprogramming.com/Blog/Page.aspx?display=GoodEnough" title="Good Enough">Ron Jeffries has said</a>, &#8220;the river is moving, and if we don&#8217;t keep rowing, we are going to drift back downstream.&#8221; I think self improvement is a spice of life. If my company provides me with all the books I need (and want), and lets me attend courses and conferences of my choice, chances are I&#8217;ll stay with it for life.</li>
<li><strong>Ownership</strong><br />
People usually do a better job, are more careful and thorough, if they own the thing they&#8217;re working on. This is true for software as well. Make me a business partner and I&#8217;ll optimize my work according to your business goals.</li>
<li><strong>Appreciation</strong><br />
The human race seems to be immensely better at criticizing than at giving appreciation. Yet, this is what we all crave, and &#8211; it has a great impact on how we see our employers. A rewarding salary is one form of showing appreciation, but I also need the outspoken forms.</li>
<li><strong>Closures</strong><br />
No one can go on for ever without reaching a finish line. I want to work in a team that is long-term efficient and gets  to <em>get done</em> often. Help me divide and I&#8217;ll conquer for you.</li>
</ul>
<p>That was my list, what&#8217;s on yours?</p>
<p>Cheers!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hans-eric.com/2008/04/28/alan-cooper-open-source-is-a-sign-of-failure/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 0.571 seconds -->
