<?xml version="1.0" encoding="ISO-8859-1"?>
<rss version="2.0">
  <channel>
    <title>Purple Blog</title>
    <link>http://purpletech.com/blog/</link>
    <description>Alex Chaffee's Purple Blog</description>
    <!-- optional tags -->
    <language>en-us</language>           <!-- valid langugae goes here -->
    <generator>Nucleus CMS v3.22</generator>
    <copyright>Â©</copyright>             <!-- Copyright notice -->
    <category>Weblog</category>
    <docs>http://backend.userland.com/rss</docs>
    <image>
      <url>http://purpletech.com/blog//nucleus/nucleus2.gif</url>
      <title>Purple Blog</title>
      <link>http://purpletech.com/blog/</link>
    </image>
    <item>
 <title><![CDATA[Rails / lighttpd gotcha: AJAX stalling? Check your Content-Length header]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=43</link>
<description><![CDATA[So neither Ruby on Rails nor lighttpd set the Content-Length header in HTTP
responses on their own. That means that the browser doesn't know when
it's gotten the whole response, so it has to keep the connection open
in case more bytes come down. In normal web usage this doesn't cause a
problem (*) since browsers are smart enough to display partial
results. But for AJAX responses it means that, sometimes (**) the
onComplete handler (***) doesn't get called for over a minute. The onInteractive handler gets called quickly, but that doesn't help, since usually you do stuff during onComplete when you're guaranteed to have the full response.
<p>
Here's the fix in Rails. Put the following in your application.rb:
<p>
<pre>
 after_filter :set_content_length

 def set_content_length
   @response.headers['Content-Length'] = @response.body.length
 end
</pre>
Anyone who wants to fix the above to check for an existing
content-length, be my guest :-)
<p>
(**) The stalling happens sporadically, not sure with what pattern. In
one app we saw it maybe one in 5 requests; some of those were actually HTTP requests so the 
<p>
(*) Occasionally the page will be fully visible but the cursor will
still be a pointer-plus-spinning-hourglass. And this may cause
performance problems in high-volume sites.
<p>
(***) onInteractive and onComplete are prototype.js event callbacks; the corresponding standard XMLHttpRequest "ready states" are  INTERACTIVE and COMPLETE; "ready state" is a parameter to the onReadyStateChange callback.
<p>
(****) Apache is nice enough to tack on a proper Content-Length for you, so if you're running behind Apache you're safe from this problem.
]]></description>
 <category>General</category>
<comments>http://purpletech.com/blog/index.php?itemid=43</comments>
 <pubDate>Mon, 15 May 2006 08:39:20 -0700</pubDate>
</item><item>
 <title><![CDATA[Trapped in the Closet]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=42</link>
<description><![CDATA[You've probably done this a thousand times:

<pre>
private Map<String, Foo> foos = new HashMap<String, Foo>();

public void getFoo(String key) {
  synchronized (foos) {
    Foo foo = foos.get(key);
    if (foo == null) {
      foo = new Foo(key);
      foos.put(key, foo);
    }
    return foo;
}
</pre>

If two threads are both trying to get the same item before it exists, the first one 
will create it, and the second one will block until it's ready.  (I've heard of the
dreaded 
<a href="http://www-128.ibm.com/developerworks/java/library/j-dcl.html">double-checked locking</a> conundrum, but I believe that if I close my eyes, plug my ears
and say "nah nah nah" then it will never happen.)
<p>
This is a common enough creation pattern.  So common, in fact, that it feels
like there should be a type of Map that does it for you.  Well, now there is :-)
Christian and I call ours a Closet -- I suppose it's sort of a magic closet that
creates things for you if they're not hanging in there already.
<p>
<pre>
private Closet<String, Foo> foos = new Closet<String, Foo>() {
  protected Foo create(String key) {
    return new Foo(key);
  }
};

public Foo getFoo(String key) {
  return foos.get(key);
}
</pre>

<p>
Much nicer, But wait, we're not done! There's a problem with this design 
in a world where create() takes a long time. 
(We came across it while trying to cache Lucene IndexReaders.) 
If two concurrent threads try to get *different* items, and the first one hasn't been created yet,
then the second thread will block even though its item is ready and waiting.
<p>
We arrived at a fairly elegant solution to this problem, but the more interesting part 
was writing the tests first. Writing a unit test for a concurrency problem is always annoying. It's tempting
to spawn a bunch of threads and then use sleep() either from your tests or from overridden methods,
but that will make your tests slow, and even then they don't always work consistently.
<p>
It's better to model your tests either to *simulate* multiple threads, or to actually spawn threads but keep
a tight reign on them.  The subordinate test threads do a few things, then wait for the main test thread to 
tell them to proceed.  That keeps the logic in your main test clean and simple, like a script for a play
with several characters -- Joe does this, Bob says that, Joe walks there, Jane enters stage left.
<p>
Now all we need to do is add expiration logic and we've turned our Closet into a cache.
<p>
(Full code is unavailable for the moment, sadly... stay tuned.)
]]></description>
 <category>General</category>
<comments>http://purpletech.com/blog/index.php?itemid=42</comments>
 <pubDate>Mon, 15 May 2006 08:32:14 -0700</pubDate>
