<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>The Sustainable Software Workshop</title>
	<atom:link href="http://sustainablesoftware.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://sustainablesoftware.wordpress.com</link>
	<description>On a quest for long-term quality in software development</description>
	<lastBuildDate>Thu, 07 Aug 2008 11:03:27 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='sustainablesoftware.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>The Sustainable Software Workshop</title>
		<link>http://sustainablesoftware.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://sustainablesoftware.wordpress.com/osd.xml" title="The Sustainable Software Workshop" />
	<atom:link rel='hub' href='http://sustainablesoftware.wordpress.com/?pushpress=hub'/>
		<item>
		<title>JaQu — Another Lightweight SQL Interface for Java</title>
		<link>http://sustainablesoftware.wordpress.com/2008/07/31/jaqu-another-lightweight-sql-interface-for-java/</link>
		<comments>http://sustainablesoftware.wordpress.com/2008/07/31/jaqu-another-lightweight-sql-interface-for-java/#comments</comments>
		<pubDate>Thu, 31 Jul 2008 18:28:19 +0000</pubDate>
		<dc:creator>Bernhard Glomann</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://sustainablesoftware.wordpress.com/?p=32</guid>
		<description><![CDATA[Following up on my earlier post, I would like to mention a new tool by the name of JaQu (Java Query) that Thomas Mueller announced in a comment to my repost on Javalobby. Meanwhile, it has been released as part of the H2 Database Engine and I&#8217;ve had a chance to try it. Even though [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sustainablesoftware.wordpress.com&amp;blog=2727654&amp;post=32&amp;subd=sustainablesoftware&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Following up on my <a href="http://sustainablesoftware.wordpress.com/2008/06/11/lightweight-sql-interfaces-for-java/" target="_blank">earlier post</a>, I would like to mention a new tool by the name of <a href="http://www.h2database.com/html/jaqu.html" target="_blank">JaQu</a> (Java Query) that Thomas Mueller announced in a <a href="http://java.dzone.com/articles/lightweight-sql-interfaces-jav#comment-3975" target="_blank">comment to my repost on Javalobby</a>. Meanwhile, it has been released as part of the <a href="http://www.h2database.com/" target="_blank">H2 Database Engine</a> and I&#8217;ve had a chance to try it.</p>
<p>Even though JaQu comes bundled with H2, it is not specific to that database. I have tested the following code example successfully with an <a href="http://db.apache.org/derby/" target="_blank">Apache Derby</a> database.</p>
<p><span id="more-32"></span>JaQu provides a <a href="http://www.martinfowler.com/bliki/FluentInterface.html" target="_blank">fluent interface</a> (or <a href="http://martinfowler.com/bliki/DomainSpecificLanguage.html" target="_blank">internal DSL</a>) for building SQL queries in Java. Before you start writing queries, you need to create a class for each table, with a public field for each column. This is how such a class looks for my <em>Robots</em> table:</p>
<p><pre class="brush: java;">

public class Robot implements Table {

    public Integer id;
    public String name;
    public Date dateOfBirth;

    @Override
    public void define() {
        tableName(&quot;Robots&quot;);
        primaryKey(id);
    }
}
</pre></p>
<p>Using this table class, my <a href="http://sustainablesoftware.wordpress.com/2008/06/11/lightweight-sql-interfaces-for-java/" target="_blank">example query</a> can be expressed as follows:</p>
<p><pre class="brush: java;">

public void printClassicRobots() {
    QuotedTimestamp dobThreshold =
        QuotedTimestamp.from(
                new GregorianCalendar(1980, 0, 1));
    Db db = Db.open(Database.URL, Database.USER,
            Database.PASSWORD);
    Robot r = new Robot();
    List&lt;Robot&gt; robots =
        db.from(r).
        where(r.dateOfBirth).smaller(dobThreshold).
        select();
    for (Robot robot : robots) {
        System.out.format(&quot;%08d: %s\n&quot;,
                robot.id, robot.name);
    }
}
</pre></p>
<p>In order to get the date inserted correctly into the query, I had to define the following class, which encloses the string representation of the time stamp in single quotes:</p>
<p><pre class="brush: java;">

public class QuotedTimestamp extends Timestamp {

    public static QuotedTimestamp from(
            Calendar calendar) {
        return new QuotedTimestamp(
                calendar.getTimeInMillis());
    }

    public QuotedTimestamp(long time) {
        super(time);
    }

    @Override
    public String toString() {
        return &quot;'&quot; + super.toString() + &quot;'&quot;;
    }
}
</pre></p>
<p>It is obviously still early days for JaQu, and I&#8217;m sure these kinds of issues will be resolved in the future, maybe by using <a href="http://java.sun.com/javase/6/docs/technotes/guides/jdbc/getstart/preparedstatement.html#1000039" target="_blank">prepared statements</a> internally rather than converting everything to pure SQL strings. I definitely like the powerful API provided by JaQu, which supports much more complex queries than the one shown above. Please take a look at <a href="http://code.google.com/p/h2database/source/browse/trunk/h2/src/test/org/h2/test/jaqu/SamplesTest.java" target="_blank">this page</a> for more code examples, including joins, grouping etc.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/sustainablesoftware.wordpress.com/32/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/sustainablesoftware.wordpress.com/32/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sustainablesoftware.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sustainablesoftware.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sustainablesoftware.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sustainablesoftware.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sustainablesoftware.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sustainablesoftware.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sustainablesoftware.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sustainablesoftware.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sustainablesoftware.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sustainablesoftware.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sustainablesoftware.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sustainablesoftware.wordpress.com/32/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sustainablesoftware.wordpress.com/32/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sustainablesoftware.wordpress.com/32/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sustainablesoftware.wordpress.com&amp;blog=2727654&amp;post=32&amp;subd=sustainablesoftware&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sustainablesoftware.wordpress.com/2008/07/31/jaqu-another-lightweight-sql-interface-for-java/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/86c8327133f577fd11d1ba632cfabf06?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Bernhard</media:title>
		</media:content>
	</item>
		<item>
		<title>Lightweight SQL Interfaces for Java</title>
		<link>http://sustainablesoftware.wordpress.com/2008/06/11/lightweight-sql-interfaces-for-java/</link>
		<comments>http://sustainablesoftware.wordpress.com/2008/06/11/lightweight-sql-interfaces-for-java/#comments</comments>
		<pubDate>Wed, 11 Jun 2008 11:51:14 +0000</pubDate>
		<dc:creator>Bernhard Glomann</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://sustainablesoftware.wordpress.com/?p=30</guid>
		<description><![CDATA[I previously blogged about the shortcomings of JDBC and its way of passing SQL statements as strings without any compile-time checking or type safety. The same also applies to other SQL-based database access libraries such as Microsoft&#8217;s ODBC, OLE DB and ADO.NET. None of these APIs provide proper integration of SQL with the host language. [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sustainablesoftware.wordpress.com&amp;blog=2727654&amp;post=30&amp;subd=sustainablesoftware&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I previously <a href="http://sustainablesoftware.wordpress.com/2008/02/10/lightweight-database-abstraction/" target="_blank">blogged</a> about the shortcomings of <a href="http://java.sun.com/docs/books/tutorial/jdbc/index.html" target="_blank">JDBC</a> and its way of passing SQL statements as strings without any compile-time checking or type safety. The same also applies to other SQL-based database access libraries such as Microsoft&#8217;s <a href="http://msdn.microsoft.com/en-us/library/ms710252(VS.85).aspx" target="_blank">ODBC</a>, <a href="http://msdn.microsoft.com/en-us/library/ms722784(VS.85).aspx" target="_blank">OLE DB</a> and <a href="http://msdn.microsoft.com/en-us/library/h43ks021(VS.71).aspx" target="_blank">ADO.NET</a>. None of these APIs provide proper integration of SQL with the host language. Of course you could argue that object-relational mapping (ORM) tools like <a href="http://www.hibernate.org/" target="_blank">Hibernate</a> have eliminated the need to work directly with SQL, but I found that there are still situations where you want to control database operations more explicitly.</p>
<p>Microsoft has addressed this issue quite elegantly with the introduction of <a href="http://msdn.microsoft.com/en-us/library/bb425822.aspx" target="_blank">LINQ to SQL</a> in the .NET Framework 3.5. Although there is nothing equivalent in Java, I recently came across some promising efforts to improve language integration by providing <a href="http://www.martinfowler.com/bliki/FluentInterface.html" target="_blank">fluent interfaces</a> or other lightweight wrappers around JDBC and SQL.</p>
<p><span id="more-30"></span></p>
<h3>Standard JDBC Example</h3>
<p>Before we dive into these newer approaches, consider the following example using traditional JDBC (which prints a list of robots that were “born” before 1980):</p>
<p><pre class="brush: java;">

public void printClassicRobots() {
    Calendar dobThreshold =
        new GregorianCalendar(1980, 0, 1);
    PreparedStatement statement = null;
    try {
        Connection connection = getConnection();
        statement = connection.prepareStatement(
                &quot;SELECT ID, Name&quot; +
                &quot; FROM Robots&quot; +
                &quot; WHERE DateOfBirth &lt; ?&quot;);
        statement.setDate(1, new Date(
                dobThreshold.getTimeInMillis()));

        ResultSet rs = statement.executeQuery();
        while (rs.next()) {
            System.out.format(&quot;%08d: %s\n&quot;,
                    rs.getInt(1),
                    rs.getString(2));
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        cleanup(statement);
    }
}
</pre></p>
<h3>JEQUEL</h3>
<p>The <a href="http://www.jequel.de/" target="_blank">JEQUEL</a> (Java Embedded QUEry Language) project by <a href="http://www.jexp.de/blog/archives/4-On-Jequel.html" target="_blank">Michael Hunger</a> provides an <a href="http://martinfowler.com/bliki/DomainSpecificLanguage.html" target="_blank">internal DSL</a> (domain specific language) for building SQL statements. Using JEQUEL, the above example can be rewritten as follows:</p>
<p><pre class="brush: java;">
public static class Robots extends BaseTable&lt;Robots&gt;{

    public final Field&lt;Integer&gt; id = integer();
    public final Field&lt;String&gt; name = string();
    public final Field&lt;Date&gt; dateOfBirth = date();

    {
        initFields();
    }
}

public void printClassicRobots() {
    Calendar dobThreshold =
        new GregorianCalendar(1980, 0, 1);
    Robots robots = new Robots();
    Sql query =
        Select(robots.id, robots.name)
        .from(robots)
        .where(robots.dateOfBirth.lt(named(&quot;dob&quot;)))
        .toSql();
    query.executeOn(getDataSource())
        .withParams(&quot;dob&quot;, dobThreshold)
        .handleValues(new ValueRowHandler() {
            public void handleValue(int id,
                    String name) {
                System.out.format(&quot;%08d: %s\n&quot;,
                        id, name);
            }
    });
}
</pre></p>
<p>After defining a query, it is executed on a <a href="http://java.sun.com/javase/6/docs/api/javax/sql/DataSource.html" target="_blank">DataSource</a>, and its result set is processed. One way (among others) of doing this is by providing a callback object with a <em>handleValue</em> method whose parameters correspond to the columns in the result set. Unfortunately you don&#8217;t find out until run time if the method signature doesn&#8217;t match the result set. Overall, I think JEQUEL looks like a very elegant solution, and I will be looking into it in more detail.</p>
<h3>Quaere</h3>
<p>The <a href="http://quaere.codehaus.org/" target="_blank">Quaere</a> project by <a href="http://andersnoras.com/blogs/anoras/archive/2007/09/11/introducing-quaere-language-integrated-queryies-for-java.aspx" target="_blank">Anders Norås</a> aims to provide query capabilities similar to <a href="http://msdn.microsoft.com/en-us/netframework/aa904594.aspx" target="_blank">LINQ</a> in Java. Just like LINQ itself, Quaere is not limited to database access, but provides a general DSL for querying various types of data structures and data sources. The current implementation supports in-memory arrays and collections, as well as <a href="http://java.sun.com/javaee/5/docs/tutorial/doc/bnbqa.html" target="_blank">JPA entities</a> (Java Persistence API). There is currently no support for SQL queries, so it doesn&#8217;t quite fit into the category of lightweight alternatives to ORM tools (since it requires one in the form of JPA). But it is certainly a project worth mentioning, and it should be possible to add support for SQL in the future.</p>
<h3>EoD SQL</h3>
<p>Early beta versions of JDK 6 contained an EoD (ease of development) feature as part of JDBC 4.0, <a href="http://binkley.blogspot.com/2006/04/nifty-jdbc-40.html" target="_blank">using annotations to define SQL statements</a>. This feature was later <a href="http://weblogs.java.net/blog/lancea/archive/2006/10/jdbc_eod_api_de.html" target="_blank">removed</a> from JDK 6, and so far it has not come back (it is not included in <a href="https://jdk7.dev.java.net/" target="_blank">JDK 7</a> as of build 28). However, the same API was <a href="http://lemnik.wordpress.com/2007/11/22/development-on-eod-sql-continues/" target="_blank">reimplemented</a> (with some additional features) in the <a href="https://eodsql.dev.java.net/" target="_blank">EoD SQL</a> project. Using this library, the above example can be rewritten as follows:</p>
<p><pre class="brush: java;">
public static class Robot {
    public int id;
    public String name;
}

public static interface RobotDAI extends BaseQuery {

    @Select(&quot;SELECT ID, Name FROM Robots &quot; +
            &quot;WHERE DateOfBirth &lt; ?{1}&quot;)
    public DataSet&lt;Robot&gt; getRobotsOlderThan(
            final Date date) throws SQLException;
}

public void printClassicRobots() {
    Calendar dobThreshold =
        new GregorianCalendar(1980, 0, 1);
    try {
        RobotDAI query = QueryTool.getQuery(
                getConnection(), RobotDAI.class);
        DataSet&lt;Robot&gt; robots =
            query.getRobotsOlderThan(
                    dobThreshold.getTime());
        for (Robot robot : robots) {
            System.out.format(&quot;%08d: %s\n&quot;,
                    robot.id, robot.name);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
</pre></p>
<p>SQL statements are specified in annotations on the methods of a data access interface (<em>RobotDAI</em> above). An object implementing this interface is automatically generated by the library, and calling the annotated methods on that object causes the corresponding SQL statements to be executed. The query results are returned conveniently as custom data objects rather than just a <a href="http://java.sun.com/javase/6/docs/api/java/sql/ResultSet.html" target="_blank">ResultSet</a>. Unfortunately, the SQL statements themselves still need to be specified as strings, without any compile-time checking or IDE support.</p>
<h3>FEST-SQL?</h3>
<p>In their <a href="http://www.infoq.com/articles/internal-dsls-java" target="_blank">article on InfoQ</a> about internal DSLs in Java, <a href="http://www.jroller.com/alexRuiz/" target="_blank">Alex Ruiz</a> (of <a href="http://fest.easytesting.org/" target="_blank">FEST</a> fame) and <a href="http://www.xpteam.com/jeff/" target="_blank">Jeff Bay</a> showed an example of a DSL for building SQL statements and hinted that this would be released as an open source project. I&#8217;m not sure what they will call it, maybe &#8220;FEST-SQL&#8221; (although its usefulness should not be limited to testing)? Anyway, it certainly seems like a promising project.</p>
<h3>Conclusion</h3>
<p>Summing up, there is considerable interest and ongoing efforts to provide improvements over traditional JDBC for those situations where a full-blown ORM solution may not be the right tool for the job. I would definitely like to see these efforts continue and gain wider adoption. Thanks to all involved for providing these innovative tools!</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/sustainablesoftware.wordpress.com/30/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/sustainablesoftware.wordpress.com/30/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sustainablesoftware.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sustainablesoftware.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sustainablesoftware.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sustainablesoftware.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sustainablesoftware.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sustainablesoftware.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sustainablesoftware.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sustainablesoftware.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sustainablesoftware.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sustainablesoftware.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sustainablesoftware.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sustainablesoftware.wordpress.com/30/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sustainablesoftware.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sustainablesoftware.wordpress.com/30/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sustainablesoftware.wordpress.com&amp;blog=2727654&amp;post=30&amp;subd=sustainablesoftware&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sustainablesoftware.wordpress.com/2008/06/11/lightweight-sql-interfaces-for-java/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/86c8327133f577fd11d1ba632cfabf06?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Bernhard</media:title>
		</media:content>
	</item>
		<item>
		<title>Learning Python</title>
		<link>http://sustainablesoftware.wordpress.com/2008/05/31/learning-python/</link>
		<comments>http://sustainablesoftware.wordpress.com/2008/05/31/learning-python/#comments</comments>
		<pubDate>Sat, 31 May 2008 05:07:00 +0000</pubDate>
		<dc:creator>Bernhard Glomann</dc:creator>
				<category><![CDATA[Python]]></category>

		<guid isPermaLink="false">http://sustainablesoftware.wordpress.com/?p=21</guid>
		<description><![CDATA[Like many other people, I decided to learn Python so that I could give Google App Engine a try (and I did not want to &#8220;cheat&#8221; by getting my Java code automatically translated to Python). In order to get a feel for the language, I wrote a simple Tic-tac-toe game. I thought this example might [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sustainablesoftware.wordpress.com&amp;blog=2727654&amp;post=21&amp;subd=sustainablesoftware&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Like <a href="http://cgriley.com/2008/04/google-app-engine-first-impressions.aspx" target="_blank">many</a> <a href="http://www.atomeo.com/2008/04/get-ready-for-google-apps-engine-learn.html" target="_blank">other</a> <a href="http://www.vijedi.net/wordpress/?p=125" target="_blank">people</a>, I decided to learn <a href="http://www.python.org/" target="_blank">Python</a> so that I could give <a href="http://code.google.com/appengine/" target="_blank">Google App Engine</a> a try (and I did not want to &#8220;cheat&#8221; by getting my Java code <a href="http://code.google.com/p/java2python/" target="_blank">automatically translated</a> to Python). In order to get a feel for the language, I wrote a simple <a href="http://en.wikipedia.org/wiki/Tic-tac-toe" target="_blank">Tic-tac-toe</a> game. I thought this example might be useful for others to get a quick overview of some of the highlights and peculiarities of Python, especially if you are more used to statically typed languages like I am. For a more detailed introduction, check out the official <a href="http://docs.python.org/tut/tut.html" target="_blank">Python Tutorial</a> or <a href="http://www.diveintopython.org/toc/index.html" target="_blank">Dive Into Python</a>.</p>
<h3>Defining a class</h3>
<p>Although Python is not specifically an object-oriented language, it does support OOP to a certain extent. So I created a couple of classes to represent the tic-tac-toe game. Let&#8217;s start with a <a href="http://docs.python.org/tut/node11.html" target="_blank">class</a> for the grid-shaped game board:</p>
<p><pre class="brush: python;">

class Board:
    def __init__(self, size, symbol1, symbol2):
        self.size = size
        self.symbol1 = symbol1
        self.symbol2 = symbol2
        self.grid=[size * [' '] for i in range(size)]
</pre></p>
<h4><span id="more-21"></span>Indentation</h4>
<p>One thing I had to get used to with Python is the significance of code formatting. While it&#8217;s common for scripting languages to attach meaning to line breaks, I have never come across a language where even the level of <a href="http://docs.python.org/ref/indentation.html" target="_blank">indentation</a> affects the semantics of the code. In the example above, the first line starts the definition of the <em>Board</em> class, and all subsequent lines with a higher indentation level are treated as part of the class definition. The second line defines the <em>__init__</em> method, which becomes part of the <em>Board </em>class since it is indented. The subsequent lines are even more indented, which means that they form the body of the <em>__init__</em> method.</p>
<h4>Methods</h4>
<p>Methods and functions are defined using the <a href="http://docs.python.org/tut/node6.html#SECTION006600000000000000000" target="_blank"><em>def</em> keyword</a>. The special name <em>__init__</em> identifies the constructor, which is called when an instance of the class is created. There is no special keyword to refer to the current instance within a method (like the keyword <em>this</em> in Java, C# and C++). Instead, the instance is passed to the method as its first parameter, which by convention is called <em>self</em>. Function parameters and variables are untyped and can be assigned values of any type at runtime. However, the above code was written with the intention that <em>size</em> is an integer specifying the width and height of the grid, while <em>symbol1</em> and <em>symbol2</em> should be single-character strings containing the symbols used by the two players. So for the standard tic-tac-toe game, these parameters would be set to <em>3</em>, <em>&#8216;O&#8217;</em> and <em>&#8216;X&#8217;</em>.</p>
<h3>Working with lists</h3>
<p>The last line in the code snippet above initializes a data structure to represent the grid for the tic-tac-toe game. It makes use of several Python features for working with <a href="http://docs.python.org/tut/node5.html#SECTION005140000000000000000" target="_blank">lists</a>. List literals are written as comma-separated values enclosed in square brackets. The expression <code><strong>[' ']</strong></code> creates a list that contains a space character as its only element. Lists can be multiplied with integers, so if <em>size</em> is 3, the expression <code><strong>size * [' ']</strong></code> is equivalent to <code><strong>[' ',' ',' ']</strong></code> (a list with 3 elements, each of which is a single space character). This gives us one row for our grid. The next step is to put several such rows into another list to represent the whole grid. This is done using a Python feature called <a href="http://docs.python.org/tut/node7.html#SECTION007140000000000000000" target="_blank">list comprehensions</a>:</p>
<blockquote><p><code><strong>[size * [' '] for i in range(size)]</strong></code></p></blockquote>
<p>Within the outer pair of brackets, the expression before the <em>for</em> keyword is evaluated once for each iteration defined by the <em>for</em> clause, and the results from all iterations are collected in a new list. The <a href="http://docs.python.org/tut/node6.html#SECTION006300000000000000000" target="_blank">range</a> function returns a list containing the numbers from 0 to <em>size </em>- 1, and the expression <code><strong>for i in range(size)</strong></code> defines an iteration over these numbers. So the above expression creates a list with <em>size</em> elements, each of which is another list containing <em>size</em> individual space characters.</p>
<h3>Object equality and ordering</h3>
<p>So far our game board contains an empty grid (filled with spaces). Before we add methods to manipulate the board, let&#8217;s define a class to represent a move that a player can make in the game. A move is defined by the row index and column index of the grid cell that the player fills with his or her symbol:</p>
<p><pre class="brush: python;">

class Move:
    def __init__(self, row, column):
        self.row = row
        self.column = column

    def __cmp__(self, other):
        if self.column == other.column:
            return self.row - other.row
        else:
            return self.column - other.column

</pre></p>
<p>In addition to a constructor identified by the special name <em>__init__</em>, this class contains another <a href="http://docs.python.org/ref/customization.html" target="_blank">special method</a> named <em>__cmp__</em>. This method is called whenever instances of this class need to be compared for ordering or equality. In Java terms, implementing this method is equivalent to overriding the <a href="http://java.sun.com/javase/6/docs/api/java/lang/Object.html#equals(java.lang.Object)" target="_blank">Object.equals </a>method and implementing the <a href="http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html#compareTo(T)" target="_blank">Comparable.compareTo</a> method in a consistent way. Just like the latter, this method should return a negative integer, zero, or a positive integer depending on whether the object should be considered less than, equal to, or greater than the other object, respectively. For classes that represent <a href="http://www.martinfowler.com/bliki/ValueObject.html" target="_blank">value objects</a>, it usually makes sense to implement this method, so that things like <a href="http://docs.python.org/tut/node7.html#SECTION007400000000000000000" target="_blank">set membership</a> work as expected.</p>
<p>The body of the <em>__cmp__</em> method above shows how the <a href="http://docs.python.org/tut/node6.html#SECTION006100000000000000000" target="_blank"><em>if</em> statement</a> looks in Python. Again, it is important to indent the statements in the <em>if</em> and <em>else</em> clauses properly.</p>
<h3>Working with class instances</h3>
<p>With the <em>Move </em>class defined as above, we can now add the following methods to the <em>Board </em>class:</p>
<p><pre class="brush: python;">

    def possibleMoves(self):
        moves = []
        for row in range(self.size):
            for column in range(self.size):
                if self.grid[row][column] == ' ':
                    moves.append(Move(row, column))
        return moves

    def applyMove(self, move, symbol):
        self.grid[move.row][move.column] = symbol

    def undoMove(self, move, symbol):
        self.grid[move.row][move.column] = ' '

</pre></p>
<p>The <em>possibleMoves </em>method returns a list of <em>Move</em> objects representing all the grid positions that are available for the next move. It iterates over all grid positions using two nested <a href="http://docs.python.org/tut/node6.html#SECTION006200000000000000000" target="_blank"><em>for</em> loops</a>, which work in a similar way to the enhanced <em>for</em> loop in Java and the <em>foreach</em> loop in C#.</p>
<p>A list element is accessed by writing its index in brackets. Since we represent our grid as a list of lists, the element at a specific row and column is accessed with the expression <code><strong>self.grid[row][column]</strong></code>, in the same way as elements of two-dimensional arrays are accessed in Java. If the element is empty (represented by a space character), a corresponding <em>Move</em> instance is created and appended to the list of possible moves. An instance of a class is created by simply writing the name of the class followed by the argument list for its constructor (like in Java and C#, but without the <em>new</em> keyword).</p>
<h4>Duck typing</h4>
<p>The <em>applyMove</em> method simply stores the given symbol in the grid cell identified by the given <em>Move</em> instance. Actually, since method parameters are untyped, there is nothing that defines that the <em>move</em> parameter must be an instance of the <em>Move</em> class. In fact, it doesn&#8217;t need to be. It could be any object that has members named <em>row</em> and <em>column</em> containing integer values. This is an example for the <a href="http://en.wikipedia.org/wiki/Duck_typing" target="_blank">duck typing</a> that Python supports.</p>
<h3>Generator expressions</h3>
<p>Now we have a game board that accepts moves from the players, but we still need a way to determine when the game is over and who the winner is. So let&#8217;s first add a method to the <em>Board</em> class to determine whether the given symbol occupies a complete row, column or diagonal and therefore wins the game:</p>
<p><pre class="brush: python;">

    def isWinner(self, symbol):
        # check for completely filled rows or columns
        n = self.size
        for i in range(n):
            if (n == self.grid[i].count(symbol)
            or n == sum(1 for j in range(n)
                        if self.grid[j][i]==symbol)):
                return True
        # check diagonals
        return (n == sum(1 for i in range(n)
                         if self.grid[i][i]==symbol)
        or n == sum(1 for i in range(n)
                    if self.grid[i][n-1-i]==symbol))
</pre></p>
<p>To determine whether row number <em>i</em> is filled with the given symbol, we use the expression <code><strong>self.grid[i]</strong></code> to get the list corresponding to this row and then call the <a href="http://docs.python.org/tut/node7.html#SECTION007100000000000000000" target="_blank">count method</a> to determine the number of elements in this list that are equal to the given symbol. Unfortunately we cannot use the same approach to check for complete columns, since each column&#8217;s elements are spread out across multiple lists. Of course we could just use a nested <em>for</em> loop to iterate over a column&#8217;s elements in these different lists. But I decided to make use of a nice Python feature called <a href="http://docs.python.org/tut/node11.html#SECTION00111100000000000000000" target="_blank">generator expressions</a> instead. These are similar to the list comprehensions mentioned above, but instead of creating a complete list of values produced by an expression, they produce the values incrementally as they are processed by the surrounding expression. The following generator expression produces a sequence in which the value 1 is repeated as many times as the symbol appears in column <em>i</em>:</p>
<blockquote><p><code>(1 for j in range(n) if self.grid[j][i]==symbol)</code></p></blockquote>
<p>Applying the <a href="http://docs.python.org/lib/built-in-funcs.html" target="_blank">built-in <em>sum</em> function</a> to this expression then yields the number of occurrences of the symbol in the column. Similar expressions are also used to check whether the diagonals are completely filled with the symbol.</p>
<h3>Invoking methods</h3>
<p>Finally, the last method in the <em>Board</em> class determines whether the game is over by checking if any of the two players has won or if no more move is possible because the board is filled completely:</p>
<p><pre class="brush: python;">
    def isGameOver(self):
        return (self.isWinner(self.symbol1)
                or self.isWinner(self.symbol2)
                or self.possibleMoves() == [])
</pre></p>
<p>Note how methods are invoked using dot notation, with the instance (in this case <em>self</em>) <em>before</em> the method name, even though in the method definition it appears as the first parameter <em>after</em> the method name. In general, a method defined as</p>
<blockquote><p><code><strong>def method(self, param1, param2, ...)</strong></code></p></blockquote>
<p>is invoked like this:</p>
<blockquote><p><code><strong>obj.method(arg1, arg2, ...)</strong></code></p></blockquote>
<h3>Inheritance</h3>
<p>The <em>Board</em> class is now complete in that it encapsulates the rules of the game and the effects that individual moves have on the state of the game. What we need now is something that determines what move to make in a given state. That&#8217;s the job of the players, so let&#8217;s define a class hierarchy of players reflecting different strategies for playing the game. Here is the <em>Player</em> class containing common functionality and the <em>RandomPlayer</em> class that determines its next move by randomly choosing one of the possible moves:</p>
<p><pre class="brush: python;">

import random

class Player:
    def __init__(self, symbol):
        self.symbol = symbol

    def __str__(self):
        return self.symbol

class RandomPlayer(Player):
    def nextMove(self, game):
        moves = game.board.possibleMoves()
        return moves[random.randrange(len(moves))]
</pre></p>
<p>The <em>Player</em> class keeps track of the player&#8217;s symbol (&#8216;O&#8217; or &#8216;X&#8217;). In a static language, this class would also contain an abstract declaration of the <em>nextMove</em> method, which must be implemented by subclasses and returns the player&#8217;s next move based on the given state of the game. But in Python with its dynamic typing, there is no need (or support) for abstract methods. We just need to remember to define such a method in every subclass, without being forced to do so by the compiler.</p>
<p>The <em>Player</em> class contains another special method named <em>__str__</em>. This method corresponds to the <em>toString</em> method in Java, or <em>ToString</em> in C#. It is called when a string representation of an object is needed, for example when using the <a href="http://docs.python.org/ref/print.html" target="_blank"><em>print</em> statement</a>.</p>
<p>The <em>RandomPlayer</em> class is <a href="http://docs.python.org/tut/node11.html#SECTION0011500000000000000000" target="_blank">derived</a> from the <em>Player</em> class. Unlike in Java, C# and C++, constructors in Python are inherited by derived classes. So even though the above definition of the <em>RandomPlayer</em> class contains no <em>__init__</em> method, an instance of <em>RandomPlayer</em> can be created using an expression like <code><strong>RandomPlayer('X')</strong></code>, which calls the <em>__init__</em> method defined in the <em>Player</em> class, causing the argument to the stored in the <em>symbol</em> member variable.</p>
<h3>Modules</h3>
<p>The <em>import</em> statement in the first line of the code snippet above loads the <em>random</em> module, a standard Python module providing pseudo-random number generator functions. <a href="http://docs.python.org/tut/node8.html" target="_blank">Modules</a> are basically Python source files. Unlike the <em>import</em> statement in Java (which only imports the <em>names</em> of classes so that they can be referred to by their simple names rather than their fully-qualified names), the <em>import</em> statement in Python actually loads and executes the code from the module (note: modules mostly contain class and function definitions, and executing them only creates and adds class/function objects to the symbol table, but does not execute the code inside the functions). Names from an imported module still need to be prefixed with the module name: in the last line of the code snippet above, <code><strong>random.randrange</strong></code> refers to the <em>randrange</em> function defined in the <em>random</em> module.</p>
<p>The <em>nextMove</em> method in the <em>RandomPlayer</em> class above expects as its parameter a game object, which should be an instance of the <em>Game</em> class:</p>
<p><pre class="brush: python;">
class Game:
    def __init__(self, size, player1, player2):
        self.board = Board(size, player1.symbol,
                           player2.symbol)
        self.active = player1
        self.other = player2
        self.winner = None
        self.observers = []

    def run(self):
        self.notifyObservers()
        while not self.board.isGameOver():
            self.applyMove(
                self.active.nextMove(self))

    def applyMove(self, move):
        self.board.applyMove(move,
                             self.active.symbol)
        if self.board.isWinner(self.active.symbol):
            self.winner = self.active
        self.active,self.other=self.other,self.active
        self.notifyObservers()

    def notifyObservers(self):
        for observer in self.observers:
            observer(self)

    def addObserver(self, observer):
        self.observers.append(observer)

    def removeObserver(self, observer):
        self.observers.remove(observer)
</pre></p>
<p>The <em>run</em> method contains the main loop of the game, which keeps asking the active player for the next move until the game is over. For each move, it calls the <em>applyMove</em> method, which applies the move to the board and keeps track of the winner and the active player. It uses a <a href="http://docs.python.org/tut/node5.html#SECTION005200000000000000000" target="_blank">multiple assignment</a> to swap the active player with the other player.</p>
<h3>Functions</h3>
<p>The <em>Game</em> class uses the <a href="http://www.netobjectivesrepository.com/TheObserverPattern" target="_blank">observer pattern</a> to notify interested parties about changes to the game state. The <em>observers</em> list contains function objects, which are invoked by the <em>notifyObservers</em> method whenever the game state changes. Observer function objects can be added and removed by calling the methods <em>addObserver</em> and <em>removeObserver</em>, respectively. Let&#8217;s define an observer function that displays the current board on the console:</p>
<p><pre class="brush: python;">

import string

def printBoard(game):
    n = game.board.size
    rowChars = string.digits[1:n+1]
    columnChars = string.ascii_lowercase[:n]
    print '   ' + '   '.join(columnChars)
    print ' ' + '-' * (n * 4 + 1)
    for i, row in enumerate(game.board.grid):
        print rowChars[i] + '|',
        print ' | '.join(row),
        print '|' + rowChars[i]
        print ' ' + '-' * (n * 4 + 1)
    print '   ' + '   '.join(columnChars)
    if game.board.isGameOver():
        print &quot;Game over!&quot;
        if game.winner is None:
            print &quot;No winner!&quot;
        else:
            print &quot;The winner is&quot;, game.winner
</pre></p>
<h3>Working with strings</h3>
<p>The <em>printBoard</em> function uses <a href="http://docs.python.org/tut/node5.html#SECTION005120000000000000000" target="_blank">string</a> operations and the <a href="http://docs.python.org/ref/print.html" target="_blank"><em>print</em> statement</a> to create a visual representation of the game board. Using <em>slice notation</em> and some predefined <a href="http://docs.python.org/lib/node39.html" target="_blank">string constants</a>, the expressions <code><strong>string.digits[1:n+1]</strong></code> and <code><strong>string.ascii_lowercase[:n]</strong></code> evaluate to the digits 1 to <em>n</em> and the first <em>n</em> letters in the alphabet, respectively. These characters are then used to identify the rows and columns of the board, as in <a href="http://en.wikipedia.org/wiki/Algebraic_chess_notation" target="_blank">algebraic chess notation</a>. The built-in <a href="http://docs.python.org/lib/string-methods.html" target="_blank"><em>join</em> method</a> is used to concatenate the elements of a row with the given separator. The <em>for</em> loop in the <em>printBoard</em> function makes use of the built-in <a href="http://docs.python.org/lib/built-in-funcs.html" target="_blank"><em>enumerate</em> function</a> which returns a <a href="http://docs.python.org/tut/node7.html#SECTION007300000000000000000" target="_blank">tuple</a> of index and value for each element in a sequence.</p>
<p>Here is a function that runs a game with the <em>printBoard</em> function as an observer, causing the current board to be printed to the console after every move:</p>
<p><pre class="brush: python;">

def runGame(game):
    game.addObserver(printBoard)
    game.run()
</pre></p>
<p>Now we can let two instances of <em>RandomPlayer</em> play against each other and follow their moves on the console:</p>
<p><pre class="brush: python;">

runGame(Game(3,RandomPlayer('O'),RandomPlayer('X')))

</pre></p>
<h3>Exceptions</h3>
<p>Watching the computer play against itself may get a bit boring, so let&#8217;s define another player class that lets the user choose the next move by typing the desired coordinates into the console:</p>
<p><pre class="brush: python;">
import string

class ConsolePlayer(Player):
    class InputError(Exception):
        def __init__(self, message):
            self.message = message

    def nextMove(self, game):
        while True:
            input = raw_input(&quot;Your move please, &quot; +
                      &quot;player &quot; + self.symbol + &quot;: &quot;)
            try:
                m = self.parseMove(input.strip(),
                                   game.board);
                if m in game.board.possibleMoves():
                    return m
                else:
                    print &quot;Position already taken!&quot;
            except self.InputError, e:
                print e.message

    def parseMove(self, input, board):
        if len(input) != 2:
            raise self.InputError(&quot;Please enter &quot; +
                    &quot;exactly two characters &quot; +
                    &quot;(without spaces)&quot;)
        n = board.size
        column = input[0].lower()
        columnChars = string.ascii_lowercase[:n]
        if column not in columnChars:
            raise self.InputError(&quot;First character&quot; +
                    &quot; must be one of these: &quot; +
                    columnChars)
        row = input[1]
        rowChars = ''.join(string.digits[1:n+1])
        if row not in rowChars:
            raise self.InputError(
                    &quot;Second character must be &quot; +
                    &quot;one of these: &quot; + rowChars)
        return Move(rowChars.index(row),
                    columnChars.index(column))
</pre></p>
<p>The <em>ConsolePlayer</em> class is declared as a subclass of the <em>Player</em> class defined earlier, and it contains a nested definition of another class, <em>InputError</em>, which is derived from the built-in <em>Exception</em> class. This exception is used internally by <em>ConsolePlayer</em> to handle errors in the user input.</p>
<p>Recall that the <em>Game</em> class calls a player&#8217;s <em>nextMove</em> method whenever it is that player&#8217;s turn. The <em>ConsolePlayer</em>&#8216;s implementation of the <em>nextMove</em> method uses the <a href="http://docs.python.org/lib/built-in-funcs.html" target="_blank">built-in function</a> <em>raw_input</em> to let the user enter the desired grid position. The <em>parseMove</em> method is then called to interpret the input. It uses string manipulation functions to map an input string like &#8220;b3&#8243; (letter for a column, digit for a row) to the corresponding column and row indices and returns an instance of the <em>Move</em> class. If the input string is not in the expected format, an <em>InputError</em> is raised. This exception is then caught in the <em>nextMove</em> method by the <em>try/</em><em>except</em> block surrounding the call to <em>parseMove</em>. So the exception handling in Python seems quite similar to Java, just the syntax is slightly different. And of course there is no such thing as <a href="http://www.ibm.com/developerworks/java/library/j-jtp05254.html" target="_blank">checked exceptions</a> in a dynamic language.</p>
<p>Now we can let the user play against the computer by using a <em>ConsolePlayer</em> instance and a <em>RandomPlayer </em>instance:</p>
<p><pre class="brush: python;">

runGame(Game(3,ConsolePlayer('O'),RandomPlayer('X')))

</pre></p>
<p>OK, I think this was enough Python for today. You can get the full source code for this example from my <a href="http://svn2.assembla.com/svn/sustainablesoftware/tags/SSW-TicTacToe/1.0.0/" target="_blank">Subversion repository</a> or download it as a <a href="http://www.assembla.com/file/sustainablesoftware/1_SSW-TicTacToe-1.0.0.zip" target="_blank">zip file</a>. It was developed using Eclipse with the <a href="http://pydev.sourceforge.net/" target="_blank">PyDev</a> plugin. Of course there are a lot of interesting features in Python that I didn&#8217;t mention or haven&#8217;t even discovered yet. I am going to continue exploring the Python language and the available libraries, especially Google App Engine. I am planning to turn the tic-tac-toe game into a web application using Google App Engine and blog about my experience, so please stay tuned.</p>
<h3>Bonus</h3>
<p>In case you still want to see more Python code, here is another automated player that makes a stronger opponent than the <em>RandomPlayer</em>. It uses a brute force approach to find the best possible move by recursively evaluating all paths through the game. <strong>Caution:</strong> While it takes only about <strong>1 second</strong> for this algorithm to find the best move on a 3&#215;3 board, it would take something in the order of <strong>1 year</strong> on a 4&#215;4 board, because the number of possible paths grows exponentially with the number of grid elements.</p>
<p><pre class="brush: python;">

class BruteForcePlayer(Player):
    def nextMove(self, game):
        bestMove = self.findBestMove(game.board,
                     self.symbol, game.other.symbol)
        return bestMove[0]

    def findBestMove(self, board, active, other):
        if (board.isGameOver()):
            if (board.isWinner(active)):
                return (None, 1)
            elif (board.isWinner(other)):
                return (None, 0)
            else:
                return (None, 0.5)
        else:
            bestMove = (None, -1)
            for move in board.possibleMoves():
                board.applyMove(move, active)
                score = 1 - self.findBestMove(board,
                                other, active)[1]
                board.undoMove(move, active)
                if score &gt; bestMove[1]:
                    bestMove = (move, score)
                if bestMove[1] == 1:
                    break
            return bestMove
</pre></p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/sustainablesoftware.wordpress.com/21/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/sustainablesoftware.wordpress.com/21/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sustainablesoftware.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sustainablesoftware.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sustainablesoftware.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sustainablesoftware.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sustainablesoftware.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sustainablesoftware.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sustainablesoftware.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sustainablesoftware.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sustainablesoftware.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sustainablesoftware.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sustainablesoftware.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sustainablesoftware.wordpress.com/21/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sustainablesoftware.wordpress.com/21/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sustainablesoftware.wordpress.com/21/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sustainablesoftware.wordpress.com&amp;blog=2727654&amp;post=21&amp;subd=sustainablesoftware&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sustainablesoftware.wordpress.com/2008/05/31/learning-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/86c8327133f577fd11d1ba632cfabf06?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Bernhard</media:title>
		</media:content>
	</item>
		<item>
		<title>Contracts in Java using iContract</title>
		<link>http://sustainablesoftware.wordpress.com/2008/04/13/contracts-in-java-using-icontract/</link>
		<comments>http://sustainablesoftware.wordpress.com/2008/04/13/contracts-in-java-using-icontract/#comments</comments>
		<pubDate>Mon, 14 Apr 2008 01:39:31 +0000</pubDate>
		<dc:creator>Bernhard Glomann</dc:creator>
				<category><![CDATA[Design by Contract]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://sustainablesoftware.wordpress.com/?p=9</guid>
		<description><![CDATA[When searching for design by contract tools for Java, the first one I came across was iContract. There is a good article at JavaWorld that describes how to use iContract, but unfortunately the link it contains for downloading iContract no longer works. Apparently iContract has been abandoned by its creators for a while, but it [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sustainablesoftware.wordpress.com&amp;blog=2727654&amp;post=9&amp;subd=sustainablesoftware&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>When searching for <a href="http://en.wikipedia.org/wiki/Design_by_contract" target="_blank">design by contract</a> tools for Java, the first one I came across was iContract. There is a good <a href="http://www.javaworld.com/javaworld/jw-02-2001/jw-0216-cooltools.html" target="_blank">article at JavaWorld</a> that describes how to use iContract, but unfortunately the link it contains for downloading iContract no longer works. Apparently iContract has been abandoned by its creators for a while, but it has been revived as <a href="http://jcontracts.sourceforge.net/" target="_blank">JContractS</a>. I have used JContractS to create my example below, but I am still referring to it as iContract since this name is well established, and JContractS seems to be functionally equivalent to the original iContract.</p>
<p>iContract uses the special <a href="http://java.sun.com/j2se/javadoc/" target="_blank">Javadoc</a> tags @pre and @post to specify a method&#8217;s preconditions and postconditions (see my <a href="http://sustainablesoftware.wordpress.com/2008/03/10/smart-objects-put-their-contracts-in-writing/" target="_blank">earlier post</a> for an introduction to these terms). There is also an @invariant tag that can be used on the class level to specify a common condition that must hold before and after any of the class&#8217;s methods are executed.</p>
<h3>Let&#8217;s See some Code</h3>
<p>The following example code is based on the swarm robotics example described in my <a href="http://sustainablesoftware.wordpress.com/2008/04/13/when-robots-go-to-law-school/" target="_blank">previous post</a>. iContract does not support the new language features of Java 5, so I adapted my example to Java 1.4 syntax. I am only going to include some code snippets here to show how to use iContract, but you can get the full source code for this example from my <a href="http://svn2.assembla.com/svn/sustainablesoftware/tags/SSW-iContract/1.0.0/">Subversion repository</a> or download it as a <a href="http://www.assembla.com/file/sustainablesoftware/1_SSW-iContract-1.0.0.zip" target="_blank">zip file</a>. All you need to run this example is JDK 1.4 (or higher) and <a href="http://ant.apache.org/" target="_blank">Ant</a>.</p>
<p><span id="more-9"></span></p>
<h4>Simple Conditions</h4>
<p>The <em>hasFeature</em> method in the <em>Robot</em> interface is used to check whether a robot has a specific feature. It expects its argument to be one of the predefined constants in the <em>FEATURES</em> array. Using the <a href="http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#binarySearch(int[],%20int)" target="_blank">Arrays.binarySearch</a> method (which returns a non-negative result if the value is found in the array), this precondition can be specified as follows:</p>
<p><pre class="brush: java;">

    /**
     * @pre java.util.Arrays.binarySearch(FEATURES,
     *      feature) &gt;= 0
     */
    public boolean hasFeature(int feature);

</pre></p>
<p>A <em>Robot</em> may be part of a <em>Swarm</em>, which is returned by the <em>getSwarm</em> method. The return value must be either null (if the robot does not belong to a swarm), or it must be a <em>Swarm</em> instance whose members (given by its <em>getRobots</em> method) include this robot. This postcondition can be specified as follows:</p>
<p><pre class="brush: java;">
    /**
     * @post return == null ||
     *       return.getRobots().contains(this)
     */
    public Swarm getSwarm();
</pre></p>
<h4>Implications</h4>
<p>The postcondition of the <em>getSwarm</em> method can be expressed in another way: <em>If</em> this method returns a non-null value, <em>then </em>it must be a swarm that includes this robot among its members. This kind of condition can be expressed in iContract using the <em>implies</em> operator. With this operator, the above condition could be rewritten as follows:</p>
<blockquote><p><code>return != null implies return.getRobots().contains(this)</code></p></blockquote>
<p>The <em>implies</em> operator is also used in the precondition of the <em>setSwarm</em> method. This precondition is supposed to prevent people from calling <em>setSwarm</em> directly when they want to add a robot to a swarm. Instead, they should call the <em>addRobot</em> method in the <em>Swarm</em> class, which adds the robot to its list of members and then calls <em>Robot.setSwarm</em>.</p>
<p><pre class="brush: java;">

    /**
     * @pre swarm != null implies
     *      swarm.getRobots().contains(this)
     * @post getSwarm() == swarm
     */
    public void setSwarm(Swarm swarm);

</pre></p>
<h4>Pre-State Values</h4>
<p>For methods that modify an object&#8217;s state, it often makes sense to specify the postcondition in terms of how the new state relates to the state before method execution (the pre-state). To express this kind of postcondition, iContract supports the @pre operator, which can be appended to an expression and represents the expression&#8217;s value before method execution. For example, after executing the <em>addRobot</em> method in the <em>Swarm</em> class, the swarm&#8217;s collection of members should contain the newly added robot, as well as all the robots it already contained <em>before</em> (but no others). Using the @pre operator to express these postconditions, the method would look like this:</p>
<p><pre class="brush: java;">

    /**
     * @pre robot.getSwarm() == null
     * @post getRobots().contains(robot)
     * @post getRobots().containsAll(getRobots()@pre)
     * @post getRobots().size() ==
     *       1 + getRobots().size()@pre
     */
    public void addRobot(Robot robot) {
        robots.add(robot);
        robot.setSwarm(this);
    }

</pre></p>
<h4>Quantifiers</h4>
<p>There are two ways to tell that a given <em>Robot</em> instance belongs to a given <em>Swarm</em> instance: the robot&#8217;s <em>getSwarm</em> method returns the swarm, and the robot is contained in the collection returned by the swarm&#8217;s <em>getRobots</em> method. To ensure that the two sides of this relationship are always consistent, we can define an  invariant for the <em>Swarm</em> class using the <em>forall</em> quantifier. This quantifier specifies a condition (after the vertical bar) that must be satisfied for <em>all</em> elements in a collection:</p>
<p><pre class="brush: java;">

/**
 * @invariant forall Robot r in getRobots() |
 *            r.getSwarm() == this
 */
public class Swarm {
    // ...
}

</pre></p>
<p>Besides the forall quantifier, iContract supports the <em>exists</em> quantifier, which only requires that <em>at least one</em> element of a collection satisfies the given condition. By nesting the <em>exists</em> quantifier <em>n</em> times, you can specify that at least <em>n</em> elements of a collection must satisfy the condition. This approach is used in the precondition for the <em>Robot</em>&#8216;s <em>getLocation</em> method, which specifies that in order to determine its location, a robot must either have a GPS device or be part of a swarm in which at least 3 other robots have GPS devices, from which it could triangulate its location:</p>
<p><pre class="brush: java;">

    /**
     * @pre !hasFeature(FEATURE_GPS) implies
     *      exists Robot a in getSwarm().enumRobots()|
     *      exists Robot b in getSwarm().enumRobots()|
     *      exists Robot c in getSwarm().enumRobots()|
     *      a != b &amp;&amp; a != c &amp;&amp; b != c &amp;&amp;
     *      a.hasFeature(FEATURE_GPS) &amp;&amp;
     *      b.hasFeature(FEATURE_GPS) &amp;&amp;
     *      c.hasFeature(FEATURE_GPS)
     * @post return != null
     */
    public Point2D getLocation();</pre></p>
<p>To make this work, I had to add the <em>enumRobots</em> method to the <em>Swarm</em> class, which returns the swarm&#8217;s robots as a <a href="http://java.sun.com/javase/6/docs/api/java/util/Enumeration.html" target="_blank">java.util.Enumeration</a>. For some reason, iContract wouldn&#8217;t accept this condition when using the <em>getRobots</em> method instead of <em>enumRobots</em>.</p>
<h4>Runtime Checking</h4>
<p>Let&#8217;s see what happens when a contract is violated at runtime, for example when we try to directly call <em>Robot.setSwarm</em> instead of going through <em>Swarm.addRobot</em>:</p>
<p><pre class="brush: java;">

    public static void main(String[] args) {
        Worker worker = new Worker();
        Swarm swarm = new Swarm();
        worker.setSwarm(swarm);
    }
</pre></p>
<p>Note: The <em>Worker</em> class implements the <em>Robot</em> interface. As you would expect (based on the <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" target="_blank">Liskov substitution principle</a>), iContract automatically applies the contracts defined in the <em>Robot</em> interface to the <em>Worker</em> class.</p>
<p>In order to enable runtime checking of the contracts, the source code needs to be instrumented with the iContract tool (see the <a href="http://trac2.assembla.com/sustainablesoftware/browser/tags/SSW-iContract/1.0.0/build.xml" target="_blank">build.xml</a> file for details on how it is invoked). This step results in a new set of source files with embedded code for checking the contracts. When compiling and running these instrumented source files, a RuntimeException is thrown at the beginning of the <em>setSwarm</em> method, indicating that its precondition was violated.</p>
<h4>Contract Documentation</h4>
<p>Contract specifications can be included in the Javadoc documentation by using <a href="http://icplus.sourceforge.net/iDoclet.html" target="_blank">iDoclet</a>. However, this only seems to work with JDK 1.3, not with any newer version.</p>
<h3>Discussion</h3>
<p>What I like about iContract is the declarative language with its logic operators, similar to <a href="http://en.wikipedia.org/wiki/Object_Constraint_Language" target="_blank">OCL</a>. This kind of language should be more suitable for static analysis techniques than other contract tools that are based on more general scripting languages. However, I&#8217;m not aware of any existing static analysis tools for iContract. There is also nothing to keep you from using arbitrary Java methods in your contract specifications, including methods with side effects.</p>
<p>There are some drawbacks inherent in iContract&#8217;s approach of embedding contract specifications in Javadoc comments. First of all, it means that any tool operating on contracts needs to have access to the source code. But contract specifications should really be included in the byte code of a class, since they are part of its public interface. In a perfect world, I would imagine that third-party jar files come with embedded contract specifications that could be seamlessly included in any sort of runtime or static contract checking that you apply to your project, along with the contracts in your own code.</p>
<p>Another problem with specifying contracts within comments is that you don&#8217;t get IDE support (such as code completion, syntax checking, refactoring) when writing contracts. Of course this problem could be addressed by special IDE plug-ins, but I&#8217;m not aware of any such plug-ins for iContract.</p>
<p>As mentioned above, runtime checking of contracts requires source code instrumentation as a preprocessing step before compilation. This means that, unlike with standard Java <a href="http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html" target="_blank">assertions</a>, contract checking cannot be enabled or disabled at runtime.</p>
<p>Unfortunately, iContract proved unsuitable for my professional work, mainly because it does not support Java 5 syntax and is no longer actively developed.</p>
<p>Overall, my impression of iContract is that it was an early implementation of design by contract for Java, making best use of what was available at the time. But from today&#8217;s perspective, iContract&#8217;s approach seems somewhat outdated, and I think that some of its limitations could be overcome by leveraging more recent developments, such as <a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html" target="_blank">annotations</a>, <a href="http://en.wikipedia.org/wiki/Aspect-oriented_programming" target="_blank">aspect-oriented programming</a>, the <a href="http://java.sun.com/javase/6/docs/technotes/guides/scripting/index.html" target="_blank">Java Scripting API</a> and <a href="http://java.sun.com/javase/6/docs/technotes/guides/instrumentation/" target="_blank">instrumentation support</a>. In fact, there are several newer tools based on these technologies, and I will be reviewing some of them in upcoming posts.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/sustainablesoftware.wordpress.com/9/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/sustainablesoftware.wordpress.com/9/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sustainablesoftware.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sustainablesoftware.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sustainablesoftware.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sustainablesoftware.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sustainablesoftware.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sustainablesoftware.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sustainablesoftware.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sustainablesoftware.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sustainablesoftware.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sustainablesoftware.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sustainablesoftware.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sustainablesoftware.wordpress.com/9/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sustainablesoftware.wordpress.com/9/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sustainablesoftware.wordpress.com/9/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sustainablesoftware.wordpress.com&amp;blog=2727654&amp;post=9&amp;subd=sustainablesoftware&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sustainablesoftware.wordpress.com/2008/04/13/contracts-in-java-using-icontract/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/86c8327133f577fd11d1ba632cfabf06?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Bernhard</media:title>
		</media:content>
	</item>
		<item>
		<title>When Robots Go to Law School&#8230;</title>
		<link>http://sustainablesoftware.wordpress.com/2008/04/13/when-robots-go-to-law-school/</link>
		<comments>http://sustainablesoftware.wordpress.com/2008/04/13/when-robots-go-to-law-school/#comments</comments>
		<pubDate>Mon, 14 Apr 2008 00:00:10 +0000</pubDate>
		<dc:creator>Bernhard Glomann</dc:creator>
				<category><![CDATA[Design by Contract]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://sustainablesoftware.wordpress.com/?p=10</guid>
		<description><![CDATA[&#8230;they learn how to write contracts! Well, I wanted to use something a little different from the typical customers and orders, so I came up with an example from the field of swarm robotics for my upcoming posts on design by contract tools. Disclaimer: This example is only for illustration and not meant to be [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sustainablesoftware.wordpress.com&amp;blog=2727654&amp;post=10&amp;subd=sustainablesoftware&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>&#8230;they learn how to write contracts! Well, I wanted to use something a little different from the typical customers and orders, so I came up with an example from the field of <a href="http://en.wikipedia.org/wiki/Swarm_robotics" target="_blank">swarm robotics</a> for my upcoming posts on <a href="http://sustainablesoftware.wordpress.com/2008/03/10/smart-objects-put-their-contracts-in-writing/" target="_blank">design by contract</a> tools.</p>
<p>Disclaimer: This example is only for illustration and not meant to be useful for any real robotics application.</p>
<p>The following UML class diagram (created with <a href="http://www.netbeans.org/" target="_blank">NetBeans</a>) shows a simple object model for robots and swarms. Each <em>Robot</em> may or may not belong to a <em>Swarm</em>, and a swarm can consist of any number of robots. The <em>AbstractRobot</em> class implements some common functionality defined by the <em>Robot</em> interface and serves as the base class for two concrete robot implementations: <em>Navigator</em> and <em>Worker</em>.<br />
<img class="alignnone size-full wp-image-20" src="http://sustainablesoftware.files.wordpress.com/2008/04/robots2.png?w=450" alt="Robots class diagram"   /></p>
<p>The <em>Navigator</em> is equipped with a <a href="http://en.wikipedia.org/wiki/Gps" target="_blank">GPS</a> system that enables it to determine its own location. The <em>Worker</em>&#8216;s unique feature is its robot arm that allows it to pick up and manipulate objects. So each of these specialized robots has only limited functionality, but when working together in a swarm they are much more powerful. For example, consider the task of picking up an object from a specific location and dropping it off somewhere else. Neither one of these two robot types could perform this task by itself, because the navigator cannot pick up objects, and the worker does not know how to get to the object&#8217;s location. But if they work together, the navigator can lead the way to the object, and the worker can then pick up the object.</p>
<p><span id="more-10"></span></p>
<p>Let&#8217;s take a look at the source code for the <em>Robot</em> interface.</p>
<p><pre class="brush: java;">
public interface Robot {

    public static final int FEATURE_GPS = 1;
    public static final int FEATURE_ARM = 2;

    public static final int[] FEATURES = new int[] {
        FEATURE_GPS, FEATURE_ARM
    };

    /**
     * Checks whether this robot has the given
     * feature.
     *
     * @param feature   must be one of the values in
     *                  {@link #FEATURES}
     */
    public boolean hasFeature(int feature);

    /**
     * Gets the swarm to which this robot belongs.
     *
     * @return must be either null or a swarm whose
     *         members (see {@link Swarm#getRobots()})
     *         include this robot
     */
    public Swarm getSwarm();

    /**
     * Sets the swarm to which this robot belongs.
     * This method should only be called from the
     * {@link Swarm} class.
     *
     * @param swarm if this is not null, its
     *              collection of members (see
     *              {@link Swarm#getRobots()})
     *              must already contain this robot
     */
    public void setSwarm(Swarm swarm);

    /**
     * Gets the robot's location. This method may only
     * be called if this robot either has a GPS device
     * (see {@link #FEATURE_GPS}) or belongs to a
     * swarm where at least 3 robots have GPS.
     *
     * @return  the robot's location (not null)
     */
    public Point2D getLocation();
}
</pre></p>
<p>The <em>getLocation</em> method deserves an explanation. If the robot is equipped with GPS, it can get its location easily. But even if it doesn’t have GPS, it might be able to determine its location with the help of other robots. It could measure the time it takes for a signal to travel between itself and another robot, and use this information to compute its distance from that robot. If there are at least 3 robots with GPS in the swarm, the robots without GPS can triangulate their positions by measuring their distances from these 3 robots. This is why the <em>getLocation</em> method requires that the robot either has GPS or belongs to a swarm where at least 3 robots have GPS.</p>
<p>The <em>Swarm</em> class is basically just a collection of robots. Here is the source code:</p>
<p><pre class="brush: java;">

/**
 * Swarm of {@link Robot}s.
 *
 * All member robots (see {@link #getRobots()}) must
 * &quot;know&quot; that they belong to this swarm (that is,
 * their {@link Robot#getSwarm()} method must return
 * this swarm).
 */
public class Swarm {

    private Collection&lt;Robot&gt; robots =
        new ArrayList&lt;Robot&gt;();

    /**
     * Gets the collection of robots that are members
     * of this swarm.
     *
     * @return  not null
     */
    public Collection&lt;Robot&gt; getRobots() {
        return new ArrayList&lt;Robot&gt;(robots);
    }

    /**
     * Adds the given robot to the swarm.
     *
     * @param   robot   the robot to add; must not
     *                  already belong to a swarm
     */
    public void addRobot(Robot robot) {
        robots.add(robot);
        robot.setSwarm(this);
    }

    /**
     * Removes the given robot from the swarm.
     *
     * @param   robot   the robot to remove; must be
     *                  a member of this swarm (see
     *                  {@link #getRobots()})
     */
    public void removeRobot(Robot robot) {
        robots.remove(robot);
        robot.setSwarm(null);
    }
}

</pre></p>
<p>The <em>AbstractRobot</em> class contains straightforward implementations of the methods defined by the Robot interface, except for the <em>getLocation</em> method, which is implemented differently in the <em>Navigator</em> and <em>Worker</em> classes (using GPS and triangulation, respectively). You can get the full source code for this example from my <a href="http://svn2.assembla.com/svn/sustainablesoftware/tags/SSW-InformalContracts/1.0.0/">Subversion repository</a> or download it as a <a href="http://www.assembla.com/file/sustainablesoftware/1_SSW-InformalContracts-1.0.0.zip" target="_blank">zip file</a>. All you need to run this example is JDK 5 (or higher) and <a href="http://ant.apache.org/" target="_blank">Ant</a>.</p>
<p>In upcoming posts I will evaluate various tools for creating formal contract specifications to replace the informal contracts that I wrote in the JavaDoc comments above.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/sustainablesoftware.wordpress.com/10/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/sustainablesoftware.wordpress.com/10/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sustainablesoftware.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sustainablesoftware.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sustainablesoftware.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sustainablesoftware.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sustainablesoftware.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sustainablesoftware.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sustainablesoftware.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sustainablesoftware.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sustainablesoftware.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sustainablesoftware.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sustainablesoftware.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sustainablesoftware.wordpress.com/10/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sustainablesoftware.wordpress.com/10/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sustainablesoftware.wordpress.com/10/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sustainablesoftware.wordpress.com&amp;blog=2727654&amp;post=10&amp;subd=sustainablesoftware&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sustainablesoftware.wordpress.com/2008/04/13/when-robots-go-to-law-school/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/86c8327133f577fd11d1ba632cfabf06?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Bernhard</media:title>
		</media:content>

		<media:content url="http://sustainablesoftware.files.wordpress.com/2008/04/robots2.png" medium="image">
			<media:title type="html">Robots class diagram</media:title>
		</media:content>
	</item>
		<item>
		<title>Smart Objects Put their Contracts in Writing</title>
		<link>http://sustainablesoftware.wordpress.com/2008/03/10/smart-objects-put-their-contracts-in-writing/</link>
		<comments>http://sustainablesoftware.wordpress.com/2008/03/10/smart-objects-put-their-contracts-in-writing/#comments</comments>
		<pubDate>Tue, 11 Mar 2008 01:53:38 +0000</pubDate>
		<dc:creator>Bernhard Glomann</dc:creator>
				<category><![CDATA[Design by Contract]]></category>

		<guid isPermaLink="false">http://sustainablesoftware.wordpress.com/?p=7</guid>
		<description><![CDATA[When you write a function or method that is going to be called from other people&#8217;s code, then you would want to let them know how to use it, right? If you are using Java, the typical way of doing that would be to document your method in a JavaDoc comment. As an example, consider [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sustainablesoftware.wordpress.com&amp;blog=2727654&amp;post=7&amp;subd=sustainablesoftware&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>When you write a function or method that is going to be called from other people&#8217;s code, then you would want to let them know how to use it, right? If you are using Java, the typical way of doing that would be to document your method in a JavaDoc comment. As an example, consider the specification for the <a href="http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#binarySearch%28int%5B%5D,%20int%29" target="_blank">Arrays.binarySearch</a> method in the Java API. It clearly states that the array that you pass into this method must be sorted in order for the method to work correctly. This is what the method expects from its caller. The documentation goes on to explain what values the method returns under which conditions. This is what the caller can expect from the method. You can think of these mutual expectations as forming a <i>contract</i> between the method (service provider) and the caller (client, service consumer). The service provider basically tells the client: As long as you ensure <i>X</i> before calling my method, I guarantee <i>Y</i> when my method returns. <i>X</i> is known as the precondition, <i>Y</i> as the postcondition.</p>
<p><span id="more-7"></span>Clearly specifying such contracts is essential, especially for <a href="http://www.martinfowler.com/bliki/PublishedInterface.html" target="_blank">published interfaces</a>. It allows developers of client code to make sure they use the method correctly, and it tells them what assumptions they can make about the result and/or side effect of the method. When something goes wrong, the contract helps find the cause of the problem. If the precondition was not satisfied, then there must be a bug in the calling code. If the precondition was satisfied, but the postcondition was not, then there must be a bug within the method.</p>
<p>So I guess what I&#8217;m saying is that documenting your contracts is important. That&#8217;s pretty much common practice, and many people would say it&#8217;s a no-brainer. So let&#8217;s go a step further. In fact, relying only on documentation to specify contracts has some limitations. First of all, contracts specified in a natural language (such as English) can be ambiguous, and different people may interpret them differently. It&#8217;s also easy to forget to update the documentation when changing the code. And a lot of methods do not even get documented in the first place, especially if they are not part of a published interface. But I think that being clear about contracts is also important among internal classes and non-published interfaces. Finally, the biggest limitation seems to be that adherence to these contracts can only be checked manually. In order to use the contracts for locating a bug, you first need to know that the bug exists. Only after learning about a bug and knowing how to reproduce it, you can step through the code and look for a contract violation.</p>
<p>To overcome these limitations, you need a formal, unambiguous way of specifying contracts, and an automated way of checking them. That&#8217;s exactly what the <a href="http://en.wikipedia.org/wiki/Design_by_contract" target="_blank">design by contract</a> methodology promises. Bertrand Meyer introduced this concept with his programming language Eiffel back in 1986. Eiffel has built-in support for specifying formal contracts as part of the program code. But what if you can&#8217;t use Eiffel? Interestingly, in over 20 years design by contract still hasn&#8217;t made its way into most mainstream languages.</p>
<p>For lack of language support, I haven&#8217;t used &#8220;real&#8221; design by contract in a serious project. Instead, I have used regular assertions (using the assert keyword in Java or the corresponding macro in C/C++) to verify my contracts. I have found assertions very helpful in debugging and catching bugs early. But since these assertions are just statements within the method implementation, they cannot really be used to <i>specify</i> contracts, but only to <i>verify</i> them. So I still have to specify the contracts separately in the documentation in order to make them explicit and visible. But this means that the contract is represented twice, violating the <a href="http://c2.com/cgi/wiki?DontRepeatYourself">DRY principle</a>.</p>
<p>I think that design by contract done right can really help achieve software sustainability. So I&#8217;ve been experimenting with some external tools that add support for design by  contract to languages like Java, and I will be writing about my experiences with these tools. In evaluating these tools, I&#8217;m particularly interested in their support for:</p>
<ul>
<li>Generating documentation from contracts</li>
<li>Run-time verification of contracts</li>
<li>Static analysis of contracts to generate unit tests or even prove correctness</li>
</ul>
<p>Stay tuned for some hands-on code examples using design by contract.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/sustainablesoftware.wordpress.com/7/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/sustainablesoftware.wordpress.com/7/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sustainablesoftware.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sustainablesoftware.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sustainablesoftware.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sustainablesoftware.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sustainablesoftware.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sustainablesoftware.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sustainablesoftware.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sustainablesoftware.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sustainablesoftware.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sustainablesoftware.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sustainablesoftware.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sustainablesoftware.wordpress.com/7/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sustainablesoftware.wordpress.com/7/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sustainablesoftware.wordpress.com/7/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sustainablesoftware.wordpress.com&amp;blog=2727654&amp;post=7&amp;subd=sustainablesoftware&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sustainablesoftware.wordpress.com/2008/03/10/smart-objects-put-their-contracts-in-writing/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/86c8327133f577fd11d1ba632cfabf06?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Bernhard</media:title>
		</media:content>
	</item>
		<item>
		<title>Lightweight Database Abstraction</title>
		<link>http://sustainablesoftware.wordpress.com/2008/02/10/lightweight-database-abstraction/</link>
		<comments>http://sustainablesoftware.wordpress.com/2008/02/10/lightweight-database-abstraction/#comments</comments>
		<pubDate>Mon, 11 Feb 2008 04:11:50 +0000</pubDate>
		<dc:creator>Bernhard Glomann</dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[Java]]></category>

		<guid isPermaLink="false">http://sustainablesoftware.wordpress.com/?p=4</guid>
		<description><![CDATA[Although there are object-relational mapping tools like Hibernate for persisting Java objects, there are still situations where you need or want to access the database directly using JDBC. One thing that has always bothered me about JDBC is the disconnect between the SQL command strings and the surrounding Java code. Consider the following example (which [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sustainablesoftware.wordpress.com&amp;blog=2727654&amp;post=4&amp;subd=sustainablesoftware&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Although there are object-relational mapping tools like <a href="http://www.hibernate.org/" target="_blank">Hibernate</a> for persisting Java objects, there are still situations where you need or want to access the database directly using <a href="http://java.sun.com/docs/books/tutorial/jdbc/index.html" target="_blank">JDBC</a>.</p>
<p>One thing that has always bothered me about JDBC is the disconnect between the SQL command strings and the surrounding Java code. Consider the following example (which prints a list of robots that were &#8220;born&#8221; before 1980):</p>
<p><pre class="brush: java;">
    public void printClassicRobots() {
        Calendar dobThreshold =
            new GregorianCalendar(1980, 0, 1);
        PreparedStatement statement = null;
        try {
            Connection connection = getConnection();
            statement = connection.prepareStatement(
                    &quot;SELECT ID, Name&quot; +
                    &quot; FROM Robots&quot; +
                    &quot; WHERE DateOfBirth &lt; ?&quot;);
            statement.setDate(1, new Date(
                    dobThreshold.getTimeInMillis()));

            ResultSet rs = statement.executeQuery();
            while (rs.next()) {
                System.out.format(&quot;%08d: %s\n&quot;,
                        rs.getInt(1),
                        rs.getString(2));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            cleanup(statement);
        }
    }
</pre></p>
<p>What I don&#8217;t like about this kind of code:</p>
<ol>
<li>Since the SQL command is just another string, the compiler does not know anything about its meaning and cannot check if its syntax is correct or if the number and types of columns in its result set are consistent with the subsequent method calls that extract data from the result set.</li>
<li>Different database systems use different variants of SQL, making it quite challenging to write portable SQL statements in all but the simplest cases.</li>
<li>Refactoring the database schema can be very tedious and error-prone if you have to resort to a text search to find all the places where a certain table or column is used in your code.</li>
</ol>
<p><span id="more-4"></span>In C# 3.0, all of these issues have been addressed through the introduction of <a href="http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx" target="_blank">LINQ to SQL</a>. But Java developers are out of luck and probably will be for some time, since adding something comparable to Java would require similarly wide-ranging language changes as were necessary to make this work in C#. So while I can&#8217;t provide a complete solution to these problems in Java, there are some simple steps I found useful in addressing at least some of them.</p>
<h3>Making table references explicit</h3>
<p>As a first step, let&#8217;s add a class to represent the <strong>Robots</strong> table, with a string constant for the table name and one for each column name:</p>
<p><pre class="brush: java;">

public class Robots {

    public static final String TABLE = &quot;Robots&quot;;

    public static final String ID = &quot;ID&quot;;

    public static final String NAME = &quot;Name&quot;;

    public static final String DOB = &quot;DateOfBirth&quot;;
}
</pre></p>
<p>We can then change the query method from above as follows:</p>
<p><pre class="brush: java;">
    public void printClassicRobots() {
        Calendar dobThreshold =
            new GregorianCalendar(1980, 0, 1);
        PreparedStatement statement = null;
        try {
            Connection connection = getConnection();
            statement = connection.prepareStatement(
                    &quot;SELECT &quot; + Robots.ID +
                    &quot;, &quot; + Robots.NAME +
                    &quot; FROM &quot; + Robots.TABLE +
                    &quot; WHERE &quot; + Robots.DOB + &quot; &lt; ?&quot;);
            statement.setDate(1, new Date(
                    dobThreshold.getTimeInMillis()));

            ResultSet rs = statement.executeQuery();
            while (rs.next()) {
                System.out.format(&quot;%08d: %s\n&quot;,
                        rs.getInt(1),
                        rs.getString(2));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            cleanup(statement);
        }
    }
</pre></p>
<p>The main advantage of this approach is that it makes table references explicit. If string constants are defined in this way for all table and column names and used consistently in all SQL statements, then it becomes easy to find all the places in your code where a given table or column is used, simply by using the &#8220;Find References&#8221; feature of your IDE. This can be helpful when refactoring the database schema.</p>
<p>Another advantage of representing database artifacts as explicit Java artifacts is that these Java artifacts provide a good place for documenting the database schema. Each table&#8217;s or column&#8217;s meaning can be documented by attaching a JavaDoc comment to the corresponding class or field declaration.</p>
<p>But wait, there&#8217;s more!</p>
<h3>Adding table definitions</h3>
<p>Now you might say that using string constants is pretty obvious and really no big deal, and I would agree with you. So let&#8217;s go a step further. If we&#8217;re going to create a separate class for each table, we might as well use that class for a little more than just to hold a couple of string constants. In addition to declaring the names of tables and columns that are <em>referenced</em> in the program, we can include the <em>definitions</em> of these tables and columns.</p>
<p>So I created two annotations, @Table and @Column, to hold some meta-data about tables and columns, for example the data type and size of a column. The class for the <strong>Robots</strong> table now looks like this:</p>
<p><pre class="brush: java;">
@Table(name = &quot;Robots&quot;)
public class Robots {

    @Column(name = &quot;ID&quot;, index = 0,
            type = Types.INTEGER, primaryKey = true)
    public final String id;

    @Column(name = &quot;Name&quot;, index = 1,
            type = Types.VARCHAR, size = 100)
    public final String name;

    @Column(name = &quot;DateOfBirth&quot;, index = 2,
            type = Types.DATE)
    public final String dob;

    public Robots(String name, String[] columns) {
        this.tableName = name;
        this.id = columns[0];
        this.name = columns[1];
        this.dob = columns[2];
    }

    @Override
    public String toString() {
        return tableName;
    }

    private final String tableName;
}
</pre></p>
<p>I am not going to go into details about the individual elements in these annotations, but you get the idea. The point is that we now have a class that encapsulates the definition of a specific table. The class contains the information necessary for creating this table in a database. It is actually pretty straightforward to write some general code that takes this kind of class as input, uses reflection to read the annotations from it and then calls <a href="http://db.apache.org/ddlutils/" target="_blank">DdlUtils</a> to create the actual database table.</p>
<p>Another thing I changed from the first version of the <strong>Robots</strong> class is that the fields for the columns are no longer static. In this way, these fields can be initialized at run time, for example to account for naming differences between multiple existing databases, or to automatically <a href="http://java.sun.com/javase/6/docs/api/java/sql/DatabaseMetaData.html#getIdentifierQuoteString()" target="_blank">quote the names</a> if they conflict with reserved words in the database.</p>
<p>Using this new version of the <strong>Robots</strong> class, the query method looks like this:</p>
<p><pre class="brush: java;">
    public void printClassicRobots() {
        Calendar dobThreshold =
            new GregorianCalendar(1980, 0, 1);
        PreparedStatement statement = null;
        try {
            Connection connection = getConnection();
            Robots robots = getRobotsTable();
            statement = connection.prepareStatement(
                    &quot;SELECT &quot; + robots.id +
                    &quot;, &quot; + robots.name +
                    &quot; FROM &quot; + robots +
                    &quot; WHERE &quot; + robots.dob + &quot; &lt; ?&quot;);
            statement.setDate(1, new Date(
                    dobThreshold.getTimeInMillis()));

            ResultSet rs = statement.executeQuery();
            while (rs.next()) {
                System.out.format(&quot;%08d: %s\n&quot;,
                        rs.getInt(1),
                        rs.getString(2));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            cleanup(statement);
        }
    }
</pre></p>
<p>The method now requires an instance of the <strong>Robots</strong> class, since its fields are no longer static. This instance could be created as part of some initialization code when the database connection is established. At this point it could also be checked whether the existing tables in the connected database are consistent with the definitions in the corresponding Java table classes, and if necessary, tables could be created or altered automatically using tools like <a href="http://db.apache.org/ddlutils/" target="_blank">DdlUtils</a> as mentioned above.</p>
<p>I like to think of table classes like the <strong>Robots</strong> class as defining the interface between the Java code and the database. Here you can define explicitly the assumptions you make troughout your program about the database schema. These assumptions can be verified or enforced early in your program&#8217;s execution (by checking and/or creating the database schema), and from that point on you shouldn&#8217;t have to worry about getting exceptions at random locations in your code because some column doesn&#8217;t exist (unless someone changes the schema at runtime).</p>
<p>I hope you enjoyed my first real blog post, and I am looking forward to your comments.  I would be interested in your experiences in this area, and in any ideas on how to solve the remaining problems that I mentioned in the beginning.</p>
<h3>Bonus</h3>
<p>In case you were wondering, this is what the above method prints on my example database:</p>
<pre>00000027: R2-D2
00000018: C-3PO
00000011: Maria</pre>
<p>You can read more about these and other famous robots at the <a href="http://www.robothalloffame.org/" target="_blank">Robot Hall of Fame</a>.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/sustainablesoftware.wordpress.com/4/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/sustainablesoftware.wordpress.com/4/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sustainablesoftware.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sustainablesoftware.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sustainablesoftware.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sustainablesoftware.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sustainablesoftware.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sustainablesoftware.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sustainablesoftware.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sustainablesoftware.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sustainablesoftware.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sustainablesoftware.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sustainablesoftware.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sustainablesoftware.wordpress.com/4/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sustainablesoftware.wordpress.com/4/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sustainablesoftware.wordpress.com/4/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sustainablesoftware.wordpress.com&amp;blog=2727654&amp;post=4&amp;subd=sustainablesoftware&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sustainablesoftware.wordpress.com/2008/02/10/lightweight-database-abstraction/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/86c8327133f577fd11d1ba632cfabf06?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Bernhard</media:title>
		</media:content>
	</item>
		<item>
		<title>Welcome to the Sustainable Software Workshop!</title>
		<link>http://sustainablesoftware.wordpress.com/2008/02/03/welcome-to-the-sustainable-software-workshop/</link>
		<comments>http://sustainablesoftware.wordpress.com/2008/02/03/welcome-to-the-sustainable-software-workshop/#comments</comments>
		<pubDate>Mon, 04 Feb 2008 04:25:04 +0000</pubDate>
		<dc:creator>Bernhard Glomann</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://sustainablesoftware.wordpress.com/?p=3</guid>
		<description><![CDATA[In this blog, I am going to write about my experiences and lessons learned while working as a software engineer. One of my goals in my daily work is to develop sustainable software: software that can be maintained at a high level of quality in the long term while frequently adapting to changing requirements. All [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sustainablesoftware.wordpress.com&amp;blog=2727654&amp;post=3&amp;subd=sustainablesoftware&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>In this blog, I am going to write about my experiences and lessons learned while working as a software engineer.</p>
<p>One of my goals in my daily work is to develop sustainable software: software that can be maintained at a high level of quality in the long term while frequently adapting to changing requirements. All too often, development focuses on getting stuff working for the next deadline, while the long-term vision and consistency of the design is neglected. Over time, the code becomes increasingly complex and hard to maintain, and the quality deteriorates.</p>
<p>Of course these problems are not new, and there are ways to help prevent them, for example using agile methodologies and practices such as unit testing and refactoring. I am planning to blog about my experiences in putting some of these techniques into practice, and there will probably also be insights from everyday problem solving, as well as random geek stuff&#8230;</p>
<p>Stay tuned!</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/sustainablesoftware.wordpress.com/3/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/sustainablesoftware.wordpress.com/3/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/sustainablesoftware.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/sustainablesoftware.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/sustainablesoftware.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/sustainablesoftware.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/sustainablesoftware.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/sustainablesoftware.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/sustainablesoftware.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/sustainablesoftware.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/sustainablesoftware.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/sustainablesoftware.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/sustainablesoftware.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/sustainablesoftware.wordpress.com/3/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/sustainablesoftware.wordpress.com/3/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/sustainablesoftware.wordpress.com/3/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=sustainablesoftware.wordpress.com&amp;blog=2727654&amp;post=3&amp;subd=sustainablesoftware&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://sustainablesoftware.wordpress.com/2008/02/03/welcome-to-the-sustainable-software-workshop/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/86c8327133f577fd11d1ba632cfabf06?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">Bernhard</media:title>
		</media:content>
	</item>
	</channel>
</rss>
