<?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>Symphonious &#187; Java</title> <atom:link href="http://www.symphonious.net/category/code-and-geek-stuff/java/feed/" rel="self" type="application/rss+xml" /><link>http://www.symphonious.net</link> <description>Living in a state of accord.</description> <lastBuildDate>Wed, 25 Jan 2012 21:25:34 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.1</generator> <item><title>Background Logging with the Disruptor</title><link>http://www.symphonious.net/2011/09/26/background-logging-with-the-disruptor/</link> <comments>http://www.symphonious.net/2011/09/26/background-logging-with-the-disruptor/#comments</comments> <pubDate>Mon, 26 Sep 2011 20:27:26 +0000</pubDate> <dc:creator>Adrian Sutton</dc:creator> <category><![CDATA[Code and Geek Stuff]]></category> <category><![CDATA[Disruptor]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[LMAX]]></category> <category><![CDATA[Performance]]></category> <guid
isPermaLink="false">http://www.symphonious.net/?p=1568</guid> <description><![CDATA[Peter Lawrey posted an example of using the Exchanger class from core Java to implement a background logging implementation. He briefly compared it to the LMAX disruptor and since someone requested it, I thought it might be interesting to show a similar implementation using the disruptor. Firstly, let’s revisit the very high level differences between [...]]]></description> <content:encoded><![CDATA[<p> <a
href="http://vanillajava.blogspot.com/2011/09/exchange-and-gc-less-java.html">Peter Lawrey posted an example of using the Exchanger class from core Java to implement a background logging implementation</a>. He briefly compared it to the <a
href="http://code.google.com/p/disruptor/">LMAX disruptor</a> and since someone requested it, I thought it might be interesting to show a similar implementation using the disruptor.</p><p> Firstly, let’s revisit the very high level differences between the exchanger and the disruptor. Peter notes:</p><blockquote><p> This approach has similar principles to the <a
href="http://code.google.com/p/disruptor/">Disruptor</a>. No GC using recycled, pre-allocated buffers and lock free operations (The Exchanger not completely lock free and doesn&#39;t busy wait, but it could)</p><p> Two keys difference are:</p><ul><li> there is only one producer/consumer in this case, the disruptor supports multiple consumers.</li><li> this approach re-uses a much smaller buffer efficiently. If you are using ByteBuffer (as I have in the past) an optimal size might be 32 KB. The disruptor library was designed to exploit large amounts of memory on the assumption it is relative cheap and can use medium sized (MBs) to very large buffers (GBs). e.g. it was design for servers with 144 GB. I am sure it works well on much smaller servers. ;)</li></ul></blockquote><p> Actually, there’s nothing about the Disruptor that requires large amounts of memory. If you know that your producers and consumers are going to keep pace with each other well and you don’t have a requirement to replay old events, you can use quite a small ring buffer with the Disruptor. There are a lot of advantages to having a large ring buffer, but it’s by no means a requirement.</p><p> It’s also worth noting that the Disruptor does not require consumers to busy-spin, you can choose to use a blocking wait strategy, or strategies that combine busy-spin and blocking to handle both spikes and lulls in event rates efficiently.</p><p> There is also an important advantage to the Disruptor that wasn’t mentioned: it will process events immediately if the consumer is keeping up. If the consumer falls behind however, it can process events in a batch to catch up. This significantly reduces latency while still handling spikes in load efficiently.</p><h2> The Code</h2><p> First let’s start with the LogEntry class. This is a simple value object that is used as our entries on the ring buffer and passed from the producer thread over to the consumer thread.</p><p> Peter’s Exchanger based implementation &#8211; the use of StringBuilder in the LogEntry class is actually a race condition and not thread safe. Both the publishing side and the consumer side are attempting to modify it and depending on how long it takes the publishing side to write the log message to the StringBuilder, it will potentially be processed and then reset by the consumer side before the publisher is complete. In this implementation I’m instead using a simple String to avoid that problem.</p><div
id="gist-1243275" class="gist"><div
class="gist-file"><div
class="gist-data gist-syntax"><div
class="highlight"><pre><div class='line' id='LC1'><span class="kn">import</span> <span class="nn">com.lmax.disruptor.EventFactory</span><span class="o">;</span></div><div class='line' id='LC2'><br/></div><div class='line' id='LC3'><span class="kd">class</span> <span class="nc">LogEntry</span></div><div class='line' id='LC4'><span class="o">{</span></div><div class='line' id='LC5'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">public</span> <span class="kd">static</span> <span class="kd">final</span> <span class="n">EventFactory</span><span class="o">&lt;</span><span class="n">LogEntry</span><span class="o">&gt;</span> <span class="n">FACTORY</span> <span class="o">=</span> <span class="k">new</span> <span class="n">EventFactory</span><span class="o">&lt;</span><span class="n">LogEntry</span><span class="o">&gt;()</span></div><div class='line' id='LC6'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">{</span></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">public</span> <span class="n">LogEntry</span> <span class="nf">newInstance</span><span class="o">()</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">{</span></div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="k">return</span> <span class="k">new</span> <span class="nf">LogEntry</span><span class="o">();</span></div><div class='line' id='LC10'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">};</span></div><div class='line' id='LC12'><br/></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">long</span> <span class="n">time</span><span class="o">;</span></div><div class='line' id='LC14'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kt">int</span> <span class="n">level</span><span class="o">;</span></div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">String</span> <span class="n">text</span><span class="o">;</span></div><div class='line' id='LC16'><span class="o">}</span></div><div class='line' id='LC17'><br/></div></pre></div></div><div
class="gist-meta"> <a
href="https://gist.github.com/raw/1243275/025846f5c293bcf6dbe2a20c73bad514e5317ad0/LogEntry.java" style="float:right;">view raw</a> <a
href="https://gist.github.com/1243275#file_log_entry.java" style="float:right;margin-right:10px;color:#666">LogEntry.java</a> <a
href="https://gist.github.com/1243275">This Gist</a> brought to you by <a
href="http://github.com">GitHub</a>.</div></div></div><p> The one Disruptor-specific addition is that we create an EventFactory instance which the Disruptor uses to pre-populate the ring buffer entries.</p><p> Next, let’s look at the BackgroundLogger class that sets up the process and acts as the producer.</p><div
id="gist-1243275" class="gist"><div
class="gist-file"><div
class="gist-data gist-syntax"><div
class="highlight"><pre><div class='line' id='LC1'><span class="kn">import</span> <span class="nn">com.lmax.disruptor.RingBuffer</span><span class="o">;</span></div><div class='line' id='LC2'><span class="kn">import</span> <span class="nn">com.lmax.disruptor.dsl.Disruptor</span><span class="o">;</span></div><div class='line' id='LC3'><br/></div><div class='line' id='LC4'><span class="kn">import</span> <span class="nn">java.util.concurrent.ExecutorService</span><span class="o">;</span></div><div class='line' id='LC5'><span class="kn">import</span> <span class="nn">java.util.concurrent.Executors</span><span class="o">;</span></div><div class='line' id='LC6'><br/></div><div class='line' id='LC7'><span class="kd">public</span> <span class="kd">class</span> <span class="nc">BackgroundLogger</span></div><div class='line' id='LC8'><span class="o">{</span></div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">private</span> <span class="kd">static</span> <span class="kd">final</span> <span class="kt">int</span> <span class="n">ENTRIES</span> <span class="o">=</span> <span class="mi">64</span><span class="o">;</span></div><div class='line' id='LC10'><br/></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">private</span> <span class="kd">final</span> <span class="n">ExecutorService</span> <span class="n">executorService</span><span class="o">;</span></div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">private</span> <span class="kd">final</span> <span class="n">Disruptor</span><span class="o">&lt;</span><span class="n">LogEntry</span><span class="o">&gt;</span> <span class="n">disruptor</span><span class="o">;</span></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">private</span> <span class="kd">final</span> <span class="n">RingBuffer</span><span class="o">&lt;</span><span class="n">LogEntry</span><span class="o">&gt;</span> <span class="n">ringBuffer</span><span class="o">;</span></div><div class='line' id='LC14'><br/></div><div class='line' id='LC15'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">BackgroundLogger</span><span class="o">()</span></div><div class='line' id='LC16'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">{</span></div><div class='line' id='LC17'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">executorService</span> <span class="o">=</span> <span class="n">Executors</span><span class="o">.</span><span class="na">newCachedThreadPool</span><span class="o">();</span></div><div class='line' id='LC18'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">disruptor</span> <span class="o">=</span> <span class="k">new</span> <span class="n">Disruptor</span><span class="o">&lt;</span><span class="n">LogEntry</span><span class="o">&gt;(</span><span class="n">LogEntry</span><span class="o">.</span><span class="na">FACTORY</span><span class="o">,</span> <span class="n">ENTRIES</span><span class="o">,</span> <span class="n">executorService</span><span class="o">);</span></div><div class='line' id='LC19'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">disruptor</span><span class="o">.</span><span class="na">handleEventsWith</span><span class="o">(</span><span class="k">new</span> <span class="n">LogEntryHandler</span><span class="o">());</span></div><div class='line' id='LC20'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">disruptor</span><span class="o">.</span><span class="na">start</span><span class="o">();</span></div><div class='line' id='LC21'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">ringBuffer</span> <span class="o">=</span> <span class="n">disruptor</span><span class="o">.</span><span class="na">getRingBuffer</span><span class="o">();</span></div><div class='line' id='LC22'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC23'><br/></div><div class='line' id='LC24'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">public</span> <span class="kt">void</span> <span class="nf">log</span><span class="o">(</span><span class="n">String</span> <span class="n">text</span><span class="o">)</span></div><div class='line' id='LC25'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">{</span></div><div class='line' id='LC26'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">final</span> <span class="kt">long</span> <span class="n">sequence</span> <span class="o">=</span> <span class="n">ringBuffer</span><span class="o">.</span><span class="na">next</span><span class="o">();</span></div><div class='line' id='LC27'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">final</span> <span class="n">LogEntry</span> <span class="n">logEntry</span> <span class="o">=</span> <span class="n">ringBuffer</span><span class="o">.</span><span class="na">get</span><span class="o">(</span><span class="n">sequence</span><span class="o">);</span></div><div class='line' id='LC28'><br/></div><div class='line' id='LC29'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">logEntry</span><span class="o">.</span><span class="na">time</span> <span class="o">=</span> <span class="n">System</span><span class="o">.</span><span class="na">currentTimeMillis</span><span class="o">();</span></div><div class='line' id='LC30'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">logEntry</span><span class="o">.</span><span class="na">level</span> <span class="o">=</span> <span class="n">level</span><span class="o">;</span></div><div class='line' id='LC31'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">logEntry</span><span class="o">.</span><span class="na">text</span> <span class="o">=</span> <span class="n">text</span><span class="o">;</span></div><div class='line' id='LC32'><br/></div><div class='line' id='LC33'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">ringBuffer</span><span class="o">.</span><span class="na">publish</span><span class="o">(</span><span class="n">sequence</span><span class="o">);</span></div><div class='line' id='LC34'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC35'><br/></div><div class='line' id='LC36'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">public</span> <span class="kt">void</span> <span class="nf">stop</span><span class="o">()</span></div><div class='line' id='LC37'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">{</span></div><div class='line' id='LC38'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">disruptor</span><span class="o">.</span><span class="na">shutdown</span><span class="o">();</span></div><div class='line' id='LC39'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="n">executorService</span><span class="o">.</span><span class="na">shutdownNow</span><span class="o">();</span></div><div class='line' id='LC40'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC41'><span class="o">}</span></div><div class='line' id='LC42'><br/></div><div class='line' id='LC43'><br/></div><div class='line' id='LC44'><br/></div></pre></div></div><div
class="gist-meta"> <a
href="https://gist.github.com/raw/1243275/d0fdee872f13a0a2c75b4b0e1c00355e0216eec6/BackgroundLogger.java" style="float:right;">view raw</a> <a
href="https://gist.github.com/1243275#file_background_logger.java" style="float:right;margin-right:10px;color:#666">BackgroundLogger.java</a> <a
href="https://gist.github.com/1243275">This Gist</a> brought to you by <a
href="http://github.com">GitHub</a>.</div></div></div><p> In the constructor we create an ExecutorService which the Disruptor will use to execute the consumer threads (a single thread in this case), then the disruptor itself. We pass in the LogEntry.FACTORY instance for it to use to create the entries and a size for the ring buffer.</p><p> The log method is our producer method. Note the use of two-phase commit. First claim a slot with the ringBuffer.next() method, then copy our values into that slot’s entry and finally publish the slot, ready for the consumer to process. We could have also used the Disruptor.publish method which can make this simpler for many use cases by rolling the two phase commit into call.</p><p> The producer doesn’t need to do any batching as the Disruptor will do that automatically if the consumer is falling behind, though there are also APIs that allow batching the producer which can improve the performance if it fits into your design (here it’s probably better to publish each log entry as it comes in).</p><p> The stop method uses the new shutdown method on the Disruptor which takes care of waiting until all consumers have processed all available entries for you, <a
href="http://groups.google.com/group/lmax-disruptor/browse_thread/thread/511cadc6383260aa/35e537304fc6439f?lnk=gst&#38;q=stop+disruptor#35e537304fc6439f">though the code for doing it yourself is quite straight-forward</a>. Finally we shut down the executor.</p><p> Note that we don’t need a flush method since the Disruptor is always consuming log events as quickly as the consumer can.</p><p> Last of all, the consumer which is almost entirely implementation logic:</p><div
id="gist-1243275" class="gist"><div
class="gist-file"><div
class="gist-data gist-syntax"><div
class="highlight"><pre><div class='line' id='LC1'><br/></div><div class='line' id='LC2'><span class="kn">import</span> <span class="nn">com.lmax.disruptor.EventHandler</span><span class="o">;</span></div><div class='line' id='LC3'><br/></div><div class='line' id='LC4'><span class="kd">public</span> <span class="kd">class</span> <span class="nc">LogEntryHandler</span> <span class="kd">implements</span> <span class="n">EventHandler</span><span class="o">&lt;</span><span class="n">LogEntry</span><span class="o">&gt;</span></div><div class='line' id='LC5'><span class="o">{</span></div><div class='line' id='LC6'><br/></div><div class='line' id='LC7'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">public</span> <span class="nf">LogEntryHandler</span><span class="o">()</span></div><div class='line' id='LC8'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">{</span></div><div class='line' id='LC9'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC10'><br/></div><div class='line' id='LC11'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="kd">public</span> <span class="kt">void</span> <span class="nf">onEvent</span><span class="o">(</span><span class="kd">final</span> <span class="n">LogEntry</span> <span class="n">logEntry</span><span class="o">,</span> <span class="kd">final</span> <span class="kt">long</span> <span class="n">sequence</span><span class="o">,</span> <span class="kd">final</span> <span class="kt">boolean</span> <span class="n">endOfBatch</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">Exception</span></div><div class='line' id='LC12'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">{</span></div><div class='line' id='LC13'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="c1">// Write</span></div><div class='line' id='LC14'>&nbsp;&nbsp;&nbsp;&nbsp;<span class="o">}</span></div><div class='line' id='LC15'><br/></div><div class='line' id='LC16'><span class="o">}</span></div><div class='line' id='LC17'><br/></div></pre></div></div><div
class="gist-meta"> <a
href="https://gist.github.com/raw/1243275/f353a5c78c4bc6c75121b1870d37608e36935d31/LogEntryHandler.java" style="float:right;">view raw</a> <a
href="https://gist.github.com/1243275#file_log_entry_handler.java" style="float:right;margin-right:10px;color:#666">LogEntryHandler.java</a> <a
href="https://gist.github.com/1243275">This Gist</a> brought to you by <a
href="http://github.com">GitHub</a>.</div></div></div><p> The consumer’s onEvent method is called for each LogEntry put into the Disruptor. The endOfBatch flag can be used as a signal to flush written content to disk, allowing very large buffer sizes to be used causing writes to disk to be batched when the consumer is running behind, yet also ensure that our valuable log messages get to disk as quickly as possible.</p><p> <a
href="https://gist.github.com/1243275">The full code is available as a Gist</a>.</p>]]></content:encoded> <wfw:commentRss>http://www.symphonious.net/2011/09/26/background-logging-with-the-disruptor/feed/</wfw:commentRss> <slash:comments>4</slash:comments> </item> <item><title>The Single Implementation Fallacy</title><link>http://www.symphonious.net/2011/06/18/the-single-implementation-fallacy/</link> <comments>http://www.symphonious.net/2011/06/18/the-single-implementation-fallacy/#comments</comments> <pubDate>Sat, 18 Jun 2011 17:42:53 +0000</pubDate> <dc:creator>Adrian Sutton</dc:creator> <category><![CDATA[Code and Geek Stuff]]></category> <category><![CDATA[Java]]></category> <guid
isPermaLink="false">http://www.symphonious.net/?p=1536</guid> <description><![CDATA[As my colleague and favorite debating opponent Danny Yates noted: We got into a bit of a debate at work recently. It went a bit like this: “Gah! Why do we have this interface when there is only a single implementation?” (The stock answer to this goes:) “Because we need the interface in order to [...]]]></description> <content:encoded><![CDATA[<p> As my colleague and favorite debating opponent <a
href="http://blog.codeaholics.org/2011/the-single-implementation-paradox/">Danny Yates noted</a>:</p><blockquote><p> We got into a bit of a debate at work recently. It went a bit like this:</p><p> “Gah! Why do we have this interface when there is only a single implementation?”</p><p> (The stock answer to this goes:) “Because we need the interface in order to mock this class in our tests.”</p><p> “Oh no you don’t, you can use the FingleWidget [insert appropriate technology of your mocking framework of choice here - e.g. JMock ClassImposteriser]! I’m smarter than you!”</p><p> “Well, yes, you can. But if you’ve correctly followed Design for Extension principles, you’ve made the class final, right? And you definitely can’t mock that! Hah! I’m smarter than you!”</p><p> “Ah ha! But you could always use the <a
href="http://jdave.org/documentation.html#mocking">JDave Unfinaliser Agent</a>! I’m so smart it hurts!”</p></blockquote><p> I tend to side with Danny that using the unfinaliser agent is a bad idea, but I also have to question the benefit of declaring a class final in the first place. However, let’s first cover why I think <a
href="http://www.symphonious.net/2011/06/02/enterprisey-interfaces/">single implementation interfaces are an “enterprisey” anti-pattern</a> in a little more detail.</p><h2> Why Single Implementation Interfaces Are Evil</h2><h3> Interface Separation or Interface Duplication</h3><p> The main argument people raise in favour of having interfaces for everything, even if there’s only one implementation is that it separates the API from the implementation. However in practice with languages like Java, this is simply not true. The interface has to be entirely duplicated in the implementation and the two are tightly coupled. Take the code:</p><pre>
public interface A {
  String doSomething(int p1, Object p2);
}
public class AImpl implements A {
  public String doSomething(int p1, Object p2) { ... }
}
</pre><p> This is a pretty clear violation of Don’t Repeat Yourself (DRY). The fact that the implementation name is essentially the same as the interface is a clear indication that there’s actually only one concept here. If there had been a vision of multiple implementations that work in different ways the class name would have reflected this (e.g. LinkedList vs ArrayList or FileReader vs StringReader).</p><p> As a general rule, if you can’t think of a good name for your class (or method, variable, etc) you’ve probably broken things down in the wrong way and you should rethink it.</p><h3> Extra Layers == Extra Work</h3><p> The net result of duplicating the API is that each time you want to add or change a method on the interface you have to duplicate that work and add it to the class as well. It’s a small amount of time but distracts from the real task at hand and amounts to a lot of unnecessary “busy work” if you force every class to have a duplicate interface. Plus if you subscribe to the idea of <a
href="http://www.infoq.com/news/2011/05/less-code-is-better">code as inventory</a>, those duplicated method declarations are costing you money.</p><p> <a
href="http://radar.oreilly.com/2011/06/devwir-ios-lawsuits-openoffice-apache-java.html">Also, as James Turner pointed out</a>:</p><blockquote> Unneeded interfaces are not only wasted code, they make reading and debugging the code much more difficult, because they break the link between the call and the implementation.</blockquote><p> This is probably the biggest problem I have with single implementation interfaces. When you’re tracking down a difficult bug you have to load up a lot of stuff into your head all at once – the call stack, variable values, expected control flow vs actual etc etc. Having to make the extra jump through a pointless interface on each call can be the straw that breaks the camel’s back and cause the developer to loose track of the vital context information. It’s doubly bad if you have to jump through a factory as well.</p><h3> Library Code</h3><p> Many people argue that in library code, providing separate interfaces is essential to define the API and ensure nothing leaks out accidentally. This is the one case where I think it makes sense to use an interface as it frees up your internal classes to use method visibility to let classes collaborate “behind the scenes” and have a clean implementation, without that leaking out to the API.</p><p> A word of warning however: one of the fatal mistakes you can make in a Java library is to provide interfaces that you expect the code using the library to implement. Doing this makes it extremely difficult to maintain backwards compatibility – if you ever need to add a method to that interface compatibility is immediately and unavoidably broken. On the other hand, providing an abstract class that you expect to be extended allows new methods to be added more easily since they can often provide a no-op implementation and maintain backwards compatibility. Abstract classes do limit the choices the code using the library can make though so neither option is a clear cut winner.</p><h2> Why Declaring Classes Final is Pointless</h2><p> So at last we come back around to the original problem of needing to mock out classes during testing but being unable to because they’re marked final. There seem to be two main reasons that people like to make classes final:</p><ol><li> Classes should be marked final unless they are explicitly designed for inheritance.</li><li> Marking a class final provides hints to HotSpot that can improve performance either by method inlining or using faster method call dispatch algorithms (direct instead of dynamic).</li></ol><h3> Designing for Extension</h3><p> I have a fair bit of sympathy for the argument that classes should be final unless designed for inheritance, but for shared code within a development team it has a very critical flaw &#8211; it’s trivial to just remove the word final and carry on, so people will. Let’s face it, if you look at a class and think “I can best solve my problem by extending this class” then a silly little keyword which may have just been put their by habit is not going to stop you. You’d need to also provide a clear comment about why the class isn’t suitable for extension but in most cases such a reason doesn’t exist &#8211; extension just hadn’t been thought about yet so the class is inherently not designed for extension. Besides which, if you have the concept of shared code ownership then whoever extends the class is responsible for making any design changes required to make it suitable for extending when they use it as a base class. Most likely though, they have already looked at the class and decided it’s suitable for extension as is which is why they are trying to do just that.</p><p> Perhaps what would be better is to require any class that is designed for extension to have a @DesignedForExtension annotation, then use code analysis tools (like <a
href="http://code.google.com/p/freud/">Freud</a>) to fail the build if a class without that annotation is extended. That makes the default not-extendable which is more likely to be correct and still lets you mock the object for testing. You would however want an IDE plugin to make the error message show up immediately but it does seem like a nice way to get the best of all worlds.</p><h3> Final Classes Go Faster</h3><p> I found myself immediately suspicious of this claim &#8211; it may have been true once but HotSpot is a seriously clever little JIT engine and advances at an amazing pace. Many people claim that HotSpot can inline final methods and it can, but it can also inline non-final methods. That’s right, <a
href="http://java.sun.com/developer/technicalArticles/Networking/HotSpot/inlining.html">it will automatically work out that there is only one possible version of this method that exists and go right ahead and inline it for you</a>.</p><p> There is also a slight variant of this that claims that since dynamic method dispatch is more expensive, marking a method as final means the JVM can avoid the dynamic dispatch for that method. Marking a class final effectively makes all it’s methods final so that every method would get the benefit.</p><p> My reasoning is such that if HotSpot can work out that it can safely inline a method, it clearly has all the information required to avoid the dynamic dispatch as well. I can’t however find any reference to definitively show it does that. Fortunately, I don’t need to. Remember back at the start we said we had to introduce an interface to make things testable? That means changing our code from:</p><pre>
final class A { public void doSomething(); }
…
A a = new A();
a.doSomething();
</pre><p> To:</p><pre>
interface A { void doSomething(); }
final class AImpl implements A { public void doSomething(); }
…
A a = new AImpl();
a.doSomething();
</pre><p> Since we’ve duplicated the method declaration, there is no guarantee that the only version of doSomething is in AImpl, since any class could implement interface A and provide a version of doSomething. We’re right back to relying on HotSpot doing clever tricks to enable method inlining and avoiding dynamic method dispatch.</p><p> There simply can be no performance benefit to declaring a class final if you then refer to it via an interface rather than the concrete class. And if you refer to it as the concrete class you can’t test it.</p><h2> Conclusion</h2><p> There shouldn’t be anything too surprising here – less code is better, simpler architectures work better and never underestimate how clever HotSpot is. Slavishly following the rule of separating the interface from the code doesn’t make code any more testable, it doesn’t reduce coupling between classes (since they still call the same methods) and it does create extra work. So why does everyone keep doing it?</p><p> Oh and, nyah, nyah, I’m so smart it hurts…</p>]]></content:encoded> <wfw:commentRss>http://www.symphonious.net/2011/06/18/the-single-implementation-fallacy/feed/</wfw:commentRss> <slash:comments>5</slash:comments> </item> <item><title>Abstracting Acceptance Tests</title><link>http://www.symphonious.net/2011/03/26/abstracting-acceptance-tests/</link> <comments>http://www.symphonious.net/2011/03/26/abstracting-acceptance-tests/#comments</comments> <pubDate>Sat, 26 Mar 2011 21:38:37 +0000</pubDate> <dc:creator>Adrian Sutton</dc:creator> <category><![CDATA[Code and Geek Stuff]]></category> <category><![CDATA[Java]]></category> <guid
isPermaLink="false">http://www.symphonious.net/?p=1511</guid> <description><![CDATA[For the past three months I’ve been settling into my new role with LMAX developing a high-performance financial “exchange”1, hence the silence on the blog lately. One of the things I’ve found extremely impressive about LMAX is the impressive acceptance test coverage and the relative ease with which they are maintained. Normally as a set [...]]]></description> <content:encoded><![CDATA[<p> For the past three months I’ve been settling into my new role with LMAX developing a high-performance financial “exchange”<a
class="footnote" id="footlink1:1301173295622" href="#footnote1:1301173295622">1</a>, hence the silence on the blog lately. One of the things I’ve found extremely impressive about LMAX is the impressive acceptance test coverage and the relative ease with which they are maintained. Normally as a set of acceptance tests gets to be extremely large they can become an impediment to being agile and changing the system since a small change to the UI can affect a large number of tests.</p><p> At LMAX that issue has been quite well handled by building a custom DSL for writing the acceptance tests so the acceptance tests are described at a very high level and then the details are handled in one place within the DSL &#8211; where they can be easily adjusted if the UI needs to be changed. It’s certainly not a new idea, but it’s executed better at LMAX than I’ve seen anywhere else.  They regularly have not just testers but also business analysts writing acceptance tests ahead of the new functionality being developed.</p><p> One of the key reasons for the success of the DSL at LMAX is getting the level of abstraction right &#8211; much higher than most acceptance test examples use. The typical example of a login acceptance test would be something like:</p><ol><li> Open the application</li><li> Enter “fred” in the field “username”</li><li> Enter “mypass” in the field “password”</li><li> Click the “login” button</li><li> Assert that the application welcome screen is shown</li></ol><p> However the LMAX DSL would abstract all of that away as just:</p><ol><li> Login as “fred”</li></ol><p> The DSL knows what web page to load to login (and how to log out if it’s already logged in), what fields to fill out and has default values for the password and other fields on the login form.  You can specify them directly if required, but the DSL takes care of as much as possible.</p><p> The second thing I’ve found very clever with the DSL is the way it helps to ensure tests run in an isolated environment as much as possible &#8211; even when running in parallel with other tests. There is very heavy use of aliases instead of actual values. So telling the DSL to login as “fred” will actually result in logging in as something like “fred-938797” &#8211; the real username being stored under the alias “fred” when the user was setup by the DSL. That way you have can thousands of tests all logging in as “user” and still be isolated from each other.</p><p> Interestingly, the LMAX DSL isn’t particularly English-like at all &#8211; it’s much closer to Java than English. It aims to be simple enough to understand by smart people who are working with the acceptance tests, but not necessarily the code, regularly. Sometimes developers can assume that non-developers are only capable of reading actual English text and invest too much time in making the DSL readable rather than functional, effective and efficient at expressing the requirements.</p><p> There is still a very obvious cost to building and maintaining such a large body of acceptance: some stories can require as much time writing acceptance tests as they do building the actual functionality and there is a lot of time and money invested in having enough hardware to run all those slow acceptance tests. Even so, I’ve seen a huge payoff for that effort even in the short time I’ve worked there.  The acceptance tests give people the confidence to try things out and go ahead an refactor code that needs it &#8211; even it the changes also require large-scale changes to the unit tests.</p><p
class="footnote"> <a
href="#footlink1:1301173295622" id="footnote1:1301173295622">1</a> &#8211; strictly speaking I believe it’s a multi-lateral trading facility. Don&#39;t ask me what the exact difference is. <a
class="footnotereturn" href="#footlink1:1301173295622">↩</a></p>]]></content:encoded> <wfw:commentRss>http://www.symphonious.net/2011/03/26/abstracting-acceptance-tests/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Apple-Scented Coffee Beans are Accurate</title><link>http://www.symphonious.net/2010/11/12/apple-scented-coffee-beans-are-accurate/</link> <comments>http://www.symphonious.net/2010/11/12/apple-scented-coffee-beans-are-accurate/#comments</comments> <pubDate>Fri, 12 Nov 2010 14:12:40 +0000</pubDate> <dc:creator>Adrian Sutton</dc:creator> <category><![CDATA[Apple]]></category> <category><![CDATA[Code and Geek Stuff]]></category> <category><![CDATA[Java]]></category> <guid
isPermaLink="false">http://www.symphonious.net/?p=1474</guid> <description><![CDATA[So Apple have announced that they will be contributing large swaths of code to the OpenJDK project and that from Java 7 onwards, Java will be a separate download from Oracle, much like Flash is now a separate download from Adobe. This really shouldn’t be unexpected for anyone who was paying attention to what was [...]]]></description> <content:encoded><![CDATA[<p> So <a
href="http://www.apple.com/pr/library/2010/11/12openjdk.html">Apple have announced that they will be contributing large swaths of code to the OpenJDK project</a> and that from Java 7 onwards, Java will be a separate download from Oracle, much like Flash is now a separate download from Adobe. This really shouldn’t be unexpected for <a
href="http://www.symphonious.net/2010/10/26/reading-the-apple-scented-coffee-beans/">anyone who was paying attention</a> to what was going on rather than just running around thinking the sky was falling.</p><p> This is fantastic news for Java developers of all types. Mac Java developers have been asking for Java to be separated from the OS for many, many years so that multiple versions of Java are more manageable and especially to decouple Java releases from the OS release timeline.</p><p> Since the main JVM for OS X will now be open source, intrepid developers can dive in and fix issues they run into or at least dig into the code to understand it better and find work-arounds they can use. Apple has historically been quite innovative with it’s JVM port as well, bringing some great stuff to the JVM on OS X first<a
class="footnote" id="footlink1:1289570799500" href="#footnote1:1289570799500">1</a>. It should now be easier to share those innovations across platforms which is great for all Java users.</p><p> It’s also nice to know that Java 6 will continue to be bundled with the OS in OS X 10.7 Lion. That gives a nice ramp-up for Apple and developers to transition to an optionally installed JVM and ensure things work smoothly either by applications bundling a JVM with the app or the installer or through auto-install methods for applets and webstart etc.</p><p> Finally, this should mean that JDK7 development on Mac will be done in the open, giving developers earlier and far greater access to try it out and report any issues back.</p><p> Seems like a huge win all round to me.</p><p
class="footnote"> <a
href="#footlink1:1289570799500" id="footnote1:1289570799500">1</a> &#8211; for example the ability to share the core classes between JVM instances, but also a lot of stuff in how swing works and integrates with the OS <a
class="footnotereturn" href="#footlink1:1289570799500">↩</a></p>]]></content:encoded> <wfw:commentRss>http://www.symphonious.net/2010/11/12/apple-scented-coffee-beans-are-accurate/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>On the DVD vs in Software Update</title><link>http://www.symphonious.net/2010/10/27/on-the-dvd-vs-in-software-update/</link> <comments>http://www.symphonious.net/2010/10/27/on-the-dvd-vs-in-software-update/#comments</comments> <pubDate>Wed, 27 Oct 2010 13:56:05 +0000</pubDate> <dc:creator>Adrian Sutton</dc:creator> <category><![CDATA[Apple]]></category> <category><![CDATA[Java]]></category> <guid
isPermaLink="false">http://www.symphonious.net/?p=1467</guid> <description><![CDATA[James Turner gives a week in review and mentions the deprecated Java on OS X issue1. One thing to correct: Deprecation basically means that neither package will be delivered as part of the installation DVDs, and updates will not come via the Apple update mechanisms. It doesn&#39;t mean they won&#39;t be available anymore, it just [...]]]></description> <content:encoded><![CDATA[<p> <a
href="http://radar.oreilly.com/2010/10/developer-week-in-review-3.html?utm_source=feedburner&#38;utm_medium=feed&#38;utm_campaign=Feed%3A+oreilly%2Fradar%2Fatom+%28O%27Reilly+Radar%29">James Turner gives a week in review</a> and mentions the deprecated Java on OS X issue<a
class="footnote" id="footlink1:1288187415254" href="#footnote1:1288187415254">1</a>. One thing to correct:</p><blockquote> Deprecation basically means that neither package will be delivered as part of the installation DVDs, and updates will not come via the Apple update mechanisms. It doesn&#39;t mean they won&#39;t be available anymore, it just means you&#39;ll have to download them directly from Oracle and Adobe.</blockquote><p> Firstly, there’s <a
href="http://www.symphonious.net/2010/10/26/reading-the-apple-scented-coffee-beans/">nothing to suggest</a> that Java won’t come from Apple but not be part of the standard OS X package.</p><p> Secondly, just because something isn’t on the OS X install DVD doesn’t mean it’s not updated via Software Update.  Aperture for example is a separately purchased product but updates come through Apple Software Update automatically. On Lion, software update is likely to open up further since it’s the obvious conduit to deliver updates for apps on the Mac App Store.</p><p> Of course, if the JVM winds up coming from Oracle, I wouldn’t hold your breath for updates via Software Update.</p><p
class="footnote"> <a
href="#footlink1:1288187415254" id="footnote1:1288187415254">1</a> &#8211; I’m not sure how deprecated Java counts as lost in the hubbub of Back to the Mac, from where I’m sitting it looks a lot like the other way around but anyway. <a
class="footnotereturn" href="#footlink1:1288187415254">↩</a></p>]]></content:encoded> <wfw:commentRss>http://www.symphonious.net/2010/10/27/on-the-dvd-vs-in-software-update/feed/</wfw:commentRss> <slash:comments>0</slash:comments> </item> <item><title>Reading the Apple-Scented Coffee Beans</title><link>http://www.symphonious.net/2010/10/26/reading-the-apple-scented-coffee-beans/</link> <comments>http://www.symphonious.net/2010/10/26/reading-the-apple-scented-coffee-beans/#comments</comments> <pubDate>Tue, 26 Oct 2010 17:15:47 +0000</pubDate> <dc:creator>Adrian Sutton</dc:creator> <category><![CDATA[Apple]]></category> <category><![CDATA[Java]]></category> <guid
isPermaLink="false">http://www.symphonious.net/?p=1465</guid> <description><![CDATA[It’s interesting to see how many people are jumping to conclusions around the very carefully worded deprecation notice for Java in OS X. Read it carefully and pay careful attention to what it actually says: As of the release of Java for Mac OS X 10.6 Update 3, the Java runtime ported by Apple and [...]]]></description> <content:encoded><![CDATA[<p> It’s interesting to see how many people are jumping to conclusions around the <a
href="http://developer.apple.com/library/mac/#releasenotes/Java/JavaSnowLeopardUpdate3LeopardUpdate8RN/NewandNoteworthy/NewandNoteworthy.html%23//apple_ref/doc/uid/TP40010380-CH4-SW1">very carefully worded deprecation notice for Java in OS X</a>. Read it carefully and pay careful attention to what it actually says:</p><blockquote> As of the release of Java for Mac OS X 10.6 Update 3, the Java runtime ported by Apple and that ships with Mac OS X is deprecated. Developers should not rely on the Apple-supplied Java runtime being present in future versions of Mac OS X.</blockquote><p> Most notably the note <em>only</em> refers to the <em>Apple ported</em> JVM that <em>ships with</em> OS X. This leaves the door open for an Apple ported JVM that ships as a separate download and for a non-Apple JVM that ships with OS X.</p><p> If you can drown out all the screaming and gnashing of teeth and pay attention to the Apple Java-Dev list you’d also notice:</p><ol><li> A huge amount of effort went into this release, especially setting things up to support multiple JVMs from multiple vendors. In the past, there was only one JVM available on an OS X install, it was upgraded with the OS and provided by Apple<a
class="footnote" id="footlink1:1288112417885" href="#footnote1:1288112417885">1</a>.</li><li> Even after this release, the Apple engineers who post to the list are still talking about their long term plans for the JVM (<a
href="http://lists.apple.com/archives/Java-dev/2010/Oct/msg00456.html">one example</a>).</li></ol><p> No one outside of Apple knows for sure what the future of Java on OS X is, and those inside who do know aren’t allowed to talk, but given the currently available evidence it seems at least as likely that Apple will continue to provide a JVM but as a separate download (or possibly just an optional install) as it is that they’ll abandon Java entirely.</p><p> Yes, there is a chance that Apple will just walk away from Java and leave a gaping void, but I don’t see indications that it’s a corporate strategy of Apple. Remember that Apple isn’t a company that sends a lot of mixed messages. They can turn a marketing message on a dime and they don’t pull punches. They’re also small enough and tightly managed enough that it’s rare for one part of the company to be off doing something that’s not inline with the company direction. If people are still building improvements to Java on OS X rather than moving to maintenance mode, that’s a strong signal that there is a future of some kind.</p><p> The real problem here is the same one that always happens with Apple &#8211; they’re not communicating their plans so developers can plan accordingly and not panic. But if you haven’t learnt to roll with the punches that approach delivers, you’re not a <em>real</em> Mac developer.</p><p
class="footnote"> <a
href="#footlink1:1288112417885" id="footnote1:1288112417885">1</a> &#8211; A situation which caused most of the complaints on the java-dev list.<a
class="footnotereturn" href="#footlink1:1288112417885">↩</a></p>]]></content:encoded> <wfw:commentRss>http://www.symphonious.net/2010/10/26/reading-the-apple-scented-coffee-beans/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>FireFox is Picky About Clipboard HTML, Java is Sloppy</title><link>http://www.symphonious.net/2010/09/21/firefox-is-picky-about-clipboard-html-java-is-sloppy/</link> <comments>http://www.symphonious.net/2010/09/21/firefox-is-picky-about-clipboard-html-java-is-sloppy/#comments</comments> <pubDate>Tue, 21 Sep 2010 10:06:38 +0000</pubDate> <dc:creator>Adrian Sutton</dc:creator> <category><![CDATA[Code and Geek Stuff]]></category> <category><![CDATA[Editors]]></category> <category><![CDATA[Java]]></category> <guid
isPermaLink="false">http://www.symphonious.net/?p=1436</guid> <description><![CDATA[Windows uses a particularly ugly format for putting HTML on the clipboard, called CF_HTML. Basically, it adds a header to the content with pretty useless information essentially declaring how many bytes in the header (and yes you have to pad the byte counts since they themselves are included in the count). The problem between Java [...]]]></description> <content:encoded><![CDATA[<p> Windows uses a particularly ugly format for putting HTML on the clipboard, called <a
href="http://msdn.microsoft.com/en-us/library/aa767917(VS.85).aspx">CF_HTML</a>. Basically, it adds a header to the content with pretty useless information essentially declaring how many bytes in the header (and yes you have to pad the byte counts since they themselves are included in the count).</p><p> The problem between Java and Firefox is that Java always sets the ‘StartHTML’ and ‘EndHTML’ fields to -1 to indicate there is no context and Firefox will refuse to paste HTML from the clipboard if StartHTML or EndHTML is set to -1. As such, if you copy HTML from Java it will be impossible to paste into Firefox. It works perfectly with Word and IE.</p><p> I’m not 100% clear on whether the clipboard data Java is generating is valid but I consider it a bug in both Java and Firefox &#8211; Java for not being strict about what it outputs and Firefox for being too strict about what it accepts. Bug reports shall be made<a
class="footnote" id="footlink1:1285065920040" href="#footnote1:1285065920040">1</a>.</p><p> On the Java side, the problem is in sun.awt.windows.WDataTrasferer.HTMLSupport.convertToHTMLFormat which sadly is Sun-specific, private and loaded from the bootclasspath so a little difficult to work around. There is however a <a
href="http://www.peterbuettner.de/develop/javasnippets/clipHtml/index.html">nasty, but effective, hack from Peter Buettner</a> which does indeed get around the problem. I’ve chosen to avoid the need to copy/paste HTML in this particular application but the approach is worth saving a reference to in case it’s needed later.</p><p
class="footnote"> <a
href="#footlink1:1285065920040" id="footnote1:1285065920040">1</a> &#8211; <a
href="https://bugzilla.mozilla.org/show_bug.cgi?id=598289">Bug 598289</a> with Mozilla and there’s a <a
href="/firefoxPasteBug.zip">simple test case available</a>. The bug report has also been filed with Oracle and is <a
href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6986348">now available in the bug parade</a>. <a
class="footnotereturn" href="#footlink1:1285065920040">↩</a></p>]]></content:encoded> <wfw:commentRss>http://www.symphonious.net/2010/09/21/firefox-is-picky-about-clipboard-html-java-is-sloppy/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Java AWT Robot and Windows Remote Desktop</title><link>http://www.symphonious.net/2010/06/15/java-awt-robot-and-windows-remote-desktop/</link> <comments>http://www.symphonious.net/2010/06/15/java-awt-robot-and-windows-remote-desktop/#comments</comments> <pubDate>Tue, 15 Jun 2010 09:32:38 +0000</pubDate> <dc:creator>Adrian Sutton</dc:creator> <category><![CDATA[Code and Geek Stuff]]></category> <category><![CDATA[Java]]></category> <category><![CDATA[Testing]]></category> <guid
isPermaLink="false">http://www.symphonious.net/?p=1371</guid> <description><![CDATA[Problem If you’re attempting to use the Java AWT Robot to help automate tests, you may find it convenient to log in via remote desktop to watch the tests execute and verify they work well. You may also find that they work fine while you’re watching them but then inexplicably start failing whenever you aren’t. [...]]]></description> <content:encoded><![CDATA[<h3> Problem</h3><p> If you’re attempting to use the Java AWT Robot to help automate tests, you may find it convenient to log in via remote desktop to watch the tests execute and verify they work well. You may also find that they work fine while you’re watching them but then inexplicably start failing whenever you aren’t. Basically your test is an <a
href="http://en.wikipedia.org/wiki/Blink_(Doctor_Who)">angel from Dr Who</a>.</p><p> What’s most likely happening is that when you disconnect from the remote desktop session, the console on the Windows box is left in a locked state and you need to enter the user password before you can resume interacting with programs on the main display. Since the AWT Robot is doing a very effective job of acting like a user, it also can’t interact with the programs you’re intending and instead is interacting, probably quite ineffectively, with the login dialog box.</p><h3> Solution</h3><p> It may be possible to get the AWT Robot to actually login before continuing, but then your tests would break when you were watching and it complicates the tests. Instead, you can take two approaches:</p><ol><li> Stop using remote desktop and switch to VNC which doesn’t lock the screen when you disconnect.</li><li> Rather than disconnecting from remote desktop, transfer the session back to the console. Use Start-&#62;Run or a DOS prompt and run:<pre>
tscon.exe 0 /dest:consol
</pre></li></ol><p> Or of course just get up and walk over to the remote machine and watch the tests on the console directly, but that’s not always a viable option.</p>]]></content:encoded> <wfw:commentRss>http://www.symphonious.net/2010/06/15/java-awt-robot-and-windows-remote-desktop/feed/</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Returning Parameters in JMock 2</title><link>http://www.symphonious.net/2010/03/09/returning-parameters-in-jmock-2/</link> <comments>http://www.symphonious.net/2010/03/09/returning-parameters-in-jmock-2/#comments</comments> <pubDate>Tue, 09 Mar 2010 18:07:39 +0000</pubDate> <dc:creator>Adrian Sutton</dc:creator> <category><![CDATA[Code and Geek Stuff]]></category> <category><![CDATA[Java]]></category> <guid
isPermaLink="false">http://www.symphonious.net/?p=1312</guid> <description><![CDATA[If you have a method like: String getParameter(String name, String defaultValue) where defaultValue is returned if the parameter isn’t specified, it can be challenging to get the right behavior in JMock without just hard coding what the defaultValue should be. Fortunately, a custom match which doubles as an Action can solve this pretty easily: import [...]]]></description> <content:encoded><![CDATA[<p> If you have a method like:</p><pre>
<code>String getParameter(String name, String defaultValue)</code>
</pre><p> where defaultValue is returned if the parameter isn’t specified, it can be challenging to get the right behavior in JMock without just hard coding what the defaultValue should be. Fortunately, a custom match which doubles as an Action can solve this pretty easily:</p><pre>
import org.hamcrest.*;
import org.jmock.api.*;
public class CapturingMatcher&#60;T&#62; extends BaseMatcher&#60;T&#62; implements Action {
	public T captured;
	public boolean matches(Object o) {
		try {
			captured = (T)o;
			return true;
		} catch (ClassCastException e) {
			return false;
		}
	}
	public void describeTo(Description description) {
		description.appendText(&quot;captured value &quot;);
		description.appendValue(captured);
	}
	public Object invoke(Invocation invocation) throws Throwable {
		return captured;
	}
}
</pre><p> It can then be used like:</p><pre>
context.checking(new Expectations() {{
	CapturingMatcher&#60;String&#62; returnCapturedValue = new CapturingMatcher&#60;String&#62;();
	allowing(mockObject).getParameter(with(equal(&quot;expectedParameterName&quot;)), with(returnCapturedValue)); will(returnCapturedValue);
}});
</pre><p> The matcher is used both for the parameter value (which it stores) and the return action, so it acts like a back reference would in a regex.  The same class be be useful alone as a matcher to let you interrogate the parameter value using normal assert statements rather than building a custom matcher.</p><p> I really should investigate what the describeTo function really should do though &#8211; I’m sure it would generate pretty weird messages at the moment.</p>]]></content:encoded> <wfw:commentRss>http://www.symphonious.net/2010/03/09/returning-parameters-in-jmock-2/feed/</wfw:commentRss> <slash:comments>6</slash:comments> </item> <item><title>Show Me the Metrics</title><link>http://www.symphonious.net/2010/03/03/show-me-the-metrics/</link> <comments>http://www.symphonious.net/2010/03/03/show-me-the-metrics/#comments</comments> <pubDate>Wed, 03 Mar 2010 14:25:10 +0000</pubDate> <dc:creator>Adrian Sutton</dc:creator> <category><![CDATA[Code and Geek Stuff]]></category> <category><![CDATA[Java]]></category> <guid
isPermaLink="false">http://www.symphonious.net/?p=1307</guid> <description><![CDATA[There’s been a lot of new innovations going on in programming languages and development techniques in general lately, but there’s a really key missing element: metrics. Seeing posts like Stephan Schmidt’s Go Ahead: Next Generation Java Programming Style and the response from Cedric Otaku really should make any professional software engineer concerned about the future [...]]]></description> <content:encoded><![CDATA[<p> There’s been a lot of new innovations going on in programming languages and development techniques in general lately, but there’s a really key missing element: metrics.</p><p> Seeing posts like Stephan Schmidt’s <a
href="http://codemonkeyism.com/generation-java-programming-style/">Go Ahead: Next Generation Java Programming Style</a> and <a
href="http://beust.com/weblog2/archives/000517.html">the response from Cedric Otaku</a> really should make any professional software engineer concerned about the future of their craft. Not because either of them are necessarily right or wrong, but because two highly skilled engineers are engaged in debate based purely on pure personal preference. There’s barely even any anecdotal evidence provided, let alone actual measurements to see what impact on productivity, quality or other desirable qualities the proposed approaches have.</p><p> A while back I stumbled across <a
href="http://www.slideshare.net/gvwilson/bits-of-evidence-2338367">the slides from Greg Wilson’s presentation </a><em><a
href="http://www.slideshare.net/gvwilson/bits-of-evidence-2338367">Bits of Evidence</a></em>. It’s almost a shame that the slides are well designed because they really are a short summary and I’d love to have heard all the extra information Greg spoke about around those slides. Even so, they really highlight the fact that we’re rushing off down all these new paths basically just because some guy said to. One of the side notes sums it up really well:</p><blockquote><p> Please note: I’m not disagreeing with his claims &#8211; I just want to point out that even the best of us aren’t doing what we expect the makers of acne creams to do.</p></blockquote><p> It would be easy to dismiss the importance of this because <em>in your own experience</em> technique A works better than technique B and with regular Agile retrospectives you’d notice if it had failings and worked to overcome them. Unfortunately, you’re very likely to fall victim to the same selection bias that makes psychics believable. People inherently remember the “hits” and forget the “misses”<a
class="footnote" id="footlink1:1267625653939" href="#footnote1:1267625653939">1</a>, so even personal experience isn’t something you should depend on to make decisions unless it’s backed up at least partly by real hard data.</p><p> I like playing with new technology as much as the next person, but at the end of the day I have to wonder if the benefits are always as compelling as we’d all like to think. Probability would suggest that some of the new approaches really are a big improvement, but it would also suggest some of them are a mistake. Without metrics to judge them on, how are we going to know the difference?</p><p
class="footnote"> <a
href="#footlink1:1267625653939" id="footnote1:1267625653939">1</a> &#8211; Wikipedia claims this was first raised in Broad, C. D. (1937). The philosophical implications of foreknowledge. <em>Proceedings of the Aristotelian Society (Supplementary)</em>, <em>16</em>, 177-209. <a
class="footnotereturn" href="#footlink1:1267625653939">↩</a></p>]]></content:encoded> <wfw:commentRss>http://www.symphonious.net/2010/03/03/show-me-the-metrics/feed/</wfw:commentRss> <slash:comments>8</slash:comments> </item> </channel> </rss>