</item><item>
 <title><![CDATA[JSLint]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=41</link>
<description><![CDATA[I've been doing a lot of JavaScript (and a lot of cursing) lately. Edward pointed me to <a href="http://jslint.com/">JSLint</a>, which checks the syntax and style of your JS code. I think it's too strict (but it's supposed to be) but I do recommend reading the <a href="http://jslint.com/lint.html">documentation</a> -- the explanations of /why/ JSLint complains are clear and insightful. 


For instance:
<blockquote>
The == and != operators do type coercion before comparing. This is bad because it causes '' == 0 to be true. This can mask type errors.
<p>
When comparing to any of the following values, use the === or !== operators, which do not do type coercion.
<p>
0 '' undefined null false true
<p>
If you want the type coercion, then use the short form. Instead of
<p>
(foo != 0)
<p>
just say
<p>
(foo)
<p>
and instead of
<p>
(foo == 0)
<p>
say
<p>
(!foo)
</blockquote>

See http://jslint.com/lint.html and http://www.jslint.com/
<p>

There's also a command-line version which could be used in a continuous build (though I'd recommend we're careful deciding which checks to activate).

P.S. "JSLint is less anal than the sycophantic conformanity demanded by XHTML, but more strict than the popular browsers." That's my favorite sentence I've read all week.
]]></description>
 <category>Code</category>
<comments>http://purpletech.com/blog/index.php?itemid=41</comments>
 <pubDate>Fri, 28 Apr 2006 07:37:28 -0700</pubDate>
</item><item>
 <title><![CDATA[Language Elegance]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=40</link>
<description><![CDATA[Keith Braithwaite waxes objective in <a href="http://peripateticaxiom.blogspot.com/2006/04/keywords-magic-and-edsls.html">peripatetic axiom: Keywords, Magic and (E)DSLs</a> -- he gives a pretty good high-level introduction to Smalltalk and what language simplicity really means.  He makes the point that Java isn't really object-oriented -- or rather, as I like to put it, 
<blockquote>
Java is object-oriented, in that it's kind of oriented <b>towards</b> objects, from afar.
</blockquote>
<p>
There's something beautiful and elegant about a system with as few rules as necessary to get the job done. Java and, sadly, Ruby, overcomplicate life with bifurcations and exceptional cases and defaults and other magic.  Only Smalltalk and Scheme reach the level of elegance I'm talking about -- a very small number of rules from which you can derive the universe of software.
<p>
(Keith's example is that <code>if</code>, a part of the grammar of any C-style language, is actually implemented as a method of the class Boolean. It takes two blocks as parameters; the concrete Boolean subclass True executes the first and False executes the second.)
<p>
And no, I'm not advocating a return to assembly language, although the simplicity of stack- and register-based programming approaches what I'm talking about. In Java there's at least two ways to do so many things.  There are primitives *and* objects. There are statics *and* instance members. There are Arrays and ArrayList. There are final classes (like String) and regular ones.  And each of these pairs has different semantics, and you keep getting tripped up over things you can and can't do.
<p>
Ruby's a little better, in that everything's an object -- oh wait, unless it's a mixin (aka module). Which means that if someone decided to implement some stuff as a mixin, and you want to override it, you can't use "super", you have to declare an alias and call it. And everything following a method name is a parameter, unless it kind of looks like a hash, in which case it's all one parameter, unless it looks like a block, in which case it's the "default block".
<p>
My point is, if you remove rules rather than adding them, there's a chance you'll turn Chess into Checkers. But there's also a change you'll reach Go.
]]></description>
 <category>General</category>
<comments>http://purpletech.com/blog/index.php?itemid=40</comments>
 <pubDate>Sun, 9 Apr 2006 21:14:55 -0700</pubDate>
</item><item>
 <title><![CDATA[Save Considered Harmful]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=39</link>
<description><![CDATA[<a href="http://hirevito.com/greasemonkey/humanegmailautosave.html">Humane Gmail Autosave</a> solved one of the many problems with the so-called text editor in which I spend most of my time these days.  Or rather, in which I often type some stuff, then get distracted into a different task or tab and let it sit for hours. Thankfully gmail does autosave by default now, making this extension unnecessary, though it'd be nice to crank the frequency up to once per second or once per keystroke or something.
<p>
Why, in this day and age, is there even a Save command in any application? Its very presence implies -- indeed, guarantees -- that <b>the default state of the world is unsafe</b>. This breaks the rule our ancestors learned over billions of years of interaction with the objective world: <b>when you do something, it stays done, until undone.</b>
<p>
I have agreed for decades with the following sentiment:

<blockquote>
"...[The] user should never have to explicitly save or store work. The system should treat all produced or acquired data as sacred and make sure that it does not get lost, without user intervention. The user may, of course, deliberately delete anything. The ability to delete (or make any changes) means that universal, unlimited-level undo and redo should be inherent to all systems."
 - <a href="http://jef.raskincenter.org/humane_interface/summary_of_thi.html">
Jef Raskin, The Humane Interface</a>
</blockquote>

To Raskin's paragraph I would add that for documents, instead of "Save" should be "Mark" and "Revert To Mark". We could also use a "Publish" to allow you to strip out the undo history so your readers don't get to see all your second-guessing.
<p>
A dialog box in which you're editing existing data should update immediately, and have a "Revert" 'button which puts things back to how they were when you opened the dialog.  A dialog box in which you're constructing brand new stuff is temporary, so in that case there could be a "Save" button (or, better, "Create"). But it'd be great if instead, it made a new, persistent "proposal" or "draft" for the item, so it would still be there if the power went out.
]]></description>
 <category>General</category>
<comments>http://purpletech.com/blog/index.php?itemid=39</comments>
 <pubDate>Sat, 1 Apr 2006 19:27:56 -0800</pubDate>
</item><item>
 <title><![CDATA[JavaScript and Ruby support in IDEA]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=38</link>
<description><![CDATA[In addition to Ruby, I've been doing a lot of JavaScript programming lately, and I've just moved from <a href="http://www.purpletech.com/blog/?itemid=29">Eclipse</a> to 
<a href="http://intellij.com">IntelliJ IDEA 5.1</a>. Their new JavaScript plugin works like a dream. It makes me hope for an IDEA Ruby plugin.
<p>
Here's a short list of what works:
<ul>
<li>Shift-F6 - Rename classes, methods, variables
<li>Renaming a file searches references and changes them (e.g., script tags in jsunit test files)
<li>Dot completion, Ctl-Space - gives you a list of all methods, and narrows down.
<li>F4 / Ctl-B / Ctl-Click - go to the definition of the method or class you're looking at
<li>Ctl-Shift+Alt+N - search across all JS files for any variable, class, constant, method, or other symbol. Goes to to the definition when you hit enter.
<li>Ctl-Shift-N - go to file (equivalent of Ctl-Shift-R in Eclipse)
<li>Ctl-F12 - jump to a class or method in your current JS file
<li>Red syntax error squigglies - You know how you're run jsunit all those times where it just freezes because you have a syntax problem? Steve and I have gone 5 days without having that problem. I expect we won't see that again for some time.
<li>Alt-F7, on classes and methods - Find usages. YAY.
<li>Ctl-Alt-L - apply code style (reformat)
<li>Ctl-Shift-V - multi-level paste
</ul>

Now, a few things are a little rough -- e.g., Rename is a bit aggressive, so I've started doing Preview to make sure it doesn't delve into libraries when I'm renaming symbols with popular names like "execute" or "element". And sometimes it's a bit too liberal in its autocomplete suggestions. But overall it's fantastic. This vast success gives the lie to the common wisdom that you can't build good refactoring support for a dynamic language.
<p>

So now it seems Sixth and River may make a Ruby plugin for IDEA. See <a href="http://sixthandredriver.typepad.com/river_of_code/2006/01/ruby_in_idea_.html">River of Code: Ruby in IDEA?</a>.  Let's flood their blog post with "me too"s to get them in the mood.

]]></description>
 <category>Code</category>
<comments>http://purpletech.com/blog/index.php?itemid=38</comments>
 <pubDate>Sat, 1 Apr 2006 18:23:56 -0800</pubDate>
</item><item>
 <title><![CDATA[JavaScript and CSS Versioning in Rails]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=36</link>
<description><![CDATA[To defeat browser caching for static files that actually do change once in a while, a common trick is to append a random number to the URL:
<pre>&lt;link href="/css/mysite.css?9238238" rel="stylesheet" type="text/css"&gt;</pre>
If you use a truly random number (or the current time), it will reload every time. However, this is not exactly what you want; instead, you only want it to reload when the file has changed, and use the cached version when it hasn't. A good way to do this is to use the timestamp of the time the file was last modified.
<p>
Here's an easy way to do this in Ruby on Rails.Use the standard Rails helper functions stylesheet_link_tag and javascript_include_tag (which reference static files inside the 'public' directory):
<pre>
  &lt;%= stylesheet_link_tag 'mysite' %&gt;
  &lt;%= javascript_include_tag "prototype" %&gt;
</pre>
Then add the following methods into your application_helper.rb:
<pre>
 def javascript_path(js_file)
   versioned_path(super)
 end

 def stylesheet_path(css_name)
   versioned_path(super)
 end

 def versioned_path(path)
   if (path.include?("http://"))
     path
   else
     timestamp = File.mtime(File.join(RAILS_ROOT, "public",
path)).strftime("%Y%m%d%H%M%S")
     path + "?#{timestamp}"
   end
 end
</pre>
That's it!
]]></description>
 <category>Code</category>
<comments>http://purpletech.com/blog/index.php?itemid=36</comments>
 <pubDate>Tue, 21 Feb 2006 22:22:28 -0800</pubDate>
</item><item>
 <title><![CDATA[Real Lessons for Rails Deployment]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=35</link>
<description><![CDATA[<blockquote><div>"Bottom Line: If you can, use Lighty. The fact that it's now used by script/server when installed means that lots of other people are looking at it all of the time and that any problems with it will be addressed rapidly. If you need Apache's mod_rewrite or any other of its fabulous arsenal of modules, or simply have to use Apache because that's the corporate line, use Apache httpd 2.0.x if at all possible. And, if you're going to use Lighty, be sure not to use config/lighttpd.conf to stash your production configuration. I used to stash my production lighttpd configuration there, but then the built in script/server commmand introduced in Rails 0.14.something-or-other didn't work so nicely. So now I let Rails create the config/lighttpd.conf file and I stash my production configuration somewhere else."</div></blockquote>
<a href="http://duncandavidson.com/essay/2005/12/railsdeployment">Real Lessons for Rails Deployment</a>]]></description>
 <category>Links</category>
<comments>http://purpletech.com/blog/index.php?itemid=35</comments>
 <pubDate>Sat, 18 Feb 2006 19:30:24 -0800</pubDate>
</item><item>
 <title><![CDATA[Getting Started With ActiveRecord Migrations]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=34</link>
<description><![CDATA[<a href="http://jamis.jamisbuck.org/articles/2005/09/27/getting-started-with-activerecord-migrations">Getting Started With ActiveRecord Migrations</a>]]></description>
 <category>Links</category>
<comments>http://purpletech.com/blog/index.php?itemid=34</comments>
 <pubDate>Sat, 18 Feb 2006 19:14:55 -0800</pubDate>
</item><item>
 <title><![CDATA[Ruby on Rails Cheat Sheet]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=33</link>
<description><![CDATA[<a href="http://www.ilovejackdaniels.com/ruby-on-rails/ruby-on-rails-cheat-sheet/">Ruby on Rails Cheat Sheet - Ruby On Rails - ILoveJackDaniels.com</a>]]></description>
 <category>Links</category>
<comments>http://purpletech.com/blog/index.php?itemid=33</comments>
 <pubDate>Sat, 18 Feb 2006 19:14:35 -0800</pubDate>
</item><item>
 <title><![CDATA[Eclipse Am Bizarro IDEA]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=29</link>
<description><![CDATA[
I've been using Eclipse again, after a blissful 2-year leave of absence from Bizarro World. I thought it would be appropriate to repost my classic 
<a href="http://sourceforge.net/developer/diary.php?diary_id=10772&diary_user=258611">"Eclipse Am Bizarro IDEA"</a>
rant from a few years back... (below the fold).
<p>
BTW, in the meantime I've discovered many other UI and feature decisions where the Eclipsers chose... poorly. For example:
<ul>
<li>There's no checkbox for "blessing" a Run configuration as a favorite in the Run settings dialog. Instead you have to close that dialog, click on the stupid "ha ha I'm really a separate menu even though I look like a little 8-pixel triangle" "button" next to the big green play button, select "Organize Favorites...", click "Add", scroll through a list of items that are selectable, but don't actually <b>select</b> the one you want -- instead, click on the checkbox next to it in the list -- then click "OK". Twice.</li>
<li><a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=33193">Double-click-and-drag selection</a> still doesn't work; nor does triple-click to select a line.</li>
<li>The list of search results don't actually show the results, but just the files in which there were results. And there's no keystroke for showing the next result. These two factors combined means that it's easy to click on a "result", look at it, then click on the next "result" and accidentally skip over several hits from the earlier file. The "proper" behavior is to move your mouse all the way across the panel to the down-arrow "button" (again, one that <b>doesn't look like a button</b> since it doesn't have button-like
<a href="http://www.joelonsoftware.com/uibook/chapters/fog0000000060.html">affordances</a> 
(a visible border inside which you click)).</li>
<li>Activating the test runner with Ctl-F11 doesn't update the screen layout to show you the test runner if your current window is maximized (for which, thank Zeus, they now have a keystroke (Ctl-M)). This encourages you to hit Ctl-F11 again, which <b>totally breaks</b> the test runner since it doesn't support multiple simultaneous test runs yet does nothing to prevent you from starting multiple simultaneous test runs.</li>
<li>Version diffing (from Local History or Repository) is incomprehensible. There are two options -- "Compare with" and "Replace with". They apparently differ only by the presence of a "Replace" button. Why not just have "Replace" be a feature of "Compare"? In the "Replace" window, if you accidentally hit "Enter", the default action is not the expected "Show me the selected version," but is "Replace", which astonishingly replaces your whole file and then closes the window really quickly so you're like, "What the heck just happened?"</li>
<li>In Eclipse, certain editor keystrokes (ctrl-J, ctrl-K, etc.) only work in certain "perspectives" or "editor types" or whatever the heck modal madness they call it. In contrast, in IDEA, they went the opposite direction, actually making cool features like control-space work inside dialog boxes. Eclipse is shifting sand... you never know what you can do or how you can get it done.</li>
</ul>

I'll probably update this list as more frustrations occur to me.  Read More for the original Bizzaro essay...

Date: 2002-11-19 20:03 
<p>
Last night Erik and I decided that Eclipse is like Bizarro
IDEA. You remember 
<a href="http://en.wikipedia.org/wiki/Bizarro">Bizarro</a>
 -- he idolized Superman, but was an imperfect duplicate.
<p>
Eclipse and IDEA seem to be tracking each other's features,
but everything they both do, Eclipse gets wrong somehow.
<p>
"Me am Bizarro IDE! Me require many more keystrokes than
puny IDEA!"
<p>
"Me have lots more clutter on screen! More icons am better!"
<p>
"IDEA only allow one project open at a time. More am better!
Bizarro IDE open *all* projects all the time! Bizarro IDE do
everything on everything, all the time!"
<p>
"Bizarro middle finger am *much* stronger from all the
right-clicking!"
<p>
On that last point -- I have a feeling that Erich Gamma
writes entire applications solely via right-clicking. No
typing, not even any left-clicking. Pretty much any
interface *other* than right-clicking seems like an
afterthought in Eclipse.
<p>
Then there are the menus which appear and disappear randomly
depending on context; the "global search" with a dozen
options but no "global search *and replace*"; the fact that
you can't see what the keyboard shortcuts are for any of the
menu items until you press ALT, and that you can't see any
keyboard shortcuts in the tooltips for any icons; the common
operations that in IDEA are a single keystroke that in
Eclipse are 3 or 4; the strange names for things ("Team"
instead of "Version Control"; Perspectives and Views and
Workspaces and Workbenches and...)
<p>
IDEA's UI seems to work because (a) it was used by the
people that wrote it, and (b) the people that wrote it work
like I do. Eclipse seems to be more oriented towards
uml-diagramming/right-clicking/visual-debugging/code-browsing
types; me, I type my code, and I read source files, not
hierarchical trees. IDEA always seems to think ahead and
automate things I'm *actually* about to do, not force me to
stop what I'm doing and go right-click on something else to
get the 8 different options for doing something else.
<p>
That said, since I found F3 and figured out what
(multi-step) keystrokes
activate the refactorings, Eclipse is now perfectly tolerable.]]></description>
 <category>Code</category>
<comments>http://purpletech.com/blog/index.php?itemid=29</comments>
 <pubDate>Sun, 12 Feb 2006 09:11:23 -0800</pubDate>
</item><item>
 <title><![CDATA[Life Without Getters]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=25</link>
<description><![CDATA[<font size="+1">Q:</font> What's the first rule of Object-Oriented Design?
<p>
<font size="+1">A:</font> Put the behavior with the data.
<p>
Now, this may seem to be a simple enough rule. But if that's so, why do I keep seeing code like this?

<pre>foo.getBar().getBaz().process(getBar().getBaf())</pre>

"Oh, that's just a violation of the 
<a href="http://www.cmcrossroads.com/bradapp/docs/demeter-intro.html">Law of Demeter</a>,
which isn't really a law anyway, more like a suggestion." you might say. 
<p>
or this?
<pre>
@iterations.each do |iteration|
  velocity = 0
  iteration.stories.each do |story|
    if story.feature?
      velocity = velocity + story.velocity
    end
  end
  iteration.total_velocity = velocity
end
</pre>

"Oh, you're just complaining about 
<a href="http://www.purpletech.com/content/index.php?itemid=2">Feature Envy</a>", 
you may complain.
"I hate it when IDEA makes half my code yellow so I turn that option off."
<p>
But I have a dream. I dream of a world without getters. A world where
<a href="http://www.pragmaticprogrammer.com/ppllc/papers/1998_05.html">Tell, Don't Ask</a>
is the law of the land. A world where every reference to instance data is in the class containing that data. Let me be perfectly clear: 
<p>
Every. Single. Reference.
<p>
Inside the Same. Class. As the data.
<p>
A world where in addition to the first rule above, the next four rules are:
<p>
<ol>
<li> Put the behavior with the data.
<li> Not *near* the data... *with* the data.
<li> No, with the *data*.
<li> Yes, even with that data.
<li> Good. Now keep putting the behavior with the data. 
</ol>
<p>
More below the fold...
<p>
In other words, write your programs as a series of isolated, encapsulated objects that send messages to each other but are completely responsible for managing their internal state.
<p>
In this world, every time a variable is referenced, it's either:
<p>
<ol>
<li> a local variable
<li> a parameter to the current function
<li> an instance variable of the current class
<li> a global (boo! hiss!) -- this includes "class variables" and constants which I always try to minimize in any case
</ol>
I've seen sample code like this. I've seen shipped code that approaches this. (Mostly it was written by former Smalltalkers like Ward Cunningham or Rob Mee.) But to my surprise and shame, It occured to me recently that I've never myself written an entire program like this.  Let me repeat my shame:
<p>
I have never yet written an object-oriented program. 
<p>
If you're at all like me, this coding style may strike you as vastly annoying. Like most programmers, I got into this game because I'm goal-oriented. I see a problem, I see a bunch of tools strewn around and I pick them up and use them on my way to the goal. That leads to functional programming. Even 
<a href="http://www1.cs.columbia.edu/~evs/intro/handouts/songModular.html">modular decomposition</a>
is an afterthought -- a necessary one, and one I now do almost immediately by applying
<a href="http://www.refactoring.com/catalog/extractMethod.html">Extract Method</a> 
liberally, but an afterthought nonetheless. True OOD is a real stretch.
<p>
But that's why this is a dream. It's a challenge. Here are some things that may be difficult to do. (If I ever get a chance to do this for real, I'm sure I'll come up with more.)
<p>
<h4>Methods with return values.</h4>
<p>
This is value-judgement land. At some point an object will have to report something about its internal state; when it does, isn't it violating the First Rule and letting its instance data leak out? My advice is, whenever possible, avoid with void: make methods without return values and see if you can accomplish what you want by 
<a href="http://www.pragmaticprogrammer.com/ppllc/papers/1998_05.html">telling, not asking</a>.  
When you can't get around this, make sure it's transforming its instance data in some way.  If all else fails, try to make sure the data you're returning is immutable (or at least doesn't maintain a live pointer back into the original object's internal state). (Returning live objects is especially dangerous when returning collections.)
</p>
<p>
<h4>Rendering.</h4>
<p>
Normally view code is written like this:

<pre>
  public void renderPerson(PrintWriter out, Person person) {
    out.print("&lt;h1>" + person.getName() + "&lt;/h1>");
    out.print("Age: " + person.getAge() + "&lt;br>");
    out.print("Sex: " + person.getSex() == Sex.MALE ? "Male" : "Female" + "&lt;br>");
    out.print("Address: ");
    renderAddress(out, person.getAddress());
  }
</pre>

Leaving aside all nattering about the above code ("Localization! HTML Templates! Dont use + on Strings! Extract a renderSex method! Squawk!") I'm sure you see that this method has 
<a href="http://www.purpletech.com/content/index.php?itemid=2">Feature Envy</a>
since nearly every line refers to "person". But we don't want to just move it to the Person class -- Person is an 
<a href="http://www.c2.com/cgi/wiki?EntityBean">Entity,</a>
not a 
<a href="http://www.c2.com/cgi/wiki?ComponentDefinition">Component,</a>
and it shouldn't know about details of HTML. That would be mixing Model and View and we all agree that's to be avoided.  
<p>
The solution is to use interfaces to make a render method that's HTML-free:
<pre>
class Person {
  public interface Renderer {
    public void renderPerson(String name, Sex sex, Address address);
  }

  public void renderTo(Renderer renderer) {
    renderer.renderPerson(getName(), getSex(), getAddress());
  }
}
</pre>
<p>
Then inside your View layer you write:
<pre>
  class PersonInfoPageRenderer implements Person.Renderer, Address.Renderer {
    PrintWriter out;
    public ToHtmlRenderer(PrintWriter out) { this.out = out; }
    public void renderPerson(String name, Sex sex, Address address) {
      out.print("&lt;h1>" + name + "&lt;/h1>");
      out.print("Age: " + age + "&lt;br>");
      out.print("Sex: " + sex == Sex.MALE ? "Male" : "Female" + &lt;br>");
      out.print("Address: ");
      address.renderTo(this);
    }

    public void renderAddress(String streetAddress, String city, String state, ...) {
      ...
    }
  }

  person.renderTo(new PersonInfoPageRenderer(out))
</pre>

Note that the Address entity exports a renderer interface of its own. You can reuse the same view-specific renderer class if you like.
<p>
Yes, I know this requires more typing. What can I say? 
<a href="http://www.cafepress.com/java_sucks.4396016">Java</a> 
is a verbose language.
<p>
(That reminds me of my favorite joke:
<pre>
Q: Why were the Java programmer's fingers sore?
A: Because Java is a strongly-typed language!
</pre>
Sorry.)
<p>
You could do the same thing in Ruby with fewer lines: just define a "render_person" method and pass in <code>self</code>. 
</p>
]]></description>
 <category>Code</category>
<comments>http://purpletech.com/blog/index.php?itemid=25</comments>
 <pubDate>Sat, 11 Feb 2006 17:30:30 -0800</pubDate>
</item><item>
 <title><![CDATA[Creational Patterns: The Factory Family]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=15</link>
<description><![CDATA[Here's one of my favorite rants: The <a href="http://www.amazon.com/gp/product/0201633612/">Gang Of Four</a> didn't do a very good job at laying out the <a href="http://www.tml.tkk.fi/~pnr/Tik-76.278/gof/html/">"Creational Patterns"</a>. Their timing was all wrong: they jumped the gun and started with Abstract Factory. This reminds me of the following Steve Martin routine (paraphrased):

<blockquote>I was never good at dating. My timing was all wrong. I'd meet a girl in a bar and say, "Hi, was it good for you too?"</blockquote>

<p>
So here's my take, in proper order, on the progression of patterns for creating an object.

<h4>1. Constructor</h4>
<pre>
new Foo(bar)
</pre>
It should go without saying that the simplest and most straightforward way to create an object is to use its constructor.  (Unfortunately, it often does not, and architects are too eager to open their UML modeling tools and forget how to spell n - e - w ...)
<p>
However, sometimes constructors are too limiting. Maybe there is some initialization that must happen before the object is constructed, or immediately after. Maybe you have lots of constructors with similar or identical parameter lists and you need a series of named methods to distinguish them. In that case, the next step is...

<h4>2. Factory Method</h4>
<pre>
createFoo(bar)
createFooForSomeReason(bar)
createFooForSomeOtherReason(baz)
</pre>

This is good when the caller has some logic around the object creation, either before or after.  You may also want to override the Factory Method in a subclass, allowing polymorphic creation. See <a href="http://gsraj.tripod.com/design/creational/factory/factory.html">this article by Gopalan Suresh Raj</a> for a thorough, if long-winded, discussion.

<h4>3. Static Factory Method</h4>
<pre>
Foo.create(bar)
Foo.createForSomeReason(bar)
Foo.createForSomeOtherReason(baz)
</pre>
If a factory method (#2) is generic enough, it often makes sense to put it as a static method on the object class. Usually if you do this you'll also want to make the constructor private, to force all callers to go through the factory method(s). This ensures consistent access to the object, allows you to apply the Complete Creation principle, and makes your code more readable, since the name of the factory method should describe the scenario (at least more than a bare "new" does).
<p>
This also allows your private constructor to become simpler. A factory method can take care of initialization stuff, and the constructor can take in already set-up objects and stick them in instance variables.
<p>
However, I am growing more and more reluctant to use statics (aka globals) of any kind. It seems to violate Separation of Concerns to put the code for *creating* an object in the same place as the code for *being* that object.
</p>

<h4>4. Factory Object</h4>
<pre>new FooFactory().create(bar)</pre>
<p>
Allows separation of concerns, and consistency between instances of the same class without relying on nasty static variables. Use this if constructing the factory itself is cheap. 
</p>
<p>
Note that most OO languages, in moving the factory into a separate class you give up the power to access private members of the created class. This may mean you have to refactor the target object to expose a public (or package- or friend-accessible) method to do initialization.
</p>
<p>
It's a simple step from here to #6, a Dependency-Injected Singleton factory.
</p>

<h4>5. Static Singleton Factory Object</h4>
<pre>FooFactory.getInstance().create()</pre>
<p>
Using a singleton gives you a common entry point for creating objects across your application.  That means you can do tricks like caching, instance pooling, referential integrity checking and maintenance, etc.
</p>
<p>
Static singletons like this are easy to use since you can always just reach out and find one.  But this is not ideal cause you need static registry and teardown semantics, and it's hard (OK, annoying) to swap out instances at runtime, for instance for tests, without compromising your ability to do multithreading.  Dependency Injection 0wnz0rrz statics of all types (including this one) (see below).
</p>

<h4>6. Injected Singleton Factory Object</h4>
<pre>
getFooFactory().create()
</pre>
<p>
I might get in trouble for calling this a Singleton. The basic idea behind Dependency Injection that when you want something -- any service, like a factory, a repository, a search server, an asynchronous message scheduler -- you just ask yourself for it. You have it already, since in your constructor your client passed it in to you, and you stashed it away in an instance variable.
</p>
<p>
This allows the oxymoronic "multiple singletons" pattern: at any given point there's only one of the things in scope, but there can be many in the same application or VM; in fact, many different instances can be active at the same time. This is great for testability and flexibility.
</p>
<h4>7. Abstract Factory</h4>
<p>
<a href="http://www.developer.com/java/other/article.php/626001">Abstract Factories</a> are aware of the whole hierarchy of possible subclasses of the target object and return the right one for the given use at runtime. A better name might be "polymorphic factory." 
</p>
<p>
It's a pretty heavyweight pattern and a long way from "new". You may never use it. I never have. 
</p>
]]></description>
 <category>Code</category>
<comments>http://purpletech.com/blog/index.php?itemid=15</comments>
 <pubDate>Sat, 11 Feb 2006 12:17:24 -0800</pubDate>
</item><item>
 <title><![CDATA[Computer Science vs. Software Engineering]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=23</link>
<description><![CDATA[Joel on Software has a <a href="http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html">great essay about the "dumbing down" of CS curricula</a> world-wide that happened when they all decided to teach Java instead of C and Scheme. While I believe Java is better than C, they are both terribly flawed languages and teaching them is best left to vocational schools -- or, as Joel says, to the first week on the job for someone who already knows functional programming and pointers.<br />
<br />
A flaw in Java as a pedantic language left unmentioned by Joel is that people who learn Java think that because they've learned a language with some Object-Oriented features that they've also learned OOP/OOA/OOD. No such luck. As I have mentioned before (and will again -- have a draft post on that very topic), OO is hard. As my pal Miško says, <br />
<blockquote>
OO is like teenage sex: everyone <b>says</b> they're doing it, almost nobody <b>is</b> doing it, and those who <b>are</b> doing it aren't very good at it.
</blockquote>
At least with MIT's Scheme curriculum there was no pretense of OO: you're learning data structures, and algorithms, and recursion, and continuations, and you get to fully and deeply learn about each.<br />
<br />
And argh, why do OO teachers do inheritance first thing out of the gate? Inheritance is just delegation plus polymorphism, with some really nasty semantic problems attached (overloading, multiple inheritance, virtual method dispatching, fragile base classes, etc.)...<br />
<br />
]]></description>
 <category>General</category>
<comments>http://purpletech.com/blog/index.php?itemid=23</comments>
 <pubDate>Thu, 29 Dec 2005 22:15:31 -0800</pubDate>
</item><item>
 <title><![CDATA[Refactoring Combo: Extract Method Object]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=22</link>
<description><![CDATA[Let's say you've got a big class with a lot of methods -- a dispatcher or controller, say, that's gotten a bit out of control. The methods are real business methods (or at least they have business logic inside them), but they refer to several different entities, so you're not sure they belong on any given entity.  But you want to get them out of the original class and into domain classes.Moreover, these methods all do things in nearly the same way.  In a controller, for     instance, since they're all responding to different incoming events, they probably     have similar code for handling exceptions, logging, maybe setting up and     committing/rolling back database transactions, etc.  This is a lot of functional    duplication you'd like to <a href="http://c2.com/cgi/wiki?OnceAndOnlyOnce">remove</a>.<br />
<br />
    Sounds like it might be time for a  
<a href="http://c2.com/cgi/wiki?MethodObject">Method Object</a> [which is a step towards the
   <a href="http://c2.com/cgi/wiki?CommandPattern">Command Pattern</a>. In an earlier version of this post I conflated the two, but they're distinct, and I should go revise the draft of the article to match.]
<p>
Usually a Command is used when     you want to encapsulate the doing of something, without actually doing it right away.     But in this case, we'll execute it immediately.  Don't worry, it will carry its own     weight by removing the business logic from the original object, and by being cleaner     and more isolated, and thus more testable.  It will also be set up so that you can     do all the cool Command pattern tricks later if you want, like polymorphic dispatch     or undo.<br />
<br />
    <b>Before:</b>
<pre class="code">
public Money withdraw(int accountNumber, Money amount) throws SessionException {
    try {
        Account account = accountService.findAccount(accountNumber);
        verifyBalance(account, amount);
        account.withdraw(amount);
        return account.getBalance();
    }
    catch (AccountServiceException e) {
        logger.log(e);
        throw new SessionException(e);
    }
}</pre>

    <b>After:</b>

    <pre class="code">
public Money withdraw(final int accountNumber, final Money amount) throws SessionException {
    return new Withdraw(accountNumber, amount, logger, accountService).execute();
}
...
class Withdraw extends AtmCommand&lt;Money&gt; {
    private final int accountNumber;
    private final Money amount;
    private AccountService accountService;

    public Withdraw(int accountNumber, Money amount, Logger logger, AccountService accountService) {
        super(logger);
        this.accountNumber = accountNumber;
        this.amount = amount;
        this.accountService = accountService;
    }

    protected Money doExecute() throws AccountServiceException, SessionException {
        Account account = accountService.findAccount(accountNumber);
        verifyBalance(account, amount);
        account.withdraw(amount);
        return account.getBalance();
    }
}</pre>
<p>
    In <a href="http://www.purpletech.com/articles/combos/extract-command.html">this article</a> on purpletech.com, I will walk through the precise sequence of steps     to perform this refactoring in IntelliJ IDEA (version 5).  There are some pretty     fun keystroke combos you can use to make the whole thing relatively painless     and automated.  (Automating refactorings is better than just typing because it's     less likely to introduce errors, it's got more stable intermediate points so you     can safely stop halfway through, and most of all, because it makes you feel cool.)
</p>
<p>
Full article at: <a href="http://www.purpletech.com/articles/combos/extract-command.html">http://www.purpletech.com/articles/combos/extract-command.html</a><br />
]]></description>
 <category>Code</category>
<comments>http://purpletech.com/blog/index.php?itemid=22</comments>
 <pubDate>Sun, 20 Nov 2005 18:52:00 -0800</pubDate>
</item><item>
 <title><![CDATA[Feature Envy Rule of Thumb]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=21</link>
<description><![CDATA[If you're looking at a method and you see a lot of references to different objects inside it, do the following experiment:<br />
<br />
Make the method static (which means turning the "this" pointer into a named parameter).  Now count the number of times each object is referred to. <br />
<br />
What object is referenced the most? Chances are that it would go better as a method on that object. <br />
<br />
And if you can split it into meaningful chunks, each of which primarily references a different object -- then divide and conquer.<br />
]]></description>
 <category>Code</category>
<comments>http://purpletech.com/blog/index.php?itemid=21</comments>
 <pubDate>Sat, 19 Nov 2005 23:32:57 -0800</pubDate>
</item><item>
 <title><![CDATA[State of Grace]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=20</link>
<description><![CDATA[Need a nice ? I've got a real beaut right under the fold. Barely used, gets great mileage. Here's what it can do for you:<br />
<ul><br />
<li> pull together all sorts of disparate business logicky transitions into one nice, encapsulated, formally complete model<br />
<li> complain loudly when some application logic tries to make an illegal state transition<br />
<li> output itself in <a href="http://www.graphviz.org/cgi-bin/man?dot">DOT</a> format, creating nifty automatic documentation<br />
</ul><br />
<br />
This doesn't <b>quite</b> implement the <a href="http://c2.com/cgi/wiki?StatePattern">State Pattern</a> which, like <a href="http://c2.com/cgi/wiki?StrategyPattern">Strategy</a>, uses polymorphism to let an object change its behavior based on state. Rather, it's a <a href="http://en.wikipedia.org/wiki/Finite_state_machine">Finite State Machine</a>, representing only the <a href="http://www.informit.com/content/images/chap22_0201743973/elementLinks/22fig01.gif">nodes and arcs</a> (states and actions) that make up the legal lifecycle of whatever concept.<br />
<p><br />
By extracting the transition logic into a separate object, we apply <a href="">Separation of Concerns</a> and let the owning object deal with the business of actually verifying whether a transition is desirable, whether other business rules are met, of spawning other processes or notifying listeners, or attaching <a href="http://c2.com/cgi/wiki?CommandPattern">Command</a> objects to perform entry, exit or transition actions. Of course, any of these features (especially notifying listeners) can easily be added to the machine itself, but let's keep it simple for now.<br />
It's straightforward enough to <a href="http://www.refactoring.com/catalog/replaceTypeCodeWithStateStrategy.html">refactor to the full State pattern</a> (also <a href="http://www.informit.com/articles/article.asp?p=28677&seqNum=2">described by Metzger</a>) if and when we want to.<br />
<p><br />
Why would you want to use a state machine in the first place instead of, say, a bunch of booleans, or just smart methods? As <a href="http://www.informit.com/articles/article.asp?p=28677">Metzger says:</a><br />
<br />
<blockquote><i><br />
When you model an object whose state is important, you may find that you have a variable that tracks how the object should behave, depending on its state. This variable may appear in complex, cascading if statements that focus on how to react to the events that an object can experience. One problem with this approach to modeling state is that if statements can become complex. Another problem is that when you adjust how you model the state, you often have to adjust if statements in several methods. The STATE pattern offers a cleaner, simpler approach, using a distributed operation.<br />
</i></blockquote><br />
<br />
But the real reason to use a state machine is social: with a large project, involving many engineers, product managers, QA testers, etc., it's good to have a formal, well-described model for the lifecycles of your objects; using the code below follows the principle of <a href="http://www.artima.com/intv/dry.html">Don't Repeat Yourself</a> by allowing the model, and its representation in actual, executing code, to reign supreme.<br />
<br />
Here's a sample state machine, for tracking the transition from daytime to nighttime and back again, plus an extra terminal node for when the world explodes. (As we all know, Armageddon can only happen at night.) 
 
<pre> 
    enum DayState { 
        DAYTIME, 
        NIGHT, 
        NEVER, 
    } 
 
    enum DayAction { 
        SUNSET, 
        SUNRISE, 
        ARMAGEDDON, 
    } 
 
    class DayMachine extends StateMachine&lt;DayState, DayAction&gt; { 
        { 
            addTransition(DayState.DAYTIME, DayAction.SUNSET, DayState.NIGHT); 
            addTransition(DayState.NIGHT, DayAction.SUNRISE, DayState.DAYTIME); 
            addTransition(DayState.NIGHT, DayAction.ARMAGEDDON, DayState.NEVER); 
        } 
    } 
</pre> 
 
That's all it takes to define a state machine. You can then use it from your domain object code: 
 
<pre> 
    class Day { 
        private DayMachine dayMachine = new DayMachine(); 
        private DayState state = DayState.DAYTIME; 
 
        public void rotate() { 
            if (state == DayState.DAYTIME) { 
                doSunset(); 
            } 
            else if (state == DayState.NIGHT) { 
                state = dayMachine.move(state, DayAction.SUNRISE, DayState.DAYTIME); 
            } 
        } 
 
        public void doSunset() { 
            state = dayMachine.move(state, DayAction.SUNSET, DayState.NIGHT); 
        } 
 
    } 
</pre> 
 
Note that if someone calls doSunset() when it's already night, the machine will throw an exception. Also note the switching conditional in rotate(); this is ripe for refactoring to State Pattern. In that case we'd end up with a different subclass for each possible state, something like:  
 
<pre> 
class Night extends DayState { 
  public DayState sunrise() { 
    return new Daytime(); 
  } 
  public DayState sunset() { 
    throw new InvalidStateTransition("performing sunset on night"); 
  } 
} 
</pre> 
...but there are some tricky OO decisions involved in that process which I won't go into now; suffice it to say that using a state machine accomplishes 60-80% of the power of the State Pattern and is a lot easier to do in Java. (In Smalltalk, OTOH...) 
<p> 
Finally, the <i>coup de grace:</i> the machine can output itself in DOT format: 
<pre> 
digraph day { 
	daytime [label="daytime"]; 
	nighttime [label="nighttime"]; 
	never [label="never"];	 
	daytime -> nighttime [label="sunset"]; 
	nighttime -> daytime [label="sunrise"]; 
	nighttime -> never [label="armageddon"]; 
} 
</pre> 
which produces this pretty diagram: 
 
 
 
<p> 
Without further ado, here's the code, using Java 1.5 generics, and including (naturally) a unit test: 
 
<pre> 
public class StateMachine&lt;STATE extends Enum, ACTION extends Enum&gt; { 
 
    static class Transition&lt;STATE extends Enum, ACTION extends Enum&gt; { 
        STATE from; 
        ACTION action; 
        STATE to; 
 
        public Transition(STATE from, ACTION action, STATE to) { 
            this.from = from; 
            this.action = action; 
            this.to = to; 
        } 
 
        public STATE getFrom() { 
            return from; 
        } 
 
        public STATE getTo() { 
            return to; 
        } 
 
        public ACTION getAction() { 
            return action; 
        } 
    } 
 
    LinkedHashSet&lt;STATE&gt; states = new LinkedHashSet&lt;STATE&gt;(); 
    List&lt;Transition&gt; transitions = new ArrayList&lt;Transition&gt;(); 
 
    public void addTransition(STATE initialState, ACTION action, STATE targetState) { 
        transitions.add(new Transition&lt;STATE, ACTION&gt;(initialState, action, targetState)); 
        states.add(initialState); 
        states.add(targetState); 
    } 
 
    public List&lt;STATE&gt; transitionsFrom(STATE initialState) { 
        List&lt;STATE&gt; targetStates = new ArrayList&lt;STATE&gt;(); 
        for (Transition&lt;STATE, ACTION&gt; transition : transitions) { 
            if (transition.getFrom().equals(initialState)) { 
                targetStates.add(transition.getTo()); 
            } 
        } 
        return targetStates; 
    } 
 
    public STATE move(STATE initialState, ACTION action, STATE targetState) { 
 
        for (Transition&lt;STATE, ACTION&gt; transition : transitions) { 
            if (transition.getFrom().equals(initialState) && transition.getAction().equals(action)) { 
                return transition.getTo(); 
            } 
        } 
        throw new IllegalStateTransition(initialState, action, targetState); 
    } 
 
    public void writeDotFormat(Writer writer) { 
        PrintWriter out = new PrintWriter(writer); 
        out.println("digraph state {"); 
        for (STATE state : states) { 
            out.println(state.name() + " [label=\"" + state.name() + "\"];"); 
        } 
        for (Transition transition : transitions) { 
            out.print(transition.getFrom().name()); 
            out.print(" -&gt; "); 
            out.print(transition.getTo().name()); 
            out.print(" [label=\""); 
            out.print(transition.getAction().toString().toLowerCase()); 
            out.print("\"];"); 
            out.println(); 
        } 
        out.println("}"); 
    } 
} 
 
public class IllegalStateTransition extends RuntimeException { 
    public IllegalStateTransition(Enum initialState, Enum action, Enum targetState) { 
        super("Attempting to perform " + action + " to move from " + initialState + " to " + targetState); 
    } 
} 
 
--- 
 
public class StateMachineTest extends TestCase { 

    private DayMachine dayMachine; 
 
    protected void setUp() throws Exception { 
        super.setUp(); 
        dayMachine = new DayMachine(); 
    } 
 
    public void testTerminalState() throws Exception { 
        assertEmpty(dayMachine.transitionsFrom(DayState.NEVER)); 
    } 
 
    public void testMoveToValidState() throws Exception { 
        assertEquals(DayState.NIGHT, dayMachine.move(DayState.DAYTIME, DayAction.SUNSET, DayState.NIGHT)); 
    } 
 
    public void testMoveToInvalidState() throws Exception { 
        try { 
            dayMachine.move(DayState.DAYTIME, DayAction.ARMAGEDDON, DayState.NEVER); 
            fail("Should have failed"); 
        } 
        catch (IllegalStateTransition e) { 
            assertEquals("Attempting to perform ARMAGEDDON to move from DAYTIME to NEVER", e.getMessage()); 
        } 
    } 
 
    public void testDotFormat() throws Exception { 
        StringWriter writer = new StringWriter(); 
        dayMachine.writeDotFormat(writer); 
 
        BufferedReader reader = new BufferedReader(new StringReader(writer.toString())); 
 
        assertEquals("digraph state {", reader.readLine()); 
        assertEquals("DAYTIME [label=\"DAYTIME\"];", reader.readLine()); 
        assertEquals("NIGHT [label=\"NIGHT\"];", reader.readLine()); 
        assertEquals("NEVER [label=\"NEVER\"];", reader.readLine()); 
        assertEquals("DAYTIME -&gt; NIGHT [label=\"sunset\"];", reader.readLine()); 
        assertEquals("NIGHT -&gt; DAYTIME [label=\"sunrise\"];", reader.readLine()); 
        assertEquals("NIGHT -&gt; NEVER [label=\"armageddon\"];", reader.readLine()); 
        assertEquals("}", reader.readLine()); 
    } 
 
    private void assertEmpty(List&lt;DayState&gt; list) { 
        assertEquals(0, list.size()); 
    } 
 
} 
</pre> 
]]></description>
 <category>Code</category>
<comments>http://purpletech.com/blog/index.php?itemid=20</comments>
 <pubDate>Fri, 19 Aug 2005 12:12:19 -0700</pubDate>
</item><item>
 <title><![CDATA[Primitive Obsession]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=18</link>
<description><![CDATA[In <a href="http://www.agilelectric.com/2005/05/26/my-favourite-smells/">a g i l e l e c t r i c » My Favourite Smells</a> Chris Wheeler names a code smell that's been on my list for some time: Primitive Obsession. I frequently tell my.. (um... what's the opposite of mentor?...) <b>proteges</b>, it's perfectly acceptable -- no, really -- to make an object that wraps a single, primitive value.  <br />
<br />
My favorite example of this is the one Chris uses -- wrap an integer so you know whether an index is zero-based or one-based. But his solution isn't quite radical enough for my taste. He made two classes, OneBasedInt and a ZeroBasedInt.  This isn't OO since it makes the mistake of naming for form rather than function.  Chris, I see your value object and raise it -- that is, decrement it by one class:<br />
<br />
<code><br />
public class PageNumber {<br />
&nbsp;&nbsp;public PageNumber fromZeroBased(int zeroBased) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;return new PageNumber(zeroBased);<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;public PageNumber fromOneBased(int oneBased) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;return new PageNumber(oneBased - 1);<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;private int zeroBased;<br />
&nbsp;&nbsp;private PageNumber(int zeroBased) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;this.zeroBased = zeroBased;<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;public int asZeroBased() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;return zeroBased;<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;public int asOneBased() { <br />
&nbsp;&nbsp;&nbsp;&nbsp;return zeroBased + 1;<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;public void increment() {<br />
&nbsp;&nbsp;&nbsp;&nbsp;zeroBased += 1;<br />
&nbsp;&nbsp;}<br />
&nbsp;&nbsp;...<br />
}<br />
</code><br />
<br />
<br />
This way people don't even *need* to know which type of index they should pass in to a method -- they just pass the object, and if some low-level rendering code needs to extract an integer in the right format, it just asks the object to present itself in the proper form. Actually, according to <a href="http://www.pragmaticprogrammer.com/ppllc/papers/1998_05.html">Tell Don't Ask</a>, it might do something like pass in an output stream and ask the PageNumber to render itself in one-based format (for human viewing) or zero-based format (for a URL GET parameter).<br />
<br />
Astute readers will note that the internal representation is the One, True, Correct form of integer indexes, which is as handed down from the prophets <a href="http://cm.bell-labs.com/cm/cs/cbook/">Kernighan and Ritchie</a>, world without end, Amen.<br />
]]></description>
 <category>Code</category>
<comments>http://purpletech.com/blog/index.php?itemid=18</comments>
 <pubDate>Wed, 1 Jun 2005 22:19:51 -0700</pubDate>
</item><item>
 <title><![CDATA[Flexible JUnit assertions with assertThat()]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=17</link>
<description><![CDATA[Joe Walnes describes a <a href="http://joe.truemesh.com/blog//000511.html">Clever junit base class</a> with declarative methods for doing stuff like this:<br />
<br />
assertThat(something, eq("Hello"));<br />
assertThat(something, eq(true));<br />
assertThat(something, isA(Color.class));<br />
assertThat(something, contains("World"));<br />
assertThat(something, same(Food.CHEESE));<br />
assertThat(something, NULL);<br />
assertThat(something, NOT_NULL);<br />
assertThat(something, not(eq("Hello")));<br />
assertThat(something, not(contains("Cheese")));<br />
assertThat(something, or(contains("color"), contains("colour")));<br />
<br />
And you get failure description messages for free! -- it infers them from the constraints.<br />
<br />
I like code you can read.<br />
]]></description>
 <category>Code</category>
<comments>http://purpletech.com/blog/index.php?itemid=17</comments>
 <pubDate>Sat, 28 May 2005 22:10:35 -0700</pubDate>
</item><item>
 <title><![CDATA[Zen Refactoring]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=14</link>
<description><![CDATA[Yesterday I was pairing with Patrick, our new intern. He's great, smart as a whip, and willing to learn.  (When I told him we write tests first, he laughed, incredulously, but then I said No, really, I'm actually serious, and he listened, and later, he said, Oh, now I see.) At the end of a long successful refactoring (turning a clutch of static methods into instance methods), we were sort of buzzing and didn't want to stop, were casting about for other refactorings to do in the same class.  I suggested a technique I only just then gave a name to, that I've done occasionally on my own for a long time, but hadn't yet taught: Zen Refactoring.<br />
<br />
"Just let your eyes unfocus and scroll through the code and look for refactorings.  Look for duplication; look for too-long or too-deeply-indented code blocks.  When you notice something odd, don't read it, just select it, hit Extract Method (ctl-alt-M), and hit random keys for the name.  Then focus your eyes again and see what you've done."<br />
<br />
I demonstrated. The first time we hit a bunch of print statements with repeated formatting -- it worked, but the refactoring was tedious, with marginal payoff. But the second time was golden.  I saw a blurry if-else block; the first arm meandered for 15 or 20 deeply-indented lines, the second for fewer; their logic appeared opaque and disjoint. But after extracting the first block as a method, lo and behold:<br />
<br />
<tt><br />
if (something() || other()) {<br />
&nbsp;&nbsp;customerId = sdlfjds(x, y, z);<br />
} else {<br />
&nbsp;&nbsp;user = someOtherExistingMethod();<br />
&nbsp;&nbsp;customerId = user.getUserId();<br />
}<br />
</tt><br />
<br />
IDEA had figured out that the result of that meander was a single value, and returned it from the new method.  It was instantly clear that we should rename the extracted method "customerIdForSomethingOrOther", and extract the whole conditional as "getCustomerId". Shift-F6, ctl-alt-M, high five.<br />
<br />
Then it was Patrick's turn. Not quite as much of a slam-dunk but still a worthy refactoring. I can't wait to get an incredulous laugh from the next one I spring this on...<br />
<br />
]]></description>
 <category>Code</category>
<comments>http://purpletech.com/blog/index.php?itemid=14</comments>
 <pubDate>Sat, 21 May 2005 10:25:07 -0700</pubDate>
</item><item>
 <title><![CDATA[The Socratic Method]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=13</link>
<description><![CDATA[This guy teaches a 3rd grade class binary arithmetic using <a href="http://www.garlikov.com/Soc_Meth.html">The Socratic Method</a> -- really!]]></description>
 <category>Links</category>
<comments>http://purpletech.com/blog/index.php?itemid=13</comments>
 <pubDate>Sun, 8 May 2005 20:33:38 -0700</pubDate>
</item><item>
 <title><![CDATA[Beck/DeMarco Interviewed]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=12</link>
<description><![CDATA[Kent Beck (XP's dad) and Tom DeMarco (<a href="http://www.amazon.com/exec/obidos/tg/detail/-/0932633439/">Peopleware</a>) interviewed in <a href="http://www.itworld.com/AppDev/1246/transcript_kentbeck050506/">ITworld.com - Extreme Programming Explained</a>]]></description>
 <category>Links</category>
<comments>http://purpletech.com/blog/index.php?itemid=12</comments>
 <pubDate>Sat, 7 May 2005 20:44:46 -0700</pubDate>
</item><item>
 <title><![CDATA[Checked Exceptions: A Successful Experiment with a Negative Result]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=11</link>
<description><![CDATA[A discussion around the team room reminded me of this classic <a href="http://www.mindview.net/Etc/Discussions/CheckedExceptions">Bruce Eckel essay on Checked Exceptions</a>. Excerpt:<br />

<blockquote>
The theory is that if the compiler forces the programmer to either handle the exception or pass it on in an exception specification, then the programmer's attention will always be brought back to the possibility of errors and they will thus properly take care of them. I think the problem is that this is an untested assumption we're making as language designers that falls into the field of psychology. My theory is that when someone is trying to do something and you are constantly prodding them with annoyances, they will use the quickest device available to make those annoyances go away so they can get their thing done, perhaps assuming they'll go back and take out the device later... In the end, I think we must realize the experimental nature of checked exceptions and look at them carefully before assuming that everything about exceptions in Java is good.</blockquote>

In code I write these days, most exceptions are RuntimeExceptions, and most catch blocks wrap and rethrow checked exceptions as unchecked. The way I figure it, if you don't know what to do, you should just let it pass on through, and every application needs a "catch (Throwable e)" very near the top of its input loop. <br />
<br />
(By the way, if you do "catch (Throwable e)", make sure you do
<pre>if (e instanceof ThreadDeath) { throw (ThreadDeath) e; }</pre>
or else your threads will have even more trouble dying than Java threads normally do.)

]]></description>
 <category>Code</category>
<comments>http://purpletech.com/blog/index.php?itemid=11</comments>
 <pubDate>Mon, 2 May 2005 17:55:23 -0700</pubDate>
</item><item>
 <title><![CDATA[Domain Lanugage Testing]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=10</link>
<description><![CDATA[I've just written my third Domain Lanugage Framework. Second and third, actually, one each for two clients. I keep meaning to write a paper on the subject but until I do, here's a blog entry with an overview.<br />
<br />
Motivation:<br />
<br />
Unified Domain Language is a term from Eric Evans' book Domain-Driven Design. One of its principles is that every term in the "domain" should refer to one and only one concept, and that the lexicon is agreed upon by engineers, product managers, domain experts, and users alike. See <a href="http://domainlanguage.com/ddd/index.html">http://domainlanguage.com/ddd/index.html</a><br />
<br />
Domain Specific Language (DSL) describes an automated, program-level implementation of the Unified Domain Language. (The two concepts overlap, but are not completely interchangeable.) A DSL can be used from a scripting console or from an automated test. In theory, a script or scenario written in the DSL can be understood by programmers, testers, product managers, users, etc. It serves as a "living specification" since it is executed against real code.<br />
<br />
Example:<br />
<br />
> use user alex<br />
Using user 'alex'.<br />
> sign-in<br />
Signed in as username 'alex' using password 'secret'.<br />
> join-room hottub<br />
Joined room 'hottub'.<br />
> say "Hello"<br />
Said 'Hello' in room "hottub".<br />
> show-users-in-room<br />
Users in room 'hottub': alex<br />
> expect "alex"<br />
Expected text 'alex' was found.<br />
<br />
<br />
Alex's Domain Language - Basic Principles<br />
<br />
    * Simple. This language has no loops, variables, conditionals, subroutines, recursion, etc. It needs to be readable and writeable by non-programmers.<br />
<br />
    * One Command, One Result. Every Command has one and only one return value. It is a human-readable string that fits on a single line. It should briefly but fully describe what the command just did.<br />
<br />
For example:<br />
<br />
      BAD: "Done." <br />
     GOOD: "Added user." <br />
   BETTER: "Added user 'alex' with password 'secret'."  <br />
BAD AGAIN: "200504252301&nbsp;-&nbsp;Added&nbsp;User@234554[name='alex',password='secret',id=42]"<br />
<br />
(Certain commands, notably "show-text" and "show-html", are exceptions to the rule that the result must be brief and legible.)<br />
<br />
    * Expect. Expect is this system's equivalent of Assert. It is a magic command that searches the result of the previous command for a string. If it finds it, it says so; if not, it fails. In the Console this failure prints an appropriate message; in an automated test, it will cause that test case to fail.<br />
<br />
It is important, as you expand the domain commands, not to make too-complex versions of Expect. Instead, try to compose a command that returns a value that the existing Expect can use. For example, instead of writing "expect-html", write "show-html" and use normal "expect".<br />
<br />
    * Test Data Archive. An archive of test data, defined externally to the commands, is available for use by tests/scripts. These objects represent Domain Objects but are simplified versions of them, containing only data values for use in user interface actions. So, for instance, a User has a username, but not an id (since that is invisible to the UI).<br />
<br />
    * Slots. A slot is a poor-man's variable. Each slot is either empty, or contains one exemplar from the Test Data archive. There is a limited number of slots, defined by the domain. In other words, scripts cannot arbitrarily create slots and put values in them; to add a slot you must add it to the domain.<br />
<br />
    * Command Discovery. It should be easy to add a Command to the language. In one of my frameworks, Commands are discovered at runtime via reflection on the various fixture objects. You mark a public method as a Command by using the @Command annotation. This declares the help text, abbreviation, parameters, etc. In another, a Command is a JavaBean-like object whose class is added to a list in the code. The interpreter chooses the class, instantiates it with Class.forName, and sets properties before calling Execute.<br />
<br />
    * Lenient Command Naming. Since Command names are Java method or class names, they are not the most legible to non-programmers. So Commands in scripts are case-insensitive and hyphens may be inserted for readability.<br />
<br />
   * JUnit Integration. Each scenario runs as a separate JUnit test, for easier integration with existing test suites and IDE JUnit plugins. This is done with a cusom JUnit suite that dynamically creates different instances of a JUnit Test class, one per scenario.<br />
]]></description>
 <category>Code</category>
<comments>http://purpletech.com/blog/index.php?itemid=10</comments>
 <pubDate>Thu, 28 Apr 2005 15:05:18 -0700</pubDate>
</item><item>
 <title><![CDATA[Craigslist on Google Maps]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=9</link>
<description><![CDATA[Wow. <a href="http://www.paulrademacher.com/housing/">Listings - San Francisco</a>]]></description>
 <category>Links</category>
<comments>http://purpletech.com/blog/index.php?itemid=9</comments>
 <pubDate>Sun, 10 Apr 2005 12:02:12 -0700</pubDate>
</item><item>
 <title><![CDATA[Code As Documentation]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=8</link>
<description><![CDATA[Vicky and I were working together on Friday -- her first exposure to XP and pair programming -- and she expressed<br />
amusement that I was very excited to *remove* comments from code.<br />
After all, we're taught to comment code compulsively. XP says, when you have a choice between unclear code with comments, and clear code<br />
without comments, choose the latter.<br />
<br />
See <a href="http://martinfowler.com/bliki/CodeAsDocumentation.html">http://martinfowler.com/bliki/CodeAsDocumentation.html</a>]]></description>
 <category>Code</category>
<comments>http://purpletech.com/blog/index.php?itemid=8</comments>
 <pubDate>Sun, 3 Apr 2005 16:00:31 -0700</pubDate>
</item><item>
 <title><![CDATA[IntelliJ IDEA personal license]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=7</link>
<description><![CDATA[<a href="http://www.scissor.com">William Pietri</a> brings to our attention:<br />
<br />
<blockquote><br />
I know some here are tempted by IntelliJ's IDEA but unwilling to pay<br />
$499 for it, I note that they are doing one of their apparently randomly<br />
scheduled special deals, where you can buy a <a href="http://www.jetbrains.com/idea/buy/personal.html">personal license for $249</a>.<br />
It's a full license; the only catch is that you can't buy more than one<br />
at this price.<br />
<br />
For those unfamliar with it, it's my favorite Java editor, with great<br />
refactoring tools and excellent usability. I haven't used Eclipse<br />
lately, but I understand that they keep rough feature parity. To me, the<br />
difference is more in usability; in trying to accomplish the same tasks,<br />
I found IDEA much more pleasant to use.<br />
</blockquote><br />
<br />
]]></description>
 <category>General</category>
<comments>http://purpletech.com/blog/index.php?itemid=7</comments>
 <pubDate>Wed, 30 Mar 2005 18:56:36 -0800</pubDate>
</item><item>
 <title><![CDATA[PlanetOut Agile Workspace]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=6</link>
<description><![CDATA[If you're interested in seeing how a real XP team sets up their workspace, check out <a href="http://www.stinky.com/planetoutspace/">PlanetOut Agile Workspace 2004</a>.   Please don't share this link without letting me know first, since the URL is on stinky.com rather than its eventual home at purpletech.com. <br />
<br />
The tables are from <a href="http://www.allsteeloffice.com/">AllSteel</a> but I can't find them on their site...<br />
<br />
See also <a href="http://www.scissor.com/resources/teamroom/">http://www.scissor.com/resources/teamroom/</a> <br />
]]></description>
 <category>General</category>
<comments>http://purpletech.com/blog/index.php?itemid=6</comments>
 <pubDate>Sun, 20 Mar 2005 23:16:38 -0800</pubDate>
</item><item>
 <title><![CDATA[Fixing JUnit]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=5</link>
<description><![CDATA[I just read about <a href="http://www.beust.com/testng/">TestNG</a> on <a href="http://www.jroller.com/page/fate/20050304#tsss_day_2_testng">The BileBlog</a>. He's right about Junit's shortcomings(*), but I can't help but wonder if relying XML configuration and JavaDoc annotations are replacing one set of misfeatures with another. Why can't people wrap their minds around expressing configurations in Java code?  Then we get the benefits of type safety, refactoring, constants, calculations, debugging, etc. etc...  But I guess that rant's a topic for another post.  And now that I think of it, JavaDoc annotations are a perfectly plausible way to do metadata.  Way better than empty interfaces, that's for sure.<br />
<br />
One thing I've meant to publish is the minimal testing framework I developed for my Test-Driven Training course.  It's basically JUnit in 100 lines (plus 80 more for asserts).  Tastes great, less filling.  I'll put the code below the fold (click the "[Read More]" link to see).<br />
<br />
<i><br />
(*) "The talk kicks off by pointing out the positives of JUnit, but quickly launches into describing how anyone who relies on such a brokenass piece of goatshit is basically trying to run a marathon by first chewing off one leg and blowing up the other while ramming an uncomfortably large baby jesus buttplug (yes, such an implement does exist, google it) into any number of orifices."</i><br />
<br />
<pre><br />
public class Test<br />
{<br />
    static class AssertionFailed extends RuntimeException<br />
    {<br />
        public AssertionFailed(String msg)<br />
        {<br />
            super(msg);<br />
        }<br />
    }<br />
<br />
    static void fail(String msg)<br />
    {<br />
        throw new AssertionFailed(msg);<br />
    }<br />
<br />
    static void assertEquals(Object expected, Object actual)<br />
<br />
    {<br />
        if (!expected.equals(actual))<br />
        {<br />
            fail("Expected <" + expected + "> but got <" + actual + ">");<br />
        }<br />
    }<br />
<br />
    static void assertEquals(double expected, double actual)<br />
    {<br />
        if (expected != actual)<br />
        {<br />
            fail("Expected <" + expected + "> but got <" + actual + ">");<br />
        }<br />
    }<br />
<br />
    static void assertEquals(int expected, int actual)<br />
    {<br />
        if (expected != actual)<br />
        {<br />
            fail("Expected <" + expected + "> but got <" + actual + ">");<br />
        }<br />
    }<br />
<br />
    static void assertTrue(boolean f)<br />
    {<br />
        if (!f)<br />
        {<br />
            fail("Expected true, but got false");<br />
        }<br />
    }<br />
<br />
    static void assertFalse(boolean f)<br />
    {<br />
        if (f)<br />
        {<br />
            fail("Expected false, but got true");<br />
        }<br />
    }<br />
<br />
    static void assertNotNull(Object o)<br />
    {<br />
        if (o == null)<br />
        {<br />
            fail("Should not be null");<br />
        }<br />
    }<br />
<br />
    static void assertNull(Object actual)<br />
    {<br />
        if (actual != null)<br />
        {<br />
            fail("Expected null but got <" + actual + ">");<br />
        }<br />
    }<br />
<br />
    static void assertContains(Collection collection, Object expected)<br />
    {<br />
        if (!collection.contains(expected)) {<br />
            throw new RuntimeException("Expected collection to contain " + expected);<br />
        }<br />
    }<br />
<br />
    public static void main(String[] args) throws Exception<br />
    {<br />
        if (args.length == 0)<br />
        {<br />
            System.out.println("Usage: java Test TestClass");<br />
            System.out.println("  where TestClass is the class name of a class that extends Test,");<br />
            System.out.println("  containing methods named testFoo");<br />
            System.out.println("Usage: java Test directory/");<br />
            System.out.println("  where directory is a directory name ending with '/' or '.'");<br />
            System.out.println("  will run all classes whose names end in Test.class in that directory");<br />
            System.exit(1);<br />
        }<br />
<br />
        runTests(args);<br />
    }<br />
<br />
    private static void runTests(String[] args) throws Exception<br />
    {<br />
        Test t = new Test();<br />
<br />
        for (int i = 0; i < args.length; ++i)<br />
        {<br />
            String className = args[i];<br />
            if (className.endsWith("/") || className.equals("."))<br />
            {<br />
                runTests(getTestClassesInDirectory(className));<br />
                continue;<br />
            }<br />
<br />
            if (className.endsWith(".class"))<br />
            {<br />
                className = className.substring(0, className.length() - ".class".length());<br />
            }<br />
            t.runTests(className);<br />
        }<br />
<br />
        t.printResults();<br />
    }<br />
<br />
    public static String[] getTestClassesInDirectory(String dir) throws Exception<br />
    {<br />
        File f = new File(dir);<br />
        return f.list(new TestFilter());<br />
    }<br />
<br />
    public static class TestFilter implements FilenameFilter<br />
    {<br />
        public boolean accept(File dir, String name)<br />
        {<br />
            return (name.endsWith("Test.class"));<br />
        }<br />
    }<br />
<br />
    int successful = 0;<br />
    int unsuccessful = 0;<br />
<br />
    private void printResults()<br />
    {<br />
        if (unsuccessful == 0)<br />
            System.out.println("SUCCESS");<br />
        else<br />
            System.out.println("OK: " + successful + " FAILED: " + unsuccessful);<br />
    }<br />
<br />
    private void runTests(String className) throws Exception<br />
    {<br />
        System.out.println("Running " + className);<br />
        Class testClass = Class.forName(className);<br />
<br />
        Constructor constructor = testClass.getConstructor(new Class[] {});<br />
        Method[] methods = testClass.getMethods();<br />
        for (int i = 0; i < methods.length; ++i)<br />
        {<br />
            Method method = methods[i];<br />
            if (method.getName().startsWith("test"))<br />
            {<br />
                System.out.print(method.getName() + "...");<br />
                try<br />
                {<br />
                    Object o = constructor.newInstance(new Object[]{});<br />
                    method.invoke(o, new Object[]{});<br />
                    System.out.println("OK");<br />
                    successful++;<br />
                }<br />
                catch (InvocationTargetException ite)<br />
                {<br />
                    System.out.println("FAILURE");<br />
                    ite.getTargetException().printStackTrace(System.out);<br />
                    unsuccessful++;<br />
                }<br />
                catch (Throwable t)<br />
                {<br />
                    System.out.println("FAILURE");<br />
                    t.printStackTrace(System.out);<br />
                    unsuccessful++;<br />
                }<br />
            }<br />
        }<br />
        System.out.println();<br />
    }<br />
<br />
}<br />
</pre><br />
<br />
Make your test class extend Test and give it a main method that calls Test.main (damn Java's uninherited statics!).  That's pretty much it.  Adding setUp and tearDown would take about 5 minutes.<br />
]]></description>
 <category>Code</category>
<comments>http://purpletech.com/blog/index.php?itemid=5</comments>
 <pubDate>Sun, 20 Mar 2005 22:47:34 -0800</pubDate>
</item><item>
 <title><![CDATA[Martin Fowler's Bliki]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=4</link>
<description><![CDATA[Testing the "Add to blog" feature with a link to <a href="http://martinfowler.com/bliki/">Martin Fowler's Bliki</a>]]></description>
 <category>Links</category>
<comments>http://purpletech.com/blog/index.php?itemid=4</comments>
 <pubDate>Sun, 20 Mar 2005 21:31:27 -0800</pubDate>
</item><item>
 <title><![CDATA[Feature Envy and Self-Testing Code]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=2</link>
<description><![CDATA[I've been toying with <a href="http://intellij.net">IDEA</a>'s <a href="http://c2.com/cgi/wiki?FeatureEnvy">Feature Envy</a> warning lately. It highlights methods that repeatedly refer to another object -- the heuristic here is that if a method M in object A makes heavy use of object B, then maybe M should be on object B instead. This captures a general OO concept that I've been advocating for a while but never had a good name for (or, more likely, forgot the name of after I read <a href="http://c2.com/cgi/wiki?RefactoringImprovingTheDesignOfExistingCode">Refactoring </a>by <a href="http://martinfowler.com/bliki/">Martin Fowler</a>). If nothing else it simplifies your code by replacing an explicit parameter with the implied this pointer. <br />
<br />
There's one flaw: any good unit test method is going to set off this alarm, which makes it kind of annoying. You can disable it on a per-method basis (with a JavaDoc comment -- ugh) but I thought it might be nice to turn it off on all JUnit classes, or on all code in your IDEA-marked test source directories. But then I had another idea.<br />
<br />
What about a testing framework that not only looked for all classes named Test, but all classes in your entire codebase containing public methods starting with the word "test"? This harks back to the pre-JUnit days of self-testing objects with a main method. These self-test  methods wouldn't have to use the hack of package protection to test class-private stuff, and have the advantage that they never get lost, and that you don't need any naming conventions to find the unit tests for any given object.<br />
<br />
One downside would be that your production code would become a bit bloated with test code, but unless I'm building an applet I don't care about that at all these days. Another problem is that it doesn't allow for multiple setup/teardown scenarios, but that's easily overcome either by using custom test fixtures, or by resorting to the traditional external test class.<br />
<br />
It would actually be pretty easy to write a JUnit suite like the one Erik Hanson wrote that makes a little proxy Test object for each self-testing class... Hmm...<br />
]]></description>
 <category>Code</category>
<comments>http://purpletech.com/blog/index.php?itemid=2</comments>
 <pubDate>Sun, 20 Mar 2005 21:19:26 -0800</pubDate>
</item><item>
 <title><![CDATA[Welcome to Purple Blog]]></title>
 <link>http://purpletech.com/blog/index.php?itemid=3</link>
<description><![CDATA[It's been a while but I'm finally going to party like it's 1999. That's when I was active on the RSS spec mailing lists(*) and got really excited that people were making standards around something I'd been doing in email, and others on the Web (remember Justin's Links) for years. I honestly can't say why it took 6 years, but regret for the past is a waste of spirit, and if anything having a 6-year backlog of rants will only help.<br />
<br />
(*) You know the pubDate tag? That was me :-)<br />
(though I guess that was more around 2001)<br />
<br />
]]></description>
 <category>General</category>
<comments>http://purpletech.com/blog/index.php?itemid=3</comments>
 <pubDate>Sun, 20 Mar 2005 20:25:00 -0800</pubDate>
</item>
  </channel>
</rss>