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

<channel>
	<title>Extreme Enthusiasm</title>
	<atom:link href="http://matteo.vaccari.name/blog/feed" rel="self" type="application/rss+xml" />
	<link>http://matteo.vaccari.name/blog</link>
	<description>Extreme enthusiasm</description>
	<lastBuildDate>Sun, 22 Jan 2012 16:15:38 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Formalism versus Object Thinking</title>
		<link>http://matteo.vaccari.name/blog/archives/713</link>
		<comments>http://matteo.vaccari.name/blog/archives/713#comments</comments>
		<pubDate>Sun, 22 Jan 2012 16:08:48 +0000</pubDate>
		<dc:creator>matteo</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[essay]]></category>

		<guid isPermaLink="false">http://matteo.vaccari.name/blog/?p=713</guid>
		<description><![CDATA[The book Object Thinking makes a very good explanation of the divide between two different, antagonistic modes of thinking. The formalist tradition (in software) values logic and mathematics as design tools. A formalist thinks that documents have objective, intrinsic meaning. Think &#8220;design documents&#8221;; think &#8220;specifications&#8221;. The empirical tradition (the book calls it hermeneutics, but I [...]]]></description>
			<content:encoded><![CDATA[<p>The book <a href="http://books.google.it/books/about/Object_thinking.html?id=-eJQAAAAMAAJ&amp;redir_esc=y" title="Object thinking - David West - Google Libri">Object Thinking</a> makes a very good explanation of the divide between two different, antagonistic modes of thinking.  The formalist tradition (in software) values logic and mathematics as design tools.  A formalist thinks that documents have objective, intrinsic meaning.  Think &#8220;design documents&#8221;; think &#8220;specifications&#8221;.</p>
<p>The empirical tradition (the book calls it hermeneutics, but I will stick to this less formal name :-) values experimentation.  Empiricists hold that the meaning of a document is a shared, temporary convention between the author and the readers.  Think &#8220;user story&#8221;; think CRC cards; think &#8220;quick design session on the whiteboard.&#8221;</p>
<p>The empiriricists brought us Lisp; the formalists brought us Haskell.  The formalists brought us Algol, Pascal, Ada.  The empiricists brought us C, Perl, Smalltalk.</p>
<p>Empiricists like to explain things with anthropomorphism: &#8220;this object <em>knows</em> this and <em>wants</em> to talk to that other object&#8230;&#8221;  The formalists detest anthropomorphism; see these quotes from <a href="http://lambda-the-ultimate.org/node/264" title="Dijkstra on analogies and anthropomorphism | Lambda the Ultimate">Dijkstra</a>.</p>
<p>As a former minor student of <a href="http://cs-exhibitions.uni-klu.ac.at/index.php?id=31" title="Burroughs Corporation">the best formalist tradition</a> there is, and a current student of the Object Thinking tradition, I think I&#8217;m qualified to comment.  Please don&#8217;t take my notes as meaning that the formalist tradition sucks; I certainly don&#8217;t think this.  I&#8217;m interested in highlighting differences.  I think a good developer should <strong>learn from both schools</strong>.</p>
<p>Formalists aim to bring clarity of thought by leveraging mathematical thinking.</p>
<p>Object thinking aims to bring clarity of thought by leveraging spatial reasoning, metaphor, intuition, and other modes of thinking.  </p>
<p>It is well known that mathematical thinking is powerful.  It&#8217;s also more difficult to learn and use.  One example that was <a href="http://www.cs.utexas.edu/~EWD/transcriptions/EWD10xx/EWD1036.html" title="E.W. Dijkstra Archive: On the cruelty of really teaching computing science (EWD 1036)">a favourite of Dijkstra</a> is the problem of <a href="http://gurmeet.net/puzzles/tiling-a-chessboard-with-dominoes/" title="Tiling a Chessboard with Dominoes">covering a chessboard with dominoes</a> when the opposite corners of the chessboards were removed.  If we try to prove that it&#8217;s impossible by &#8220;trying&#8221; to do it or simulating it, we&#8217;d quickly get bogged down.  On the other hand, there&#8217;s a very simple and nice proof that shows that it&#8217;s impossible.  Once you get that idea, you have power :-)</p>
<p>An even more striking example is in <a href="http://www.cs.utexas.edu/~EWD/transcriptions/EWD09xx/EWD980.html" title="E.W. Dijkstra Archive: The strange case of The Pigeon-hole Principle (EWD 980)">this note from Dijkstra</a> on the proof method called &#8220;pigeonhole principle&#8221;.  Dijkstra finds that the name &#8220;pigeon-hole principle&#8221; is unfortunate, as is the idea to imagine &#8220;holes&#8221; and a process of filling them with &#8220;pigeons&#8221; until you find that some pigeon has no hole.  The process is vivid and easy to understand; yet it is limiting.  Dijkstra shows in this note how to define the principle in a more simple and powerful way: </p>
<blockquote><p>
  For a non-empty, finite bag of numbers, the maximum value is at least the average value.
</p></blockquote>
<p>This formulation is simple (<a href="http://www.fcgarage.com/2009/05/the-magic-suitcase.html" title="The Magic Suitcase - FC Garage by Francesco Cirillo">but not easy</a>!)  Armed with this formulation, Dijkstra explains how he used this principle to solve on the spot a combinatorial problem about Totocalcio that a collegue of his could not solve with pen and paper.  He also explains how he used it to solve a generalization of the problem, which would not be easy to prove with the &#8220;object-oriented&#8221; version of the principle.</p>
<p>I think this note presents the contrast between formalism and empiricism vividly.  If you put in the effort to internalize the formal tool, that which was difficult becomes easy, and you can solve a whole new level of problems.</p>
<p>On the other hand, the formalists do now always win :-)  Formalists reject the idea of making tests the cornerstone of software development.  In my opinion they are squarely wrong; <em>examples</em> are the primary tools to do software development, and you can&#8217;t even understand if a specification is correct until you *test* it with examples.</p>
<p>The one thing that boths camps have in common is that they are both minority arts.  Real OOP is almost as rare as Dijkstra-style program derivation.  The common industrial practice is whateverism :-)</p>
]]></content:encoded>
			<wfw:commentRss>http://matteo.vaccari.name/blog/archives/713/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Greed and Simple Design</title>
		<link>http://matteo.vaccari.name/blog/archives/709</link>
		<comments>http://matteo.vaccari.name/blog/archives/709#comments</comments>
		<pubDate>Sat, 21 Jan 2012 15:07:14 +0000</pubDate>
		<dc:creator>matteo</dc:creator>
				<category><![CDATA[Agile]]></category>

		<guid isPermaLink="false">http://matteo.vaccari.name/blog/?p=709</guid>
		<description><![CDATA[Some people like Carlo say that the famous Four Elements of Simple Design by Kent Beck are an oversimplification. Perhaps it&#8217;s true, but still I find that they are a very useful compass. Consider again: A design is simple when Runs all the tests. Contains no duplication Expresses all the ideas you want to express. [...]]]></description>
			<content:encoded><![CDATA[<p>Some people like <a href="http://www.carlopescio.com/" title="Carlo Pescio - blog">Carlo</a> say that the famous <a href="http://www.jbrains.ca/permalink/the-four-elements-of-simple-design" title="The Four Elements of Simple Design &#8211; jbrains">Four Elements of Simple Design</a> by Kent Beck are an <a href="http://www.carlopescio.com/2011/10/youre-solving-wrong-problem.html" title="Carlo Pescio - blog: You're solving the wrong problem">oversimplification</a>.  Perhaps it&#8217;s true, but still I find that they are a very useful compass.  Consider again:</p>
<p>A design is <em>simple</em> when</p>
<ol>
<li>Runs all the tests.</li>
<li>Contains no duplication</li>
<li>Expresses all the ideas you want to express.</li>
<li>Minimizes classes and methods</li>
</ol>
<p>in this order.</p>
<p>Rule 2 is important, as it pushes us to invent abstractions that capture recurring patterns.  But rule 3 is also imporant, as it pushes us to invent abstractions that correspond to the ideas that we want to express.</p>
<p>The other day I saw <a href="http://blogs.ugidotnet.org/luKa/archive/2012/01/08/greed-dice-game-exercise-from-ruby-koans.aspx" title="Greed dice game exercise from Ruby Koans">this post by Luca</a> about a fun kata: implementing the scoring rules for a dice game called &#8220;Greed&#8221;.  This exercise is part of the <a href="http://rubykoans.com/" title="Learn Ruby with the EdgeCase Ruby Koans">Ruby Koans</a>, but its use as a programming exercise dates at least from the OOPSLA &#8217;89 conference, when <a href="http://books.google.it/books?id=3BLGWnmQJ9IC&amp;printsec=frontcover&amp;dq=tom+love+object+lessons&amp;hl=it&amp;sa=X&amp;ei=xNEaT55MjI7iBPXCgdQN&amp;redir_esc=y#v=onepage&amp;q=tom%20love%20object%20lessons&amp;f=false" title="Object Lessons: Lessons Learned in Object-Oriented Development Projects - Tom Love - Google Books">Tom Love proposed a contest</a> to show how a program could be written in different ways and in different languages.</p>
<p>A little research shows <a href="http://stackoverflow.com/questions/4749973/ruby-greed-koan-how-can-i-improve-my-if-then-soup" title="Ruby Greed Koan - How can I improve my if/then soup? - Stack Overflow">many</a> <a href="http://stackoverflow.com/questions/6738715/ruby-koans-182-refactor-help" title="Ruby Koans 182. Refactor help - Stack Overflow">solutions</a> for this problem.  As this problem is presented in the context of a Ruby programming exercise, people usually tries clever tricks that exploit peculiar Ruby idioms.  For instance:</p>
<p><code>
<pre>
def score(dice)
  (1..6).collect do |roll|
    roll_count = dice.count(roll)
    case roll
      when 1 : 1000 * (roll_count / 3) + 100 * (roll_count % 3)
      when 5 : 500 * (roll_count / 3) + 50 * (roll_count % 3)
      else 100 * roll * (roll_count / 3)
    end
  end.reduce(0) {|sum, n| sum + n}
end
</pre>
<p></code><cite><a href="http://stackoverflow.com/a/6742129/164802" title="Ruby Koans 182. Refactor help - Stack Overflow">http://stackoverflow.com/a/6742129/164802</a></cite></p>
<p>There&#8217;s a place for this sort of exercises, but it&#8217;s not the sort of programming that I would like my collegues to practice!  If we apply the rule 3, I expect to see in the source cose some mention of the *rules* of the game.   I expect that there&#8217;s a programming element that corresponds to the rule that &#8220;three ones are worth 1000 points&#8221;, etc.  Really, it does not take all that much more effort, and I assert that <em>it&#8217;s more fun</em> to code expressively!</p>
<p>This is my solution:</p>
<p><code>
<pre>
class Array
  def occurrences_of(match)
    self.select{ |number| match == number }.size
  end

  def delete_one(match)
    for i in (0..size)
      if match == self[i]
        self.delete_at(i)
        return
      end
    end
  end
end

def single_die_rule(match, score, dice)
  dice.occurrences_of(match) * score
end

def triple_rule(match, score, dice)
  return 0 if dice.occurrences_of(match) < 3
  3.times { dice.delete_one match }
  score
end

def score(dice)
  triple_rule(1, 1000, dice) +
  triple_rule(2, 200, dice) +
  triple_rule(3, 300, dice) +
  triple_rule(4, 400, dice) +
  triple_rule(5, 500, dice) +
  triple_rule(6, 600, dice) +
  single_die_rule(1, 100, dice) +
  single_die_rule(5, 50, dice)
end
</pre>
<p></code></p>
<p>There's some more duplication that could be removed (the five similar rules could be expressed as a single rule) and the names could be improved, but I think this is the way to go.  Make your code look <strong>like a model of the problem</strong>!</p>
]]></content:encoded>
			<wfw:commentRss>http://matteo.vaccari.name/blog/archives/709/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Classes without a face</title>
		<link>http://matteo.vaccari.name/blog/archives/700</link>
		<comments>http://matteo.vaccari.name/blog/archives/700#comments</comments>
		<pubDate>Thu, 05 Jan 2012 08:07:45 +0000</pubDate>
		<dc:creator>matteo</dc:creator>
				<category><![CDATA[Agile]]></category>

		<guid isPermaLink="false">http://matteo.vaccari.name/blog/?p=700</guid>
		<description><![CDATA[I have a feeling for classes that should not be there. When I saw this cartoon about &#8220;how an object-oriented programmer sees the world&#8221;, I was struck by the fact that all the names of objects were wrong! These are the names that would be chosen by a poor OO programmer. A good programmer would [...]]]></description>
			<content:encoded><![CDATA[<p>I have a feeling for classes that should not be there.  When I saw <a href="http://www.bonkersworld.net/object-world/" title="Object World | Bonkers World">this cartoon</a> about &#8220;how an object-oriented programmer sees the world&#8221;, I was struck by the fact that all the names of objects were wrong!  These are the names that would be chosen by a poor OO programmer.  A good programmer would choose &#8220;Door&#8221; instead of &#8220;IndoorSessionInitializer&#8221;.  But then the cartoon would not be funny :-)</p>
<p>A similar thing happens in the code base of our current project.  Sometimes I see a class that strikes me as odd.  Perhaps it has a name that does not communicate; more often it is simply a class that should not exist.</p>
<p><span id="more-700"></span></p>
<p>One such example is the UserAuthenticationContainer.  WTF?!? you are saying?  That&#8217;s what I also thought when I saw it.  It turns out that a UserAuthenticationContainer contains a hashed password and a User.  </p>
<pre><code>class UserAuthenticationContainer {
    public final User user;
    public final String password;

    public UserAuthenticationContainer(User userFrom, String password) {
        this.user = userFrom;
        this.password = password;
    }
}
</code></pre>
<p>It was used to authenticate the user:</p>
<pre><code>public User authenticate(String username, String password) {
    try {
        UserAuthenticationContainer userAuthentication =
          registry.getUserAuthenticationContainer(username);
        if (!encode(password).equals(userAuthentication.password)) {
            throw new WrongPasswordException(username);
        }
        return userAuthentication.user;
    } catch (RecordNotFoundException e) {
        throw new UserNotFoundException(username);
    }
}
</code></pre>
<p>This is unnecessary.  This class existed only for the purpose of returning two items from a call.  We got rid of it by letting User contain its hashedPassword.  Furthermore, we moved the job of matching the user input with the hashed password inside the User object itself.  This is how the authentication code looks now:</p>
<pre><code>public User authenticate(String username, String password) {
    try {
        User user = registry.findByName(username);
        if (!user.matchesPassword(password)) {
            throw new WrongPasswordException(username);
        }
        return user;
    } catch (RecordNotFoundException e) {
        throw new UserNotFoundException(username);
    }
}
</code></pre>
<p>The matchesPassword method in turn delegates the matching to its <a href="http://matteo.vaccari.name/blog/archives/685">PasswordDataItem</a>.</p>
<pre><code>public boolean matchesPassword(String userInput) {
  return this.password.matches(userInput);
}
</code></pre>
<p>Another example is this FilterByUserShopsCriteria:</p>
<pre><code>public class FilterByUserShopsCriteria implements Criteria {
    private final Criteria criteria;

    public FilterByUserShopsCriteria(User user, Criteria criteria) {
        Collection&lt;String&gt; shopIds
          = transform(user.getShops(), toShopIds());
        this.criteria = and(criteria, in("ShopID", shopIds));
    }

    @Override
    public String condition() {
        return criteria.condition();
    }

    @Override
    public Object[] values() {
        return criteria.values();
    }
}
</code></pre>
<p>Its purpose is to return a Criteria (it represent a Sql &#8220;where&#8221; condition) that matches the Shops that belong to a user.  This class was made unnecessary by moving the generation of that Criteria in the User class itself.</p>
<p>I think that this sort of classes happens when we detach &#8220;object-oriented&#8221; from &#8220;modeling&#8221;.  An object should be a part of a model of the problem domain.  It might also be a &#8220;technical&#8221; class, like an HtmlForm; this is not part of the core domain of the application, but still has a clearly defined role in the system.  When we keep applying OOP in a &#8220;syntactical&#8221; way, we risk creating objects that may be decoupled, but are not cohesive.  Functionality is dispersed far away from the center of responsibility.  </p>
<p>The &#8220;semantic&#8221; clue is that a FilterByUserShopsCriteria is not a natural part of the problem domain.  See also <a href="http://www.carlopescio.com/2011/04/your-coding-conventions-are-hurting-you.html" title="Carlo Pescio - blog: Your coding conventions are hurting you">this post by Carlo Pescio</a> about how the names we choose for classes have a deep influence on design.</p>
]]></content:encoded>
			<wfw:commentRss>http://matteo.vaccari.name/blog/archives/700/feed</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>On the folly of representing a first name with a String</title>
		<link>http://matteo.vaccari.name/blog/archives/685</link>
		<comments>http://matteo.vaccari.name/blog/archives/685#comments</comments>
		<pubDate>Wed, 04 Jan 2012 21:01:54 +0000</pubDate>
		<dc:creator>matteo</dc:creator>
				<category><![CDATA[Agile]]></category>

		<guid isPermaLink="false">http://matteo.vaccari.name/blog/?p=685</guid>
		<description><![CDATA[Object-Oriented decomposition is supposed to be different When I read Object Thinking, I was intrigued by this quote by Grady Booch: Let there be no doubt that object-oriented design is fundamentally different from traditional structured design approaches: it requires a different way of thinking about decomposition, and it produces software architectures that are largely outside [...]]]></description>
			<content:encoded><![CDATA[<h3>Object-Oriented decomposition is supposed to be different</h3>
<p>When I read <a href="http://www.microsoft.com/learning/en/us/book.aspx?ID=6820&amp;locale=en-us" title="Object Thinking">Object Thinking</a>, I was intrigued by this quote by Grady Booch:</p>
<blockquote><p>
  Let there be no doubt that object-oriented design is fundamentally different from traditional structured design approaches: it requires a different way of thinking about decomposition, and it produces software architectures that are largely outside the realm of the structured design culture.
</p></blockquote>
<p>So it seems that OOD decomposes a problem in a way that is essentially different from what you would arrive at with other design methods.  I was intrigued: I wonder what are these different, elusive ways of decomposing things.</p>
<p><span id="more-685"></span></p>
<p>One important hint came from reading this <a href="http://www.smalltalk.org/smalltalk/TheEarlyHistoryOfSmalltalk_I.html">highly recommended paper</a> by Alan Kay, also quoted by Carlo Pescio in a <a href="http://www.carlopescio.com/2011/04/your-coding-conventions-are-hurting-you.html" title="Carlo Pescio - blog: Your coding conventions are hurting you">very interesting post</a>:</p>
<blockquote><p>
  &#8220;The basic principle of recursive design is to make the parts have the same power as the whole.&#8221; For the first time I thought of the whole as the entire computer and wondered why anyone would want to divide it up into weaker things called data structures and procedures. Why not divide it up into little computers, as time sharing was starting to? But not in dozens. Why not thousands of them, each simulating a useful structure?
</p></blockquote>
<p>So one main idea is to recurse.  When you break up a system in data structures and procedures, what you get are pieces that are less powerful than the whole.  A data structure has no behaviour, a procedure has no state.  Computers have both state and behaviour, and so do objects.  Let&#8217;s see how this idea applies to a common programming task: a web-based registration form.</p>
<h3>Tedium and repetition</h3>
<p>Suppose we must implement a registration form, with the usual abundance of  of data: first name, last name, email, username, password, etc.  The common way to do this in Java is more or less along these lines:</p>
<pre><code>&lt;form&gt;
  &lt;label for="firstName"&gt;First Name&lt;/label&gt;
  &lt;input id="firstName" name="firstName" value="${firstName}" /&gt;
  &lt;label for="lastName"&gt;Last Name&lt;/label&gt;
  &lt;input id="lastName" name="lastName" value="${lastName}" /&gt;
  &lt;label for="email"&gt;Email&lt;/label&gt;
  &lt;input id="email" name="email" value="${email}" /&gt;
  &lt;!-- and so on and so forth for 100 other fields --&gt;
&lt;/form&gt;

class RegistrationRequest {
  private String firstName;
  private String lastName;
  private String email;
  // and so on and so forth ...

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public String getFirstName() {
    return firstName;
  }
  // and so on and so forth ...

  public ErrorList validate() {
    ErrorList errors = new ErrorList();
    if (isEmpty(firstName)) {
      errors.add("First Name is required");
    }
    if (isEmpty(lastName)) {
      errors.add("Last Name is required");
    }
    // and so on and so forth ....
    return errors;
  }
}

class RegistrationRequestController {
  public void handleRequest(
    HttpServletRequest request, HttpServletRequest response
  ) {
    RegistrationRequest rr = new RegistrationRequest();
    rr.setFirstName(request.getParameter("firstName"));
    rr.setLastName(request.getParameter("lastName"));
    rr.setEmail(request.getParameter("email"));
    // etc etc ...
    if (rr.isEmpty()) {
      registrationDao.save(rr);
      response.redirectTo(THANKYOU_PAGE);
    } else {
      registrationView.setErrors(errors);
      response.getWriter().write(registrationView.toHtml());
    }
  }
}

class RegistrationDao {

  public void save(RegistrationRequest rr) {
    String sql = "insert into registration_requests" +
      " (firstName, lastName, email, ...) " + // etc.
      " values (?,?,?,....)"; // etc.
    PreparedStatement statement = connection.prepareStatement(sql);
    statement.setObject(1, rr.getFirstName());
    statement.setObject(2, rr.getLastName());
    // ... arrrgh!
    statement.execute();
  }
}
</code></pre>
<p>And so on and so forth.  The list of the attributes: firstName, lastName, email&#8230; is repeated <em>dozens</em> of times in the source code.  Talk about &#8220;remove duplication&#8221;!  Rails has an approach to solve this problem.  Rails&#8217; ActiveRecord objects turn down the number of repetitions considerably, but <a href="http://blog.steveklabnik.com/posts/2011-12-30-active-record-considered-harmful" title="ActiveRecord (and Rails) Considered Harmful - Literate Programming">not in a completely satisfactory way</a>.  Hibernate removes some of this tedium, but not all of it and definitely not in a satisfactory way.  At least for me.</p>
<p>So is there a way to code this very simple and very common scenario without killing your soul with the tedium of repeating the same list of attributes over and over?  Is there a programming technique that can save us without having to resort to the mysterious and treacherous magicks of Rails, Spring or Hibernate?</p>
<p>I hinted at such a way in <a href="http://www.slideshare.net/xpmatteo/20110305-tddcodemotion" title="TDD da un capo all'altro/TDD from end to end">my CodeMotion presentation in 2011</a>.  One simple way to get started is to stop treating the RegistrationRequest attributes as <em>code</em> and just let them be what they are: <em>data</em>.  If we substitute the RegistrationRequest class with a simple HashMap we can remove many of the repetitions.  When I showed <a href="http://www.slideshare.net/xpmatteo/20110305-tddcodemotion/22" title="TDD da un capo all'altro/TDD from end to end">slide 22</a> to the audience, they were surprised :-) Noted blogger and DDD authority Alberto Brandolini was so surprised that <a href="http://twitter.com/#!/ziobrando/status/44043446675177473" title="Twitter">he tweeted about it</a>.  Many would say that this is a dirty trick, or the mark of an inexperienced programmer.  But a Rails&#8217; <a href="http://ar.rubyonrails.org/" title="Active Record -- Object-relation mapping put on rails">ActiveRecord</a> object is not too dissimilar to a Map.  In fact the heart of a Rails&#8217; ActiveRecord object is a Hash of attributes.  Using Maps this way is natural for people coming from PHP programming, like me and like David Heinemeier Hansson.</p>
<h3 id="more_inspiration">More inspiration</h3>
<p>The HashMap kinda works, but even I admit it&#8217;s not the most elegant solution.  The next flash of inspiration came from the Object Thinking book, where he presents the example of a mortgage application form.  The form, he says, <strong>is a collection of data items</strong>.  </p>
<p>Another flash of insight from Object Thinking: holding information <em>is</em> a responsibility.  We budding OO programmers are constantly being warned against the anemic domain model.  &#8220;Don&#8217;t confuse a data structure with an object!  Stay away from objects without behaviour!&#8221;  But Object Thinking says that some objects have as their primary responsibility the one of <strong>holding information</strong>.  This is liberating :-)  There are more responsibilities that are closely related with the one of holding information: <em>presenting</em> and <em>validating</em> the information.  Now this is an interesting set of responsibilities.</p>
<p>If the application as a whole has a user interface, behaviour and persistence, then the principle of recursive design should imply that most objects should also have user interfaces, behaviour and persistence.  Persistence itself is a kind of user interface, where the user is a database.  So the registration form should have a user interface, behaviour and persistence.  And since the registration form is essentially a collection of data items, its user interface should be composed of the user interfaces of its data items; the form&#8217;s behaviour should be a composition of the behaviours of its data items.</p>
<p>All this leads to the conclusion that storing a first name in a String is folly.  A String cannot defend itself!  It cannot encapsulate its state, it cannot validate itself, it cannot persist itself.  Suppose we rewrote the RegistrationRequest like this:</p>
<pre><code>class RegistrationRequest extends CompositeDataItem {
  private PrimaryKeyDataItem requestId =
    new PrimaryKeyDataItem("requestId");

  private StringDataItem firstName =
    new StringDataItem("First Name", "firstName");

  private StringDataItem lastName =
    new StringDataItem("Last Name", "lastName");

  private StringDataItem email =
    new StringDataItem("Email", "email") {{
      add(new EmailValidationRule());
    }}
  // ...
}
</code></pre>
<p>Now this list of data items could be the one and only representation in the system of the list of attributes of the RegistrationRequest.  A lot of duplication disappears.  For instance, how do we load the HttpServletRequest parameters into the RegistrationRequest?  Easy, by delegating the work to the DataItems.  Every DataItem knows its name, so it can find the parameter(s) it needs.</p>
<pre><code>class StringDataItem extends DataItem {
  // ...
  void loadFrom(HttpServletRequest request) {
    this.value = request.getParameter(this.name);
  }
  // ...
}
</code></pre>
<p>The RegistrationRequest loads itself from the parameters by delegating to its data items:</p>
<pre><code>class RegistrationRequest extends CompositeDataItem {
  // ...
  void loadFrom(HttpServletRequest request) {
    for (DataItem item: dataItems()) {
      item.loadFrom(request);
    }
  }
  // ...
}
</code></pre>
<p>If I give an HtmlForm to the RegistrationRequest, then it can add its fields to the form:</p>
<pre><code>class RegistrationRequest extends CompositeDataItem {
  // ...
  void presentYourselfOn(HtmlForm form) {
    for (DataItem item: dataItems()) {
      item.presentYourselfOn(form);
    }
  }
  // ...
}
</code></pre>
<p>Every Data Item knows how to present itself on a form:</p>
<pre><code>class StringDataItem extends DataItem {
  // ...
  void presentYourselfOn(HtmlForm form) {
    form.addTextField(this.label, this.name, this.value);
  }
  // ...
}
</code></pre>
<p>Does this violate the principle of separating the domain from the user interface?  Not really.  We&#8217;re not concatenating strings to produce html here.  We&#8217;re interacting with a view object.  </p>
<p>Validation will also be handled recursively.</p>
<p>All of the various responsibilities that we&#8217;re giving the DataItems can make them increasingly complex.  But we can deal with this complexity with delegation.  For instance, validation rules could be separate objects that are added to the DataItems, like the EmailValidationRule in the example above.</p>
<h3 id="conclusion">Conclusion</h3>
<p>So we&#8217;ve arrived to something that <strong>is</strong> quite different from what you would get with procedural thinking.  Procedural thinking leads you to use a String to represent a first name.  This may lead you to use Lombok to generate the setters and getters automatically, and then Hibernate to generate the SQL statements automatically, and so on.  An apparently simple and obvious choice leads to a lot of complexity&#8230;  </p>
<p>The non-entirely-obvious choice of storing the attributes in DataItems leads to a simple way to implement all of the basic functionality of a Crud, with little or no need for frameworks.  This helps to keep accidental complexity low.  </p>
<p>The approach shown here is not a framework; not even a library. it&#8217;s just an idea.  You can implement it yourself in very little time, and it will probably come out different every time.  That&#8217;s right; the DataItem you need in one project is not necessarily the same that you need in another.</p>
]]></content:encoded>
			<wfw:commentRss>http://matteo.vaccari.name/blog/archives/685/feed</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>How I remembered Object Thinking</title>
		<link>http://matteo.vaccari.name/blog/archives/675</link>
		<comments>http://matteo.vaccari.name/blog/archives/675#comments</comments>
		<pubDate>Tue, 13 Dec 2011 21:56:28 +0000</pubDate>
		<dc:creator>matteo</dc:creator>
				<category><![CDATA[Agile]]></category>

		<guid isPermaLink="false">http://matteo.vaccari.name/blog/?p=675</guid>
		<description><![CDATA[A revelation inside another revelation I&#8217;ve been reading Object Thinking. It&#8217;s an unusual book, in that it talks mainly about the philosophy of OOP rather than technicalities like Dependency Injection. There are many gems in this book. One of the main things I got out of it is that Object Thinking is a revolutionary break [...]]]></description>
			<content:encoded><![CDATA[<h3>A revelation inside another revelation</h3>
<p>I&#8217;ve been reading <a href="http://books.google.it/books/about/Object_thinking.html?id=-eJQAAAAMAAJ&amp;redir_esc=y" title="Object thinking - David West - Google Libri">Object Thinking</a>.  It&#8217;s an unusual book, in that it talks mainly about the <em>philosophy</em> of OOP rather than technicalities like Dependency Injection.  There are many gems in this book.  One of the main things I got out of it is that Object Thinking is a revolutionary break with respect to established software engineering practice.  Another thing is that  the view of objects as Abstract Data Type is basically the establishment&#8217;s way to dilute and incorporate the grand new thing and make it look like a variation of the old thing.</p>
<p>Again, one thing that I changed my mind about is to take seriously the idea of <em>modeling the domain</em>.   I mean, the old OOP books all said things like &#8220;take the description of your problem, underline the nouns in the description, and these are your candidate objects&#8221;.  I used to think that this is a silly exercise!  And I&#8217;m not alone.  I heard many times the phrase: &#8220;<a href="http://c2.com/cgi/wiki?OopNotForDomainModeling" title="Oop Not For Domain Modeling">objects are good, but not for the domain</a>.&#8221;</p>
<p>In the last few years since I attended <a href="http://www.fcgarage.com/" title="FC Garage by Francesco Cirillo">Francesco Cirillo</a>&#8216;s workshop on Emergent Design in 2009, I have been studying OOP.  I learned about the <a href="http://en.wikipedia.org/wiki/Design_Patterns" title="Design Patterns - Wikipedia, the free encyclopedia">GOF patterns</a>.  I learned about the <a href="http://www.cleancoders.com/" title="Clean Coders">SOLID principles</a>.  I learned how to <a href="http://misko.hevery.com/presentations/" title="Presentations">write testable code</a>.  I learned how to do <a href="http://www.slideshare.net/xpmatteo/20110305-tddcodemotion" title="TDD da un capo all'altro/TDD from end to end">TDD for the infrastructure</a>.  I learned how to test-drive <a href="http://programmers.stackexchange.com/a/123672/42607" title="concepts - What are the London and Chicago schools of TDD? - Programmers - Stack Exchange">Chicago style and London style</a>.   I invented exercises for teaching the <a href="http://matteo.vaccari.name/blog/the-hexagonal-architecture" title="Extreme Enthusiasm   &raquo; The Hexagonal Architecture">Hexagonal Architecture</a> and the <a href="http://matteo.vaccari.name/blog/archives/293" title="Extreme Enthusiasm  &raquo; Blog Archive   &raquo; The OCP kata">Open/Closed principle</a>.  </p>
<p>All of these things are good, and very useful to learn.    Yet they are not the heart of Object Thinking.  All these things are based on the shape of programs.  For instance: I write a <a href="http://c2.com/cgi/wiki?LongMethodSmell" title="Long Method Smell">Long Method</a> (bad), then I <a href="http://c2.com/cgi/wiki?ExtractMethod" title="Extract Method">Extract Method</a> a few times, then I <a href="http://c2.com/cgi/wiki?ExtractClass" title="Extract Class">Extract Class</a>, and voila, I have done an Object Decomposition.  But this is a mechanical exercise, that takes into account mostly the <em>shape</em> of the methods and not their <em>meaning</em>.  If I&#8217;m lucky, my decomposed class will turn out to be something significant in terms of the domain.  If I&#8217;m less lucky, I&#8217;ll have extracted some boring bit of infrastructure, like the <a href="http://www.bonkersworld.net/object-world/" title="Object World | Bonkers World">IndoorSessionInitializer</a>.</p>
<p>What I was missing on is decomposition based on Object Thinking.  Decomposition based on writing the Domain Model.  Thinking about the Domain Model as a <em>simulation</em> of the problem domain, as if the domain objects were little computer people sending messages to each other.  Ding!  </p>
<h3>The incredible compressing brain of Kent Beck</h3>
<p>Kent Beck&#8217;s brain contains probably the most efficient compression algorithm ever.  Kent is able to <a href="http://codebetter.com/iancooper/2011/10/06/avoid-testing-implementation-details-test-behaviours/">compress in a couple of lines</a> what others do take volumes to explain.  Take Kent Beck&#8217;s four rules of simple design:</p>
<blockquote><p>
  The right design for the software at any given time is the one that </p>
<ol>
<li>Runs all the tests. </li>
<li>Has no duplicated logic. [...]</li>
<li>States every intention important to the programmers. </li>
<li>Has the fewest possible classes and methods.</li>
</ol>
<p>  <cite>Kent Beck, <em>Extreme Programming Explained</em></cite>
</p></blockquote>
<p>Consider item 2.  It basically means: look at the <strong>shape</strong> of your code, and wherever you see the same information encoded twice, find a way to generalize or abstract so that it is encoded just once.  In a few words he is implying  the contents of the Refactoring book, of SOLID, and all approaches that look at the shape of code for guidance on how to improve its design.</p>
<p>Then consider item 3.  It basically means: look at the <strong>meaning</strong> of your code, and make sure that the meaning is apparent in the names and the structure.  This implies that you should make your code a <em>model</em> of the problem domain.</p>
<p>(Items 1 and 4 are just safeguards against making refactorings that break functionality, or going wild with OOD ideas and making the design worse by making it overcomplicated.)</p>
<h3>Am I crazy or&#8230;</h3>
<p>As an aside, I find myself buying lots of out-of-print books.  It seems the things that I find most interesting are not what the world of programming in general finds interesting.  Even my beloved Extreme Programming seems out of fashion lately.  Nobody wrote about XP since Kent Beck wrote <a href="http://my.safaribooksonline.com/book/software-engineering-and-development/extreme-programming/0321278658" title="Extreme Programming Explained: Embrace Change, Second Edition: Safari Books Online">the last</a> of the <a href="http://www.google.it/search?hl=it&amp;tbo=p&amp;tbm=bks&amp;q=bibliogroup:%22The+XP+series%22&amp;source=gbs_metadata_r&amp;cad=11" title="Google">Coloured Books</a> in 2004.  But I still think that OOP and evolutionary design and XP are <strong>crucial</strong> things to learn.  Yet everyone wants to learn about the latest technology fad.  The latest technology fad I&#8217;m getting into is <a href="http://www.smalltalk.org/">SmallTalk</a>, and it&#8217;s something that stopped being developed around 1980. This means that either I&#8217;m crazy, or everyone else is.  </p>
<h3>In conclusion</h3>
<p>When I was young I really believed in objects.  My first falling in love with objects was over the cover of an issue of Byte Magazine dedicated to OOP.</p>
<p>I remember now that in nineteen-eighty-something I wrote an object-oriented program for an AI assignment.  It was a program for symbolic integration that took inspiration from some <a href="http://en.wikipedia.org/wiki/Fluid_Concepts_and_Creative_Analogies#The_Architecture_of_Jumbo" title="Fluid Concepts and Creative Analogies - Wikipedia, the free encyclopedia">crazy idea</a> by Douglas Hofstadter.  It was a community of software agents, each one specialized in some symbolic solution technique, that worked at the problem without any central coordination.  It was written in some variant of Lisp that had no Object-Oriented extensions; so I wrote my own OOP system on top of Lisp.  It was fun :-) and it was not difficult at all to do.</p>
<p>Then, in the nineties, I got enamored of formalist thinking; not the brand that did UML, but the brand that did <a href="http://books.google.it/books/about/A_method_of_programming.html?id=728ZAQAAIAAJ" title="A method of programming - Edsger Wybe Dijkstra, W. H. J. Feijen - Google Libri">Formal Methods</a>.  By then, OOP seemed such a scruffy and ineffective thing to me.  But by that time, when I thought of OOP I was thinking of C++; I was thinking of large, unwieldy frameworks based on very long inheritance chains.  Small wonder that I didn&#8217;t like it.</p>
<p>In the eighties, when I thought of objects, I thought of letting artificial intelligence emerge out of the collaboration of many simple autonomous agents.  What a silly and romantic idea!  Yet this idea is at the heart of OOP as was originally imagined by Alan Kay and the others.</p>
<blockquote><p>
  This is probably a good place to comment on the difference between what we thought of as OOP-style and the superficial encapsulation called &#8220;abstract data types&#8221; that was just starting to be investigated in academic circles. &#8230; To put it mildly, we were quite amazed at this, since to us, what Simula had whispered was something much stronger than simply reimplementing a weak and ad hoc idea. What I got from Simula was that you could now replace bindings and assignment with <em>goals</em>. &#8230; the objects should be presented as <em>sites of higher level behaviors more appropriate for use as dynamic components</em>.<br />
  <cite>Alan Kay, The Early History of SmallTalk</cite>
</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://matteo.vaccari.name/blog/archives/675/feed</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Can you tell a program&#8217;s paradigm by looking at it?</title>
		<link>http://matteo.vaccari.name/blog/archives/670</link>
		<comments>http://matteo.vaccari.name/blog/archives/670#comments</comments>
		<pubDate>Fri, 02 Dec 2011 18:04:01 +0000</pubDate>
		<dc:creator>matteo</dc:creator>
				<category><![CDATA[Agile]]></category>

		<guid isPermaLink="false">http://matteo.vaccari.name/blog/?p=670</guid>
		<description><![CDATA[I attended an interesting talk the other night at the Milano XP User Group. Uberto Barbini was sharing his thoughts and experiences over using Object-Oriented and Functional Programming together. Uberto showed us some production code, that he thought was a neat application of FP in a OOP context. The funny thing is that to my [...]]]></description>
			<content:encoded><![CDATA[<p>I attended an interesting talk the other night at the <a href="http://milano-xpug.pbworks.com/w/page/20915693/FrontPage" title="milano-xpug / FrontPage">Milano XP User Group</a>.  <a href="http://twitter.com/#!/ramtop" title="Twitter">Uberto Barbini</a> was sharing his thoughts and experiences over <a href="http://www.slideshare.net/ubertobarbini/boost-youroopwithfp-10235357" title="Boost your-oop-with-fp">using Object-Oriented and Functional Programming together</a>.  </p>
<p>Uberto showed us some production code, that he thought was a neat application of FP in a OOP context.  The funny thing is that to my eyes it seemed that was neither FP nor OOP; it seemed procedural to me.  Uberto argued that it was functional and not procedural, because there was no global state involved; it was a self-contained transformation of data.</p>
<p>That got me thinking.  Do I like that definition of &#8220;procedural&#8221;?  I don&#8217;t think so.  I think that you can tell procedural code when the thinking that goes behind that code is something like:</p>
<blockquote><p>
  First I do this.<br />
  Then I do that.<br />
  If Zot Then I do Blah.<br />
  Else I do Blorgh.
</p></blockquote>
<p>When you think of a recipe, or a sequence of steps, then for me it&#8217;s procedural.  Essentially &#8220;procedural&#8221; is to model the solution as a process.  </p>
<p>On the other hand, functional programming, in my humble opinion, is about mathematical models.  You model the problem and the solution with functions, sets, maps, trees and all those abstract and precise mathematical concepts.</p>
<p>What about Object-Oriented Programming then?  My thinking about OOP has been in the past that OOP is a natural consequence of writing modular programs.  An object is a hidden data structure with a visible collection of operations.  Then I understood that this is just one way to look at OOP, and probably it&#8217;s the wrong one :-)  This point of view is heavily influenced by mathematics (the idea that the operation on an object define a sort of algebra) and by procedural thinking (the idea that programs = data + procedures, just like the title of an old favourite textbook.)  </p>
<p>I learned from reading <a href="http://www.growing-object-oriented-software.com/" title="Growing Object-Oriented Software Guided by Tests:<br />
                    About the Book">GOOS</a> that OOP is mostly about the messages.  There are some intesting and tantalizing quotes from Alan Kay about that.   Even more recently I read <a href="http://www.amazon.com/Object-Thinking-DV-Microsoft-Professional-David/dp/0735619654" title="Amazon.com: Object Thinking (DV-Microsoft Professional) (9780735619654): David West: Books">Object Thinking</a>, and I came to understand that OOP is about modeling the problem with a community of autonomous agents.  The way to make OOP shine is to build a <strong>simulation</strong> of the problem.  And I remembered the thrill I once had when I first read about OOP.  About imagining these little software robots going about their business inside my programs.  An object that can &#8220;think&#8221; for itself and has a behaviour.   Now *that* is what OOP is about!</p>
<p>Back to the original theme, now was the code that Uberto showed to us OOP, FP or procedural?  It turns out that it depends!  You can&#8217;t say by just looking at the code.  It depends on the <em>thinking</em> that goes behind the code.  Uberto thinks functionally when he thinks about this code.  That makes it functional code for him.</p>
<p>Suppose that years later I inherit his codebase.  If I have no access to Uberto, it&#8217;s pretty difficult for me to <a href="http://alistair.cockburn.us/ASD+book+extract%3A+%22Naur,+Ehn,+Musashi%22" title="Alistair.Cockburn.us | ASD book extract: "Naur, Ehn, Musashi"">reconstruct his mental process</a>.  I will probably treat the code as procedural; or maybe OO depending on my way of thinking about this code.</p>
<p>So this is a pretty shocking thought, isn&#8217;t it?  I thought you could look at a program and tell its paradigm, functional or procedural or OO, just by looking at the code.  But I now think you can&#8217;t; the three paradigms are not different ways to code; they are different ways of thinking!  Procedural thinking is about recipes: follow these steps.  Functional thinking is about math: functions and sets.  Object-Oriented is about simulations: many independent agents.  And this explains why it&#8217;s difficult to do OO well.  You have to learn a different way of thinking.  This is something that I heard <a href="http://www.fcgarage.com/" title="FC Garage by Francesco Cirillo">Francesco Cirillo</a> say many times.  Now I understand it a bit better :-)</p>
]]></content:encoded>
			<wfw:commentRss>http://matteo.vaccari.name/blog/archives/670/feed</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Sulla sessione &#8220;Is Software Evolution Really Effective&#8221; di Francesco Cirillo</title>
		<link>http://matteo.vaccari.name/blog/archives/664</link>
		<comments>http://matteo.vaccari.name/blog/archives/664#comments</comments>
		<pubDate>Sun, 20 Nov 2011 17:00:15 +0000</pubDate>
		<dc:creator>matteo</dc:creator>
				<category><![CDATA[Agile]]></category>

		<guid isPermaLink="false">http://matteo.vaccari.name/blog/?p=664</guid>
		<description><![CDATA[Francesco Cirillo ha presentato questa sessione sabato scorso all&#8217;Italian Agile Day. Ho letto su http://joind.in/talk/view/4508 diversi commenti che non mi tornavano; allora ho scritto questa mia personale esegesi, perché penso che il messaggio di FC sia molto importante e mi secca vedere che viene spesso frainteso. Quindi vi do la mia personale interpretazione, senza pretendere [...]]]></description>
			<content:encoded><![CDATA[<p>Francesco Cirillo ha presentato <a href="http://vimeo.com/32527081">questa sessione</a> sabato scorso all&#8217;Italian Agile Day.  Ho letto su <a href="http://joind.in/talk/view/4508">http://joind.in/talk/view/4508</a> diversi commenti che non mi tornavano; allora ho scritto questa mia personale esegesi, perché penso che il messaggio di FC sia molto importante e mi secca vedere che viene spesso frainteso.  </p>
<p>Quindi vi do la mia personale interpretazione, senza pretendere di parlare per Francesco. Fatto: se proviamo a leggere un qualsiasi libro in tema Metodi Agili, si dà per assodato che usando i Metodi Agili si diventa più bravi.</p>
<p>La realtà dei fatti, che ho personalmente riscontrato nelle mie esperienze, è che spesso questo <strong>non è vero.</strong> Diversi team agili di mia conoscenza hanno fallito progetti, o comunque hanno conseguito una fama di essere troppo cari. Fama immeritata? Che importa! Se il risultato finale è che il cliente non ti sceglie più hai fallito. E poi è facile che la fama non sia poi così immeritata.</p>
<p>E&#8217; vero che molte pratiche agili producono un beneficio immediato; quel problema che facevi fatica a debuggare si risolve brillantemente con gli unit test, la comunicazione con il cliente migliora se andiamo a chiedergli che cosa pensa veramente, ecc. ecc. Ma c&#8217;è un grosso <strong>MA</strong>. Ci vuole molta, molta fatica per rendere questi benefici permanenti. E&#8217; sulla distanza che si vede la differenza.</p>
<p>Tanti che credono di programmare a oggetti scrivono invece codice procedurale, e la differenza sulla distanza si traduce in codice ingarbugliato. Tanti che si rifiutano di fare big design upfront, non hanno capito che devono fare invece tanto <strong>design in maniera continua</strong>. E magari non sarebbero in grado di farlo neanche se volessero, il design upfront, né big né small. E poi, ci vuole tanto coraggio per continuare a mantenere un vero contatto con il cliente nel lungo periodo.</p>
<p>Kent Beck ha detto &#8220;What does it mean to be agile? My definition is that you accept input from reality and you respond to it”. Allora facciamola per davvero questa follia di accettare l&#8217;input dalla realtà! Misuriamo quanto ci costa sviluppare. E&#8217; da qui che si vede se quello che facciamo funziona veramente.</p>
<p>E già che ci siamo, da quanto tempo non andiamo dal cliente a chiedergli &#8220;sei contento di come lavoriamo?&#8221;</p>
<p><strong>Update 2011/12/11: updated link to HD video</strong></p>
]]></content:encoded>
			<wfw:commentRss>http://matteo.vaccari.name/blog/archives/664/feed</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Fixing session management in Tomcat</title>
		<link>http://matteo.vaccari.name/blog/archives/650</link>
		<comments>http://matteo.vaccari.name/blog/archives/650#comments</comments>
		<pubDate>Wed, 26 Oct 2011 21:03:35 +0000</pubDate>
		<dc:creator>matteo</dc:creator>
				<category><![CDATA[Agile]]></category>

		<guid isPermaLink="false">http://matteo.vaccari.name/blog/?p=650</guid>
		<description><![CDATA[Sessions are the Achilles heel of every application server. Michael T. Nygard, Trampled By Your Own Customers (pdf) Earlier this year I started a big Java development project with my team. I did mostly Rails development for a long time, so when I came back to Web applications in Java I had some expectations. I [...]]]></description>
			<content:encoded><![CDATA[<blockquote><p>
  Sessions are the Achilles heel of every application server.<br />
  <cite>Michael T. Nygard, <a href="http://pragprog.com/book/mnee/release-it">Trampled By Your Own Customers</a> (<a href="http://media.pragprog.com/titles/mnee/mnee-story2.pdf">pdf</a>)</cite>
</p></blockquote>
<p>Earlier this year I started a big Java development project with my team.  I did mostly Rails development for a long time, so when I came back to  Web applications in Java I had some expectations.  I expected that Tomcat would treat user sessions in much the same way as Rails does; but it doesn&#8217;t.</p>
<p><span id="more-650"></span></p>
<p>A bit of background.  In a RESTful web application, all session data is maintained in the memory of clients, and nothing at all is saved in server-side sessions.  In a well-written web application you might want to save just a few bytes on the server; ideally you should save no more than the id of the authenticated user.  On the other hand, poorly-written application and frameworks tend to save lots of data in server-side sessions.</p>
<p>In a Rails application, there are essentially three ways to implement session data:</p>
<p>a) in encrypted cookies, which are entirely client-side;</p>
<p>b) in server-side files;</p>
<p>c) in a database table.</p>
<p>In a single-server application you might want to use a) for maximum efficiency, or b) to avoid the risk of someone tampering the cookies (not easy to do; it is necessary to steal the encryption key.)  In a multi-server application you might choose a) for maximum efficiency, or c) for added security.</p>
<p>Now let me clarify this: servers-side sessions in a database table are extremely efficient.  Most web applications make dozens of database queries per page view; adding one or two simple queries for getting the session data will *not* add a significant overhead.  </p>
<p>This was my point of view when I came from Rails to Java again.  Now we are writing an application that will run on Tomcat, and I was expecting that Tomcat, being an established product, would offer similar functionality; but it does not.</p>
<p><center><br />
    *<br />
  *&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*<br />
</center></p>
<h3>Tomcat options</h3>
<p>When it comes to session management, Tomcat offers three options:</p>
<p>i) The standard session manager, that keeps sessions in the Java heap.</p>
<p>ii) The &#8220;persistent&#8221; session manager, that keeps sessions in the Java heap and  and might swap &#8220;inactive&#8221; sessions on file or on a database.</p>
<p>iii) The &#8220;clustering&#8221; session manager, that keeps sessions in the Java heap and keeps them synchronized with other instances of Tomcat using a custom protocol over TCP.  In order to cater for the needs of poorly-written applications that save lots of data in sessions, this manager has a sophisticated algorithm for moving &#8220;deltas&#8221; of session data instead of moving full session contents.</p>
<p>At first I thought that I could use option ii) to replicate the functionality of Rails option c).  But <a href="http://www.reinwaldwarapen.com/2011/01/storing-and-sharing-sessions-among.html" title="Inside the mind of Reinwald Warapen: Storing and Sharing Sessions among standalone Tomcat instances">it turns out that it&#8217;s not possible</a>; the &#8220;persistent&#8221; session manager insists that sessions are saved to disk in batches, not individually.  This means that there is no guarantee that users will not lose their session, if they click quickly from a page to another.</p>
<p>I briefly considered option iii), but it requires to open new TCP ports.  For my application, this would require complex firewall adjustments, since our servers are located in different geographic locations.  I would feel like a stupid to ask people in Operations to open this many holes in their firewalls.  And I would not bet a dime on the security implications.  Besides, the whole concept seems a hugely complicated way to do stuff that is best left to specialized services like memcached.  The fact that the whole thing is optimized for poorly-written applications makes me like it even less.</p>
<p>In addition, all three options store session data in the Java heap.  This is an incredibly bad idea.  Memory is the most important resource for a Java application.  You don&#8217;t want to waste Java heap memory for session data that will be used at best once every few minutes, and at worst will never be needed again.  Doing this means that memory usage will grow linearly with the number of sessions, and most of that memory will be unused for most of the time.  As a consequence, we will be forced to set a maximum number of concurrent users.  </p>
<p>A RESTful application, on the other hand, will not waste memory on sessions, so its memory consumption will depend on the number of concurrent *accesses*, not sessions.  The application only allocates the memory it needs to fulfill the requests it is currently serving, and <em>no more</em>.  As a result, a RESTful application can handle many more concurrent requests, all other things being equal.</p>
<p>I can imagine that the reasoning behind the Tomcat session managers is that keeping sessions in memory is &#8220;more efficient&#8221;.  For most common applications, this reasoning is wrong.  For a scalable (and robust) application, the efficiency that matters most is memory efficiency; adding a few milliseconds of latency per request does not matter.  Tomcat reminds me of what <a href="https://www.varnish-cache.org/trac/wiki/ArchitectNotes">this very good article</a> calls &#8220;1975 programming&#8221;; adding complications when the simpler algorithm would be much better.</p>
<h3>Conclusion</h3>
<p>In conclusion, how do I think I will solve the problem with Tomcat?  I could write my own session manager; but that requires to interact with complex interfaces that I&#8217;m not confident to be able to understand correctly in a short time.  I could use one of the several alternative session managers that are based on <a href="http://code.google.com/p/memcached-session-manager/" title="Tomcat high-availability clusters with memcached">alternative</a> <a href="http://jbrisbin.com/web2/articles/tomcat-session-manager-backed-by-riak/" title="Tomcat Session Manager backed by Riak | jbrisbin.com">stores</a>; but I don&#8217;t really need to save milliseconds on latency, and I don&#8217;t want to install new services, and what&#8217;s more important I don&#8217;t know how reliable these things are.</p>
<p>The solution I decided to use is to roll my own session management in the application.  I will apply to all requests a filter that does the following:</p>
<ol>
<li>Look for a session cookie.  If it&#8217;s missing, redirect to the authentication page; otherwise find the session id in the cookie and use it to fetch session data from the database.</li>
<li>If the session data is not found or if it&#8217;s expired, then redirect to the authentication page.</li>
<li>Otherwise find the id of the authenticated user in the session.</li>
</ol>
<p>The authentication page asks the user for credentials; if they are correct, then it</p>
<ol>
<li>Generates a session id using a secure random number generator;</li>
<li>save the session id in a cookie;</li>
<li>save the user id in the database.</li>
</ol>
<p>It&#8217;s simple and very efficient.  There&#8217;s not much more needed.  This scheme has a nice property: it only creates a session for users who supplied valid credentials.  This avoids the problem of <a href="http://pragprog.com/book/mnee/release-it">generating lots of useless sessions for requests coming from search engines</a>.  It&#8217;s also more secure, because it makes it much more difficult for a sophisticated attacker to guess existing session numbers.  This is better than what most application servers do :-)</p>
<p>Another nice property is that session data never changes.  The only thing we store in it is the user id, and there is no way or reason for it to change.</p>
]]></content:encoded>
			<wfw:commentRss>http://matteo.vaccari.name/blog/archives/650/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>On knowing what you&#8217;re doing</title>
		<link>http://matteo.vaccari.name/blog/archives/645</link>
		<comments>http://matteo.vaccari.name/blog/archives/645#comments</comments>
		<pubDate>Sun, 09 Oct 2011 19:12:17 +0000</pubDate>
		<dc:creator>matteo</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[essay]]></category>

		<guid isPermaLink="false">http://matteo.vaccari.name/blog/?p=645</guid>
		<description><![CDATA[I&#8217;d like to share this quote from E.W.Dijkstra: When the design of the THE Multiprogramming System neared its completion the University&#8217;s EL X8 was getting installed, but it had not been paid yet, and we hardly had access to it because the manufacturer had to put it to the disposal of an American software house [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;d like to share this quote from E.W.Dijkstra:</p>
<blockquote><p>
When the design of the THE Multiprogramming System neared its completion the University&#8217;s EL X8 was getting installed, but it had not been paid yet, and we hardly had access to it because the manufacturer had to put it to the disposal of an American software house that was supposed to write a COBOL implementation for the EL X8. They were program testing all the time, and we let it be known that if occasionally we could have the virgin machine for a few minutes, we would appreciate it. They were nice guys, and a few times per week we would get an opportunity for our next test run. We would enter the machine room with a small roll of punched paper tape, and a few minutes later we would leave the machine room with the output we wanted. I remember it vividly because when they realized what we were achieving, our minimal usage of the machine became more and more frustrating for them. I don&#8217;t think their COBOL implementation was ever completed.<br />
<cite><a href="http://www.cs.utexas.edu/~EWD/index13xx.html">EWD1303</a>,  <em>My recollections of operating systems design</em></cite>
</p></blockquote>
<p>I can picture Dijkstra and his collegues working with paper and blackboards and thinking hard about how they were writing their software.  They came into the room and their software <strong>just worked</strong>.  And I can picture the Cobol crew in a furious vicious circle of code-and-fix; their growing frustration and despair. That was about 1960: no books on software design existed back then. For that matter, no books on compiler writing existed either.  </p>
<p>Could the Cobol crew have done better? Absolutely. In 1954, the FORTRAN team led by <a href="http://en.wikipedia.org/wiki/John_Backus">John Backus</a> produced a compiler that reportedly wrote code almost as good as hand-written.  How could the poor Cobol crew have done something as good or at least good enough?</p>
<p>My answer: by <em>designing</em> their software. By breaking the thing into parts (modules) and developing each one separately. By using analogies from other engineering disciplines; by using metaphors.  I know this is all obvious to us in 2011 as we all know about module decomposition and the use of metaphors and coupling and cohesion.  But is it really obvious?  Really?</p>
<p>What I see is that modern-day software teams today can *still* be divided in two kinds: the Dijkstra-crew kind and the Cobol-crew kind.  Those who are in control and produce reasonably good software within reasonable resources and whose code is reasonably clean;  and those who toil away late hours and produce late and buggy software, with no design, or perhaps with an ineffective, we-dont-really-believe-in-it design and crappy code.</p>
<p>Which do you want to be?  What will you do to become it?</p>
]]></content:encoded>
			<wfw:commentRss>http://matteo.vaccari.name/blog/archives/645/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Clearing some misunderstandings about TDD</title>
		<link>http://matteo.vaccari.name/blog/archives/642</link>
		<comments>http://matteo.vaccari.name/blog/archives/642#comments</comments>
		<pubDate>Sat, 08 Oct 2011 14:32:09 +0000</pubDate>
		<dc:creator>matteo</dc:creator>
				<category><![CDATA[Agile]]></category>

		<guid isPermaLink="false">http://matteo.vaccari.name/blog/?p=642</guid>
		<description><![CDATA[Great post: http://codebetter.com/iancooper/2011/10/06/avoid-testing-implementation-details-test-behaviours Re-reading Kent Beck&#8217;s TDD book, Ian Cooper recovers some important things that are often overlooked.]]></description>
			<content:encoded><![CDATA[<p>Great post:</p>
<p><a href="http://codebetter.com/iancooper/2011/10/06/avoid-testing-implementation-details-test-behaviours">http://codebetter.com/iancooper/2011/10/06/avoid-testing-implementation-details-test-behaviours</a></p>
<p>Re-reading Kent Beck&#8217;s TDD book, Ian Cooper recovers some important things that are often overlooked.  </p>
]]></content:encoded>
			<wfw:commentRss>http://matteo.vaccari.name/blog/archives/642/feed</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

