<?xml version='1.0' encoding='UTF-8'?><?xml-stylesheet href="http://www.blogger.com/styles/atom.css" type="text/css"?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearchrss/1.0/' xmlns:georss='http://www.georss.org/georss' xmlns:gd='http://schemas.google.com/g/2005' xmlns:thr='http://purl.org/syndication/thread/1.0'><id>tag:blogger.com,1999:blog-1213287780097066156</id><updated>2012-02-03T18:08:21.452-08:00</updated><category term='linux'/><category term='computer science'/><category term='idea'/><category term='block'/><category term='scala'/><category term='introduction'/><category term='jsf'/><category term='pojomatic'/><category term='seam'/><category term='programming'/><category term='ARM'/><category term='web applications'/><category term='intellij'/><category term='Scalax'/><category term='Java'/><category term='Automatic Resource Management'/><category term='desktop OS'/><category term='IDE'/><category term='OS X'/><category term='ARM block'/><category term='wicket'/><category term='Maven'/><category term='windows'/><category term='eclipse'/><category term='ManagedResource'/><title type='text'>Polyglot Window: Chris Hansen's Blog</title><subtitle type='html'>Technological ramblings from the multilingual JVM era.</subtitle><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://polyglot-window.blogspot.com/feeds/posts/default'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1213287780097066156/posts/default?max-results=100'/><link rel='alternate' type='text/html' href='http://polyglot-window.blogspot.com/'/><link rel='hub' href='http://pubsubhubbub.appspot.com/'/><author><name>Chris Hansen</name><uri>https://profiles.google.com/115790156504227129392</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh4.googleusercontent.com/-QNUxAOYtD-4/AAAAAAAAAAI/AAAAAAAAA2s/P3EtmA3Xgoc/s512-c/photo.jpg'/></author><generator version='7.00' uri='http://www.blogger.com'>Blogger</generator><openSearch:totalResults>10</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>100</openSearch:itemsPerPage><entry><id>tag:blogger.com,1999:blog-1213287780097066156.post-545689439566073495</id><published>2012-01-14T12:29:00.000-08:00</published><updated>2012-01-14T12:29:00.907-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='intellij'/><category scheme='http://www.blogger.com/atom/ns#' term='IDE'/><category scheme='http://www.blogger.com/atom/ns#' term='idea'/><category scheme='http://www.blogger.com/atom/ns#' term='eclipse'/><category scheme='http://www.blogger.com/atom/ns#' term='Maven'/><title type='text'>Switching to IntelliJ IDEA</title><content type='html'>&lt;a href="http://www.jetbrains.com/idea/"&gt;IntelliJ IDEA 11&lt;/a&gt; came out recently, and after some frustrations with Eclipse I decided to give the Community Edition a try. To my surprise, I've decided to stay with it, and I thought it was a good opportunity to dust off the old blog to explain why. Maybe it will be useful to others who have been considering trying IDEA for a while but aren't sure if it will be worth their time.&lt;br /&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span style="font-size: large;"&gt;Eclipse&lt;/span&gt;&lt;/div&gt;&lt;div&gt;First off, let me give Eclipse some credit. I've been more than satisfied with it over the past 6 or 7 years.&amp;nbsp;I haven't had any major issues with Eclipse, but it's been a bit like death by a thousand stings. Most of the pain comes from a few poor quality plugins or good plugins not playing nicely with each other.&lt;br /&gt;&lt;br /&gt;Eclipse's incremental compilation is incredible. It's probably the biggest feature that differentiates Eclipse from IDEA, both pro and con. The pro is immediate feedback. By the time you're ready to run your tests, Eclipse has done most of the heavy lifting and is ready to launch. However, that means the heavy lifting happens while you're editing or otherwise interacting with the UI, which can make the IDE feel less responsive at times. The JDT can also affect some plugins, which I'll get into later.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span style="font-size: large;"&gt;Enter IDEA&lt;/span&gt;&lt;/div&gt;&lt;div&gt;Later I'll list a bunch of small features that don't seem like much individually, but combined make a big difference. But first, the big differences.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: large;"&gt;Responsiveness&lt;/span&gt;&lt;br /&gt;The biggest difference I've noticed with IDEA is its responsiveness in regard to user interaction. It feels lightweight and snappy compared to Eclipse. Best of all, there's immediate code completion with no keyboard combination to press and&amp;nbsp;no waiting. This is huge. There have been several times I've cursed out Eclipse for having to wait a few seconds after hitting Ctrl Space. Especially in Scala code (more on that later).&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;&lt;span style="font-size: large;"&gt;Maven Integration&lt;/span&gt;&lt;/div&gt;&lt;div&gt;Surprisingly, IDEA has better Maven integration than Eclipse, despite Sonatype's great work on m2e. This is most likely an indirect result of Eclipse's incremental compilation. Because of this killer feature, Eclipse cannot delegate the build to Maven. That means m2e has to integrate the whole Maven build lifecycle into the JDT. This is called "project build lifecycle mapping" and the result is more configuration and plugin bloat. What's worse, if you're missing a lifecycle mapping it's an error by default: "&lt;a href="http://wiki.eclipse.org/M2E_plugin_execution_not_covered"&gt;Plugin execution not covered by lifecycle configuration&lt;/a&gt;". This was the straw that broke the camel's back for me.&lt;/div&gt;&lt;div&gt;&lt;br /&gt;&lt;/div&gt;&lt;div&gt;Even the pom file editor is better in IDEA. For example, it will autocomplete Maven groupIds, artifactIds and versions for artifacts you don't yet depend on, which has saved me from going outside of the IDE (especially versions). Also, it has built-in completion for Maven plugin configuration parameters in the pom file which I've had to go to the web to look up in the past. "Navigate to Managing Dependency" lets you navigate from a dependency to its corresponding dependencyManagement section, even if its in a parent pom. Plus it has an "Introduce Property" pom file refactoring which is a time-saver.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: large;"&gt;Scala Integration&lt;/span&gt;&lt;br /&gt;Scala integration in Eclipse is improving at a fast pace and soon may surpass that of IDEA, but for now I give IDEA the slight edge. It makes sense because Scala is in the same boat as Maven in Eclipse of having to integrate with the JDT. With Scala this is much more of a problem, though. The sheer amount of work that the Scala compiler has to do means incremental compilation of Scala code significantly affects the performance of Eclipse.&lt;br /&gt;&lt;br /&gt;For the most part, Scala "just works" in IDEA, with most of the same features Java has plus the Scala-specific ones you'd expect. It even has a "Convert Java file to Scala" refactoring which is also known as the Ugly Scala Code Generator (TM), but it might save you some time if you're converting a project over. However, I have had some rare phantom errors in IDEA, meaning code marked red in the editor that compiles just fine. Also, since editor parsing is separate from compilation, these don't go away when you do a build or run tests like they might in Eclipse.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-size: large;"&gt;The Rest&lt;/span&gt;&lt;br /&gt;This is the list of minor improvements which I've found useful. To keep it brief, I won't go into too much detail on each one, so I apologize if these are unclear. Many of these are examples of IntelliJ living up to its billing as an intelligent IDE because they require a deep understanding of your code.&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Ability to search for actions (Cmd Shift A). I cannot overstate how valuable this has been in my transition. You can look up any action (refactoring, searching, etc.) and execute it while keeping your hands on the keyboard. It also displays keyboard shortcuts so eventually you won't have to look it up again.&lt;/li&gt;&lt;li&gt;You can limit the scope of any search (text search, class hierarchy, etc.) to only production code or only test code.&lt;/li&gt;&lt;li&gt;Highlights classes as being unused when they are only referenced by tests.&lt;/li&gt;&lt;li&gt;Colors tabs differently based on the nature of the class. For example, test classes are green.&lt;/li&gt;&lt;li&gt;Colors annotations differently to distinguish them in imports.&lt;/li&gt;&lt;li&gt;Rename refactoring prompts to rename constructor and setter parameters in addition to getters and setters.&lt;/li&gt;&lt;li&gt;Console output from each test is self-contained, but you can get to the full console output if you need it.&lt;/li&gt;&lt;li&gt;Cmd click navigation from a string literal to a file with the same name in the project.&lt;/li&gt;&lt;li&gt;"Go To Test Subject" (Cmd Shift T) from a test class navigates to the class under test.&lt;/li&gt;&lt;li&gt;Optionally warns you when you're about to commit code with warnings/errors, and can create a separate changelist for you with only these changes if you choose not to commit.&lt;/li&gt;&lt;li&gt;"Shelve commits" lets you put aside your current changes so you can work on the current revision (or a different one) if you need to.&lt;/li&gt;&lt;li&gt;Autocomplete within string literals.&lt;/li&gt;&lt;li&gt;When you rename a class, it prompts you to rename similar variable names where the class is being used.&lt;/li&gt;&lt;li&gt;Extract method also finds duplications with different method arguments. I used to manually "pre-refactor" to get this same behavior&amp;nbsp;in Eclipse by first extracting local variables for the intended arguments.&lt;/li&gt;&lt;li&gt;Smart step-into when debugging so that you can step into a specific method on a line of code which calls many methods.&lt;/li&gt;&lt;li&gt;If you're editing a class file and add a reference to a class name that can't be resolved, there's a quick fix to "Add Maven Dependency".&lt;/li&gt;&lt;li&gt;Introduce parameter can move local variable initialization code from within a method to the method's callers.&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;div&gt;And here's some features that look useful, but I haven't tried yet.&lt;br /&gt;&lt;br /&gt;&lt;ul&gt;&lt;li&gt;Analyze dependencies.&lt;/li&gt;&lt;li&gt;Analyze backward dependencies.&lt;/li&gt;&lt;li&gt;Refactor -&amp;gt; replace&amp;nbsp;inheritance&amp;nbsp;with delegation.&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&lt;div&gt;&lt;span style="font-size: large;"&gt;Conclusion&lt;/span&gt;&lt;/div&gt;&lt;div&gt;It's mostly a bunch of little things that I like better about IDEA. Any one of them wouldn't be enough to make the switch, but combined make me feel more productive even after a few short weeks.&lt;br /&gt;&lt;br /&gt;I know it's just a matter of time until I buy the Ultimate Edition, and I'm ok with that.&amp;nbsp;You win this round, JetBrains. ;)&lt;/div&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1213287780097066156-545689439566073495?l=polyglot-window.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://polyglot-window.blogspot.com/feeds/545689439566073495/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://polyglot-window.blogspot.com/2012/01/switching-to-intellij-idea.html#comment-form' title='1 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1213287780097066156/posts/default/545689439566073495'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1213287780097066156/posts/default/545689439566073495'/><link rel='alternate' type='text/html' href='http://polyglot-window.blogspot.com/2012/01/switching-to-intellij-idea.html' title='Switching to IntelliJ IDEA'/><author><name>Chris Hansen</name><uri>https://profiles.google.com/115790156504227129392</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh4.googleusercontent.com/-QNUxAOYtD-4/AAAAAAAAAAI/AAAAAAAAA2s/P3EtmA3Xgoc/s512-c/photo.jpg'/></author><thr:total>1</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1213287780097066156.post-1480476117806517508</id><published>2009-03-26T19:42:00.000-07:00</published><updated>2009-03-26T21:09:39.985-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='ARM'/><category scheme='http://www.blogger.com/atom/ns#' term='Automatic Resource Management'/><category scheme='http://www.blogger.com/atom/ns#' term='ARM block'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>ARM Blocks in Scala: Revisited</title><content type='html'>Over a year ago, when I was new to Scala, I &lt;a href="http://polyglot-window.blogspot.com/2008/02/arm-blocks-in-scala.html"&gt;tried&lt;/a&gt; implementing Automatic Resource Management. I was not pleased with the result, so I &lt;a href="http://polyglot-window.blogspot.com/2008/02/arm-blocks-in-scala-part-3.html"&gt;ended up&lt;/a&gt; recommending ManagedResource from &lt;a href="http://scalax.scalaforge.org/"&gt;Scalax&lt;/a&gt;. After I came across a couple of links to my original post, I decided to point out a different approach that I have seen which seems to work well and appeals to me, personally. &lt;br /&gt;&lt;br /&gt;Next, I'll try to figure out where I went wrong originally, but those who are only interested in the new approach can skip the next section.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;font-size:130%;" &gt;Unnecessary Complication&lt;/span&gt;&lt;br /&gt;One of my original goals was to allow multiple resources per block. This ended up making the implementation much more complicated, especially with regard to exception handling. Also, in my first approach I included an exception handling mechanism which turns out to be unnecessary if we're only dealing with one resource at a time. The biggest problem with my first attempt, however, was that the resource had to be initialized outside of the ARM block, which, when multiple resources are initialized, can lead to the very resource leaks which we are trying to avoid. It was a good effort, however, if I do say so myself, and helped me to learn the language a bit.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight: bold;font-size:130%;" &gt;A Simpler Approach&lt;/span&gt;&lt;br /&gt;Lucky for me, Scala's first expert, Martin Odersky, also thought ARM was a good example of the flexibility of the language. I don't know when he started using ARM in his talks, but the first time I saw it was at JavaOne 2008, and then again at the Scala Lift Off event the following weekend. I will not re-post Odersky's implementation here without his permission (not that I think he would object), but I recommend that you take a look at slide 21 of his &lt;a href="http://www.slideshare.net/Odersky/fosdem-2009-1013261"&gt;FOSDEM 2009 presentation&lt;/a&gt; (which was hopefully posted with his permission).&lt;br /&gt;&lt;br /&gt;Odersky's approach is much more elegant. It only allows a single resource to be managed per block, which is actually all you need since ARM blocks can be nested to support multiple resources. Exceptions are not caught so that the caller can handle them properly. Simplicity. This ends up being very similar to the approach that C# has taken, so he chose to name the method the same as the C# "using" keyword. &lt;br /&gt;&lt;br /&gt;Here's how you use it:&lt;br /&gt;&lt;div style="overflow: auto; background-color: gray; color: white;"&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;//print a file, line by line&lt;br /&gt;using(new BufferedReader(new FileReader("test.txt"))) {&lt;br /&gt;  reader =&gt; {&lt;br /&gt;    println(reader.readLine)&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;//copy a file, line by line&lt;br /&gt;using(new BufferedReader(new FileReader("test.txt"))) {&lt;br /&gt;  reader =&gt; {&lt;br /&gt;    using(new BufferedWriter(new FileWriter("test_copy.txt"))) {&lt;br /&gt;      writer =&gt; {&lt;br /&gt;        var line = reader.readLine&lt;br /&gt;        while (line != null) {&lt;br /&gt;          writer.write(line)&lt;br /&gt;          writer.newLine&lt;br /&gt;          line = reader.readLine&lt;br /&gt;        }&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;I actually like this approach better than the ManagedResource from Scalax because the syntax feels more natural; it feels like you are using a language feature. I always thought ManagedResource was a bit strange because it felt like an abuse of the for-comprehension, but that's just my opinion.&lt;br /&gt;&lt;br /&gt;Since I hadn't seen anyone point out Martin Odersky's "using" implementation, I thought I would post about it. I think ARM is great and the fact that it can be implemented as a library in Scala is phenomenal. &lt;br /&gt;&lt;br /&gt;If we're lucky, Java SE 7 will have ARM thanks to &lt;a href="http://openjdk.java.net/projects/coin/"&gt;Project Coin&lt;/a&gt;, but it's getting more and more obvious these days that Java is not progressing as a language. Now if only I could do my everyday coding in Scala....&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1213287780097066156-1480476117806517508?l=polyglot-window.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://polyglot-window.blogspot.com/feeds/1480476117806517508/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://polyglot-window.blogspot.com/2009/03/arm-blocks-in-scala-revisited.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1213287780097066156/posts/default/1480476117806517508'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1213287780097066156/posts/default/1480476117806517508'/><link rel='alternate' type='text/html' href='http://polyglot-window.blogspot.com/2009/03/arm-blocks-in-scala-revisited.html' title='ARM Blocks in Scala: Revisited'/><author><name>Chris Hansen</name><uri>https://profiles.google.com/115790156504227129392</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh4.googleusercontent.com/-QNUxAOYtD-4/AAAAAAAAAAI/AAAAAAAAA2s/P3EtmA3Xgoc/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1213287780097066156.post-4423027341881121340</id><published>2009-01-07T21:09:00.000-08:00</published><updated>2009-01-08T20:28:43.024-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='pojomatic'/><title type='text'>Introducing Pojomatic</title><content type='html'>&lt;span style="font-weight:bold; font-size:130%;"&gt;New year, new project&lt;/span&gt;&lt;br /&gt;I'd like to start off the new year by introducing a project I've been working on for a while now along with Ian Robertson, a colleague of mine at Overstock. The project itself is actually not new at all, considering we began working on it around April of last year and it's based on something similar we've been using internally at Overstock since the early days of Java 1.5. The project is called &lt;a href="http://www.pojomatic.org/"&gt;Pojomatic&lt;/a&gt;, and what's new is that it's open source (Apache 2.0 license) and there's a release candidate available (1.0-RC1) on &lt;a href="https://sourceforge.net/project/showfiles.php?group_id=239113"&gt;Sourceforge&lt;/a&gt; or the &lt;a href="http://repo1.maven.org/maven2/org/pojomatic/pojomatic/"&gt;Maven central repository&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold; font-size:130%;"&gt;What does it do?&lt;/span&gt;&lt;br /&gt;Pojomatic is a Java library which provides automatic and configurable implementations of the hashCode() equals(Object) and toString() methods inherited from java.lang.Object using annotations. POJOs (Plain Old Java Objects) + automatic implementations of common methods = Pojomatic.&lt;br /&gt;&lt;br /&gt;This is a useful because it is generally a good idea to override hashCode() equals(Object) and sometimes toString(). One could manually implement these methods, but that is time-consuming and prone to error (e.g. forgetting to check for null everywhere). Instead, one could have an IDE generate implementations of these methods for you. As with a lot of generated code, this can be like slapping your code with an ugly stick. Besides, I'd often add fields and/or methods to the class later and forget to re-generate new implementations, which may have no effect or may lead to very subtle, hard to detect bugs (e.g. two objects are equal when they shouldn't be =&gt; two different people mistaken for the same person =&gt; money is deposited to the wrong account =&gt; one person is happy, while you are not because you have to work late to track down and fix the bug).&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold; font-size:130%;"&gt;How do I use it?&lt;/span&gt;&lt;br /&gt;The easiest way to use Pojomatic is to put one annotation (@AutoProperty) on your class and delegate the desired method(s) to the corresponding static methods in Pojomatic. For example:&lt;br /&gt;&lt;pre&gt;@AutoProperty&lt;br /&gt;public class Person {&lt;br /&gt;  private final String firstName;&lt;br /&gt;  private final String lastName;&lt;br /&gt;  private final int age;&lt;br /&gt;&lt;br /&gt;  public Person(String firstName, String lastName, int age) {&lt;br /&gt;    this.firstName = firstName;&lt;br /&gt;    this.lastName = lastName;&lt;br /&gt;    this.age = age;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public String getFirstName() {&lt;br /&gt;    return this.firstName;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public String getLastName() {&lt;br /&gt;    return this.lastName;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public int getAge() {&lt;br /&gt;    return this.age;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @Override public int hashCode() {&lt;br /&gt;    return Pojomatic.hashCode(this);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @Override public String toString() {&lt;br /&gt;    return Pojomatic.toString(this);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @Override public boolean equals(Object o) {&lt;br /&gt;    return Pojomatic.equals(this, o);&lt;br /&gt;  }&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;By default, @AutoProperty tells Pojomatic to automatically detect all of your fields and use them in all of the Pojomatic.* methods. We'll see the different options later, but in the above example, all of the fields will be used for hashCode() equals(Object) and toString() as shown here:&lt;br /&gt;&lt;pre&gt;public static void main(String[] args) {&lt;br /&gt;  Person johnDoe = new Person("John", "Doe", 32);&lt;br /&gt;  System.out.println(johnDoe.hashCode());&lt;br /&gt;  System.out.println(johnDoe.equals(new Person("John", "Doe", 32)));&lt;br /&gt;  System.out.println(johnDoe.toString());&lt;br /&gt;}&lt;/pre&gt;&lt;br /&gt;Outputs:&lt;br /&gt;&lt;pre&gt;-2068529904&lt;br /&gt;Person{firstName: {John}, lastName: {Doe}, age: {32}}&lt;br /&gt;true&lt;/pre&gt;&lt;br /&gt;Using all fields for each of hashCode() equals(Object) and toString() is usually not advised, however, so @AutoProperty can be configured to include automatically detected properties in any (valid) combination of these methods (including something in hashCode() without including it in equals(Object) violates the contract of hashCode(), so this is not allowed). Additionally, properties can be configured individually via the @Property annotation. When both annotations are present, @Property is used since it applies only to the one property. Using @Property gives you complete control and makes @AutoProperty optional. A common practice is to have all properties included in equals(Object) and toString(), while only one or two key properties are included in hashCode() like so:&lt;br /&gt;&lt;pre&gt;@AutoProperty(policy=DefaultPojomaticPolicy.EQUALS_TO_STRING)&lt;br /&gt;public class Book {&lt;br /&gt;&lt;br /&gt;  @Property(policy=PojomaticPolicy.ALL)&lt;br /&gt;  private final String isbn;&lt;br /&gt;&lt;br /&gt;  private final String title;&lt;br /&gt;&lt;br /&gt;  public Book(String isbn, String title) {&lt;br /&gt;    super();&lt;br /&gt;    this.isbn = isbn;&lt;br /&gt;    this.title = title;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public String getIsbn() {&lt;br /&gt;    return isbn;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  public String getTitle() {&lt;br /&gt;    return title;&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @Override public int hashCode() {&lt;br /&gt;    return Pojomatic.hashCode(this);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @Override public String toString() {&lt;br /&gt;    return Pojomatic.toString(this);&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  @Override public boolean equals(Object o) {&lt;br /&gt;    return Pojomatic.equals(this, o);&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;Both @AutoProperty and @Property can use accessor methods (getters) instead of fields in situations where using accessors is more desirable or when a SecurityManager prevents Pojomatic from accessing private fields through reflection.&lt;br /&gt;&lt;br /&gt;Briefly, there is also a feature which will let you customize the String representation of each property. For example, this would be useful if one of your properties contains sensitive data such as an account number, credit card number or social security number (see &lt;a href="http://pojomatic.sourceforge.net/apidocs/org/pojomatic/formatter/AccountNumberFormatter.html"&gt;AccountNumberFormatter&lt;/a&gt;). Pojomatic provides the ability for you to define your own formatter implementations as well.&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold; font-size:130%;"&gt;Feedback&lt;/span&gt;&lt;br /&gt;Pojomatic has been a lot of fun to work on, and I hope you will find it useful. I'm confident that after trying it out, you will not want to go back to handcrafting equals methods or using ugly IDE-generated code instead. Any feedback is appreciated, as well as feature requests, so what do you think?&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1213287780097066156-4423027341881121340?l=polyglot-window.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://polyglot-window.blogspot.com/feeds/4423027341881121340/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://polyglot-window.blogspot.com/2009/01/introducing-pojomatic.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1213287780097066156/posts/default/4423027341881121340'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1213287780097066156/posts/default/4423027341881121340'/><link rel='alternate' type='text/html' href='http://polyglot-window.blogspot.com/2009/01/introducing-pojomatic.html' title='Introducing Pojomatic'/><author><name>Chris Hansen</name><uri>https://profiles.google.com/115790156504227129392</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh4.googleusercontent.com/-QNUxAOYtD-4/AAAAAAAAAAI/AAAAAAAAA2s/P3EtmA3Xgoc/s512-c/photo.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1213287780097066156.post-8352713208785006229</id><published>2008-10-27T22:14:00.000-07:00</published><updated>2008-11-01T16:40:38.352-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='Java'/><category scheme='http://www.blogger.com/atom/ns#' term='wicket'/><category scheme='http://www.blogger.com/atom/ns#' term='seam'/><category scheme='http://www.blogger.com/atom/ns#' term='web applications'/><category scheme='http://www.blogger.com/atom/ns#' term='jsf'/><title type='text'>Learning Wicket</title><content type='html'>I'm always on the lookout for different ways of doing the things I'm familiar with. Once in a while, I learn a better way of doing things. Even if I don't, I find that it helps me realize what I like and dislike about the techniques that I'm used to.&lt;br /&gt;&lt;br /&gt;Take creating web applications for example. I'm familiar with JSF, both with and without Seam. Overall, I would say that I agree with the ideas behind JSF, but in practice it is not easy to be productive in developing a medium to large sized web app. It seems like some things that should be very easy to do are difficult, but maybe that's just me. Seam adds a bit more complexity, but helps overall. To the JSF world of managed beans, Seam adds ways to manage the rest of your objects called scopes. This is a good idea on paper, but feels a bit like using global variables (albeit with managed lifecycles).&lt;br /&gt;&lt;br /&gt;So I decided to give Wicket a try. What stood out to me right away is the simplicity of it. There's very little configuration, and no XML other than web.xml (which makes me realize how much I dislike having stuff like page navigation in an XML file). Each page template corresponds to one Java class. Also, there is no EL or OGNL so your markup is sure to have no logic whatsoever, which is great for those of us who prefer to code in Java. That's the bottom-line benefit that I see with Wicket: &lt;span style="font-weight:bold;"&gt;everything happens in Java code&lt;/span&gt;. Which means you get all of the benefits of writing Java code in an IDE from debugging to refactoring, etc. I haven't tried it, but I've &lt;a href="http://technically.us/code/x/the-escape-hatch"&gt;read&lt;/a&gt; that it's easy to use alternative JVM languages such as Scala and Groovy instead, if you are so inclined.&lt;br /&gt;&lt;br /&gt;Wicket is very friendly to the web designer because it does not invade the markup, so the designer can see what they are getting without firing up a web container. For now, I haven't seen any Wicket components which look good "out of the box" (translation: you probably need a web designer). However, there is no reason why there couldn't be such component libraries for Wicket. That will come with increased adoption, if it happens. After all, creating a component library in Wicket means putting your classes and markup in a JAR file, so it couldn't be easier.&lt;br /&gt;&lt;br /&gt;Some minor gripes I have with Wicket are that the markup has to stay in sync with your Java class (but all web frameworks I have used also have this problem), it can sometimes add junk to your URLs after a form submit (maybe there's a way around that). Also, there's quite a bit of casting when using version 1.3, but they are adding generics to version 1.4 which should minimize that. Overall, I'm very impressed.&lt;br /&gt;&lt;br /&gt;Resources:&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://www.ibm.com/developerworks/library/os-tapestrywicket/index.html"&gt;Tapestry and Wicket Compared&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://wicket.apache.org/"&gt;Wicket home&lt;/a&gt; for useful documentation, examples, etc.&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://www.javaworld.com/javaworld/jw-06-2008/jw-06-wicket1.html?page=1"&gt;JavaWorld Series on Wicket&lt;/a&gt; by &lt;a href="http://technically.us/code"&gt;Nathan Hamblen&lt;/a&gt;&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1213287780097066156-8352713208785006229?l=polyglot-window.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://polyglot-window.blogspot.com/feeds/8352713208785006229/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://polyglot-window.blogspot.com/2008/10/learning-wicket.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1213287780097066156/posts/default/8352713208785006229'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1213287780097066156/posts/default/8352713208785006229'/><link rel='alternate' type='text/html' href='http://polyglot-window.blogspot.com/2008/10/learning-wicket.html' title='Learning Wicket'/><author><name>Chris Hansen</name><uri>https://profiles.google.com/115790156504227129392</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh4.googleusercontent.com/-QNUxAOYtD-4/AAAAAAAAAAI/AAAAAAAAA2s/P3EtmA3Xgoc/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1213287780097066156.post-9174977066478193820</id><published>2008-03-12T21:46:00.000-07:00</published><updated>2008-03-19T21:24:10.234-07:00</updated><title type='text'>Ideal command prompt</title><content type='html'>&lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_fGPrIhK8YIE/R9i2Da_O5NI/AAAAAAAAAAM/wN8IK4xMP0U/s1600-h/terminal.jpg"&gt;&lt;img style="margin:0 10px 10px 0;cursor:pointer; cursor:hand;" src="http://2.bp.blogspot.com/_fGPrIhK8YIE/R9i2Da_O5NI/AAAAAAAAAAM/wN8IK4xMP0U/s320/terminal.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5177087941562787026" /&gt;&lt;/a&gt;&lt;br /&gt;In setting up my &lt;a href="http://polyglot-window.blogspot.com/2008/03/rantings-of-recent-mac-convert.html"&gt;new laptop&lt;/a&gt;, I've been experimenting with different command prompt settings in bash. &lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_fGPrIhK8YIE/R9i2Da_O5NI/AAAAAAAAAAM/wN8IK4xMP0U/s1600-h/terminal.jpg"&gt;Here&lt;/a&gt; is what I've settled on for now (click for a more clear &lt;a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="http://2.bp.blogspot.com/_fGPrIhK8YIE/R9i2Da_O5NI/AAAAAAAAAAM/wN8IK4xMP0U/s1600-h/terminal.jpg"&gt;image&lt;/a&gt;). It's simple, yet gives me all of the information I need in a format that is easy for the eye to parse. That's because the text color of the full path is inverted from your other colors.&lt;br /&gt;&lt;br /&gt;If you are interested in using/tweaking it:&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;export PS1="\u:\[\e[0;07m\w\e[m\]&amp;gt; "&lt;/span&gt;&lt;br /&gt;&lt;br /&gt;What's your ideal PS1? Here's a &lt;a href="http://www.cyberciti.biz/tips/howto-linux-unix-bash-shell-setup-prompt.html"&gt;how-to article&lt;/a&gt;. It's written with Linux in mind, but the information applies to pretty much any environment where bash is present (OS X, Unix, Cygwin, etc.).&lt;br /&gt;&lt;br /&gt;EDIT: My original post did not wrap the color code in \[ and \] which caused the first line wrap to overwrite the current line. Fixed!&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1213287780097066156-9174977066478193820?l=polyglot-window.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://polyglot-window.blogspot.com/feeds/9174977066478193820/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://polyglot-window.blogspot.com/2008/03/ideal-command-prompt.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1213287780097066156/posts/default/9174977066478193820'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1213287780097066156/posts/default/9174977066478193820'/><link rel='alternate' type='text/html' href='http://polyglot-window.blogspot.com/2008/03/ideal-command-prompt.html' title='Ideal command prompt'/><author><name>Chris Hansen</name><uri>https://profiles.google.com/115790156504227129392</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh4.googleusercontent.com/-QNUxAOYtD-4/AAAAAAAAAAI/AAAAAAAAA2s/P3EtmA3Xgoc/s512-c/photo.jpg'/></author><media:thumbnail xmlns:media='http://search.yahoo.com/mrss/' url='http://2.bp.blogspot.com/_fGPrIhK8YIE/R9i2Da_O5NI/AAAAAAAAAAM/wN8IK4xMP0U/s72-c/terminal.jpg' height='72' width='72'/><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1213287780097066156.post-2834104137289670494</id><published>2008-03-11T23:22:00.000-07:00</published><updated>2008-03-12T00:20:06.892-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='OS X'/><category scheme='http://www.blogger.com/atom/ns#' term='desktop OS'/><category scheme='http://www.blogger.com/atom/ns#' term='linux'/><category scheme='http://www.blogger.com/atom/ns#' term='windows'/><title type='text'>Rantings of a recent Mac convert</title><content type='html'>I ordered a new MacBook Pro (Penryn w/ multi-touch) which arrived last Monday (which probably explains my lack of posting since then). Although I do have a bit of experience with OS X and actually do my programming at work on a Mac mini (I'm in the minority here), this is my first purchase of any Apple product (which means I don't own an iPod - &lt;span style="font-weight:bold;"&gt;*gasp*&lt;/span&gt;).&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;The Desktop OS Wars&lt;/h4&gt;&lt;br /&gt;As far as OSes are concerned, I don't mind Windows, but I find that it gets in my way sometimes. That is fine for most people because they know the workarounds (e.g. reboot, re-install every 6 months...). To me, this is a waste of time since other OSes don't have this problem. This observation is mostly from XP and previous versions, but based upon what I've heard about Vista, I don't expected much better. Also, the lack of a robust terminal/shell (with things like adequate scripting) is completely inexcusable when the competitors run bash and the like.&lt;br /&gt;&lt;br /&gt;Linux is a rock-solid OS. It dominates the server environments, and rightly so. The problem is the desktop user experience. The average computer user cannot be expected to survive here, and even the most technically savvy users often find themselves searching through forum posts for hours on how to overcome some hurdle or another. Driver support is non-existent for the most part. The installation process is flawed for the vast majority of distros (one exception is Ubuntu and the like). Also, while package management is great, there are often packages that are missing and/or outdated, so it loses much of its utility. Granted, Linux in general (and Ubuntu in particular) are making great strides in this area, but the progress is too little, too late.&lt;br /&gt;&lt;br /&gt;That brings me to OS X. I think Apple's really gotten it right. Take something solid (BSD - though modified with a very different kernel) and put a nice UI on top of it, and that's exactly what they've done. I have a terminal session (bash) open 90% of the time when I'm programming, which is indispensable. I never payed much attention to aliasing or font rendering before, but I can't help but notice how much better everything looks. Some of that has to do with the top-notch (read: expensive) displays that Apple uses, but at work I've used the same (non-Apple) display on Windows, Linux and OS X and there is a clear difference.&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Final Thoughts&lt;/h4&gt;&lt;br /&gt;I have to say, I am very impressed with my MBP so far. It does everything I want it to, without any of the quirks that are present in other hardware/OS configurations. I think this is due to the relatively small number of available hardware configurations for Macs. This puts Apple in the unique position of being able to test every possible hardware configuration - they know it works. I've heard from other Mac users that "everything works", but I don't think I really believed them or understood the implications of that statement. Now I get to experience it firsthand, and it's refreshing.&lt;br /&gt;&lt;br /&gt;Anyhow, I hope to get back to posting more Scala stuff soon, and maybe something about Java for a change.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1213287780097066156-2834104137289670494?l=polyglot-window.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://polyglot-window.blogspot.com/feeds/2834104137289670494/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://polyglot-window.blogspot.com/2008/03/rantings-of-recent-mac-convert.html#comment-form' title='0 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1213287780097066156/posts/default/2834104137289670494'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1213287780097066156/posts/default/2834104137289670494'/><link rel='alternate' type='text/html' href='http://polyglot-window.blogspot.com/2008/03/rantings-of-recent-mac-convert.html' title='Rantings of a recent Mac convert'/><author><name>Chris Hansen</name><uri>https://profiles.google.com/115790156504227129392</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh4.googleusercontent.com/-QNUxAOYtD-4/AAAAAAAAAAI/AAAAAAAAA2s/P3EtmA3Xgoc/s512-c/photo.jpg'/></author><thr:total>0</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1213287780097066156.post-594125424928726997</id><published>2008-02-23T10:31:00.000-08:00</published><updated>2009-03-26T21:11:03.803-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='ARM'/><category scheme='http://www.blogger.com/atom/ns#' term='Automatic Resource Management'/><category scheme='http://www.blogger.com/atom/ns#' term='ManagedResource'/><category scheme='http://www.blogger.com/atom/ns#' term='Scalax'/><category scheme='http://www.blogger.com/atom/ns#' term='ARM block'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>ARM Blocks in Scala, Part 3: The Concession</title><content type='html'>Update: &lt;a href="http://polyglot-window.blogspot.com/2009/03/arm-blocks-in-scala-revisited.html"&gt;Here&lt;/a&gt;'s a better approach to Automatic Resource Management in Scala.&lt;br /&gt;&lt;br /&gt;After a couple of attempts (&lt;a href="http://polyglot-window.blogspot.com/2008/02/arm-blocks-in-scala.html"&gt;part 1&lt;/a&gt;, &lt;a href="http://polyglot-window.blogspot.com/2008/02/arm-blocks-in-scala-part-2.html"&gt;part 2&lt;/a&gt;) at implementing Automatic Resource Management in Scala, I've decided not to "reinvent the wheel" here. I will defer instead to the implementation found in &lt;a href="http://scalax.scalaforge.org/"&gt;Scalax&lt;/a&gt;. I did not know about their &lt;a href="http://scalax.scalaforge.org/api/scalax/control/ManagedResource.html"&gt;ManagedResource &lt;/a&gt; class before my first post (many thanks to the commenters who pointed me there), and if I had known about it I may not have made the attempt. I'm glad I did, however, because it gave me a chance to improve my Scala skills. I'm not "there" yet, though, as I still find myself writing Java-like code in Scala. When I catch myself doing so, I am usually able to refactor it into the Scala style, which ends up being more compact and elegant. Come to think of it, that is why I recommend ManagedResource over my approach. I would say mine is the Java-like approach, while ManagedResource is more elegant and more consistent with Scala style.&lt;br /&gt;&lt;br /&gt;Let's look at the same example from my first two posts using ManagedResource:&lt;br /&gt;&lt;div  style="background-color: gray; color: white; overflow: auto;"&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  def createReader = ManagedResource(new BufferedReader(new FileReader("test.txt")))&lt;br /&gt;  def createWriter = ManagedResource(new BufferedWriter(new FileWriter("test_copy.txt")))&lt;br /&gt;  &lt;br /&gt;  //copy a file, line by line&lt;br /&gt;  for(reader &lt;- createReader; writer &lt;- createWriter) {&lt;br /&gt;      var line = reader.readLine&lt;br /&gt;      while (line != null) {&lt;br /&gt;        writer.write(line)&lt;br /&gt;        writer.newLine&lt;br /&gt;        line = reader.readLine&lt;br /&gt;      }&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;&lt;span style="font-weight:bold;"&gt;Why is ManagedResource better?&lt;/span&gt;&lt;br /&gt;It may be clear from the example, but let's discuss what it is that makes the usage of ManagedResource cleaner than the previous approach. ManagedResource uses for-comprehensions, and that alone solves many of the problems I encountered. For example, I had the problem of being able to define and initialize a resource and still being able to reference it inside of the block of code. For that reason, I had to define an initialization function (in part 2), but "for" takes care of this nicely: &lt;span style="font-style:italic;"&gt;for(a &lt;- ManagedResource(new SomeResource()))&lt;/span&gt; .... It also takes care of the many-resources problem elegantly, without using varargs: &lt;span style="font-style:italic;"&gt;for(a &lt;- createA; b &lt;- createB; ...)&lt;/span&gt;. In short, "for" seems like the right tool for the job.&lt;br /&gt;&lt;br /&gt;That being said, I think ManagedResource does have some room for improvement. For example, consider the following code segment:&lt;br /&gt;&lt;div  style="background-color: gray; color: white; overflow: auto;"&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  def createReader = ManagedResource(new BufferedReader(new FileReader("test.txt")))&lt;br /&gt;  def createWriter = ManagedResource(new BufferedWriter(new FileWriter("test_copy.txt")))&lt;br /&gt;&lt;br /&gt; try {&lt;br /&gt;    //copy a file, line by line&lt;br /&gt;    for(reader &lt;- createReader; writer &lt;- createWriter) {&lt;br /&gt;      try {&lt;br /&gt;        var line = reader.readLine&lt;br /&gt;        while (line != null) {&lt;br /&gt;          writer.write(line)&lt;br /&gt;          writer.newLine&lt;br /&gt;          line = reader.readLine&lt;br /&gt;        }&lt;br /&gt;      } catch {&lt;br /&gt;        case e: IOException =&gt; println("Exception thrown while copying: " + e.getMessage)&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;  } catch {&lt;br /&gt;    case e: IOException =&gt; println("Exception thrown upon open or close: " + e.getMessage)&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;As you can see, we have total control inside of the block of code, but if an exception occurs while initializing or disposing we have no way of knowing which of the two steps was the culprit. This is probably not an issue most of the time, but I could see a possible need for handling exceptions in initialization differently from exceptions in disposal. Maybe this can be improved (it would have to be non-intrusive for the more common, general case), or maybe some level of control must be sacrificed.&lt;br /&gt;&lt;br /&gt;Also, at the time of writing, ManagedResource exposes methods for opening (initializing) and closing (disposing) a resource: "unsafeOpen" and "unsafeClose". These cannot be called from within the block of a for-comprehension, but I see no need to make them public, "protected[control]" should be the maximum visibility - if that. Making them public is a mistake because it allows for the same type of resource leaks we set out to quash. In fact, anyone who is calling these methods externally requires more control over where and when resources are initialized and disposed, and should not be using ManagedResource to begin with. If there is a legitimate reason for exposing these methods, I would like to see it.&lt;br /&gt;&lt;br /&gt;Overall, however, I have to congratulate Scalax (Jamie Webb in particular) for getting it right. Scalax is still in a very early stage, so maybe the concerns addressed here will be addressed by the time it is ready for release. These concerns are relatively minor anyway, so I recommend using ManagedResource as is.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1213287780097066156-594125424928726997?l=polyglot-window.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://polyglot-window.blogspot.com/feeds/594125424928726997/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://polyglot-window.blogspot.com/2008/02/arm-blocks-in-scala-part-3.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1213287780097066156/posts/default/594125424928726997'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1213287780097066156/posts/default/594125424928726997'/><link rel='alternate' type='text/html' href='http://polyglot-window.blogspot.com/2008/02/arm-blocks-in-scala-part-3.html' title='ARM Blocks in Scala, Part 3: The Concession'/><author><name>Chris Hansen</name><uri>https://profiles.google.com/115790156504227129392</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh4.googleusercontent.com/-QNUxAOYtD-4/AAAAAAAAAAI/AAAAAAAAA2s/P3EtmA3Xgoc/s512-c/photo.jpg'/></author><thr:total>2</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1213287780097066156.post-7634735867491529287</id><published>2008-02-15T20:58:00.000-08:00</published><updated>2009-03-26T21:10:21.533-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='ARM'/><category scheme='http://www.blogger.com/atom/ns#' term='Automatic Resource Management'/><category scheme='http://www.blogger.com/atom/ns#' term='ARM block'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>ARM Blocks in Scala, Part 2</title><content type='html'>Update: &lt;a href="http://polyglot-window.blogspot.com/2009/03/arm-blocks-in-scala-revisited.html"&gt;Here&lt;/a&gt;'s a better approach to Automatic Resource Management in Scala.&lt;br /&gt;&lt;br /&gt;I didn't plan on writing a follow-up to my &lt;a href="http://polyglot-window.blogspot.com/2008/02/arm-blocks-in-scala.html"&gt;first post on ARM Blocks in Scala&lt;/a&gt;, but I think I will be able to improve upon some things. I don't plan on any future posts on this topic, but I will not hesitate to do another one if sufficient progress can being made.&lt;br /&gt;&lt;br /&gt;Here's where we left off with Arm:&lt;br /&gt;&lt;div  style="background-color: gray; color: white; overflow: auto;"&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;object Arm {&lt;br /&gt;  type CloseType = { def close() }&lt;br /&gt;&lt;br /&gt;  def manage(resources: CloseType*)(block: =&gt; Unit)&lt;br /&gt;  (implicit exceptionHandler: (Exception) =&gt; Unit) = {&lt;br /&gt;    try {&lt;br /&gt;      block&lt;br /&gt;    } finally {&lt;br /&gt;      resources.foreach( resource =&gt; {&lt;br /&gt;        try {&lt;br /&gt;          resource.close()&lt;br /&gt;        } catch {&lt;br /&gt;          case e: Exception =&gt;&lt;br /&gt;            try {&lt;br /&gt;              exceptionHandler(e)&lt;br /&gt;            } catch {&lt;br /&gt;              case fatal: Throwable =&gt; fatal.printStackTrace() //last resort&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;      })&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;&lt;h4&gt;Motivation&lt;/h4&gt;I chose to write a follow-up because of a couple of important omissions that I made in my previous post. The first and foremost is that of resource initialization (as "helium" pointed out). The problem is that resource initialization happens outside of the scope of the Arm.manage method. This violates the principle motivation for ARM Blocks by forcing the developer to &lt;span style="font-weight:bold;"&gt;correctly&lt;/span&gt; handle resource disposal in the case that one or more resources is initialized successfully and others are not.&lt;br /&gt;For example:&lt;br /&gt;&lt;div  style="background-color: gray; color: white; overflow: auto;"&gt;&lt;pre&gt;&lt;br /&gt;val reader = new BufferedReader(new FileReader("test.txt"))&lt;br /&gt;val writer = new BufferedWriter(new FileWriter("test_copy.txt"))&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;If &lt;span style="font-style:italic;"&gt;reader&lt;/span&gt; initializes successfully and &lt;span style="font-style:italic;"&gt;writer&lt;/span&gt; does not, &lt;span style="font-style:italic;"&gt;reader&lt;/span&gt; needs to be closed. This is exactly the type of problem we were trying to avoid with ARM Blocks in the first place. I didn't have a solution for this problem at the time, but I forgot to mention it in my post - a mistake on my part.&lt;br /&gt;&lt;br /&gt;Secondly, I didn't mention how an exception within the block of code itself should/would be handled. This means that one would have to wrap the entire call to Arm.manage in a try/catch block in order to handle any exceptions that may occur inside the block itself. Not ideal.&lt;br /&gt;&lt;br /&gt;In this post, I hope to address these two concerns. The solution I present here is by no means the best solution, and I am confident it can be improved upon as well.&lt;br /&gt;&lt;br /&gt;For starters, let's take care of the first issue, which is the easier of the two:&lt;br /&gt;&lt;div  style="background-color: gray; color: white; overflow: auto;"&gt;&lt;pre&gt;&lt;br /&gt;object Arm {&lt;br /&gt;  type CloseType = { def close() }&lt;br /&gt;&lt;br /&gt;  def manage(resources: CloseType*)(block: =&gt; Unit)&lt;br /&gt;  (implicit exceptionHandler: (Exception) =&gt; Unit) = {&lt;br /&gt;    try {&lt;br /&gt;      try {&lt;br /&gt;        block&lt;br /&gt;      } catch {&lt;br /&gt;        case e: Exception =&gt; exceptionHandler(e)&lt;br /&gt;      }&lt;br /&gt;    } finally {&lt;br /&gt;      resources.foreach( resource =&gt; {&lt;br /&gt;        try {&lt;br /&gt;          if (resource != null)&lt;br /&gt;            resource.close()&lt;br /&gt;        } catch {&lt;br /&gt;          case e: Exception =&gt;&lt;br /&gt;            try {&lt;br /&gt;              exceptionHandler(e)&lt;br /&gt;            } catch {&lt;br /&gt;              case fatal: Throwable =&gt; fatal.printStackTrace() //last resort&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;      })&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;Here we reuse the existing exception handler function. This is more convenient that declaring two different exception handlers, but has the issue of knowing if the exception being handled occurred upon closing or in the block itself. We will correct this after we address the second issue.&lt;br /&gt;&lt;br /&gt;The issue of initialization is a more complicated one. The approach taken here is to define an initialization function, much like our exception handling function. It should be implicit as well in the case that resources have already been initialized and no initialization is necessary. Here's an attempt:&lt;br /&gt;&lt;div  style="background-color: gray; color: white; overflow: auto;"&gt;&lt;pre&gt;&lt;br /&gt;object Arm {&lt;br /&gt;  implicit def defaultInitializer() = {}&lt;br /&gt;  implicit def defaultExceptionHandler(e: Exception) = {}&lt;br /&gt;&lt;br /&gt;  type CloseType = { def close() }&lt;br /&gt;&lt;br /&gt;  def manage(resources: (() =&gt; CloseType)*)(block: =&gt; Unit)&lt;br /&gt;  (implicit initializer: () =&gt; Unit, exceptionHandler: (Exception) =&gt; Unit) = {&lt;br /&gt;    try {&lt;br /&gt;      try {&lt;br /&gt;        initializer()&lt;br /&gt;        block&lt;br /&gt;      } catch {&lt;br /&gt;        case e: Exception =&gt; exceptionHandler(e)&lt;br /&gt;      }&lt;br /&gt;    } finally {&lt;br /&gt;      resources.foreach( resource =&gt; {&lt;br /&gt;        try {&lt;br /&gt;          val value = resource()&lt;br /&gt;          if (value != null)&lt;br /&gt;            value.close()&lt;br /&gt;        } catch {&lt;br /&gt;          case e: Exception =&gt;&lt;br /&gt;            try {&lt;br /&gt;              exceptionHandler(e)&lt;br /&gt;            } catch {&lt;br /&gt;              case fatal: Throwable =&gt; fatal.printStackTrace() //last resort&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;      })&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;Here we define a default initializer as well as a default exception handler. Defining the exception handler is not really necessary because of the implicit identity function in Scala's Predef, but defining the default initializer may be helpful. In Arm.manage, the initialization and exception handling functions are included in the list of implicit parameters. Only one such list is allowed in the Scala language and it is required to be the last list of params. Also, if we are to use an initialization function, the resources themselves cannot be passed as arguments because it will be call-by-value (i.e. in Arm.manage, they will remain uninitialized). Instead, we use call-by-name and accept an arbitrary number of functions that return resources - remember that methods are functions in Scala. This is a necessary change, but adds a bit of clutter when it comes to usage. We will save an example until later because of a deficiency in this implementation.&lt;br /&gt;&lt;br /&gt;In this version of Arm.manage, when an exception occurs and our handler is called, we have no idea if the exception happened in initialization, in the block of code, or when trying to close the resources.&lt;br /&gt;&lt;br /&gt;Let's address this issue:&lt;br /&gt;&lt;div  style="background-color: gray; color: white; overflow: auto;"&gt;&lt;pre&gt;&lt;br /&gt;object Arm {&lt;br /&gt;  abstract class ManagementException(val cause: Exception) extends Exception(cause) {&lt;br /&gt;    override def getCause() = cause&lt;br /&gt;  }&lt;br /&gt;  class InitializationException(cause: Exception) extends ManagementException(cause)&lt;br /&gt;  class ExecutionException(cause: Exception) extends ManagementException(cause)&lt;br /&gt;  class ClosingException(cause: Exception) extends ManagementException(cause)&lt;br /&gt;&lt;br /&gt;  implicit def defaultInitializer() = {}&lt;br /&gt;  implicit def defaultExceptionHandler(e: ManagementException) = {}&lt;br /&gt;&lt;br /&gt;  type CloseType = { def close() }&lt;br /&gt;&lt;br /&gt;  def manage(resources: (() =&gt; CloseType)*)(block: =&gt; Unit)&lt;br /&gt;  (implicit initializer: () =&gt; Unit, exceptionHandler: (ManagementException) =&gt; Unit) = {&lt;br /&gt;    try {&lt;br /&gt;      var executeBlock = true&lt;br /&gt;&lt;br /&gt;      try {&lt;br /&gt;        initializer() //initialize the resources&lt;br /&gt;      } catch {&lt;br /&gt;        //forward exceptions to the handler&lt;br /&gt;        case e: Exception =&gt;&lt;br /&gt;          executeBlock = false //do not continue if initialization fails&lt;br /&gt;          exceptionHandler(new InitializationException(e))&lt;br /&gt;      }&lt;br /&gt;&lt;br /&gt;      if (executeBlock) {&lt;br /&gt;        try {&lt;br /&gt;          block // execute the block&lt;br /&gt;        } catch {&lt;br /&gt;          //forward exceptions to the handler&lt;br /&gt;          case e: Exception =&gt; exceptionHandler(new ExecutionException(e))&lt;br /&gt;        }&lt;br /&gt;      }&lt;br /&gt;    } finally {&lt;br /&gt;      //close all of the resources properly&lt;br /&gt;      resources.foreach( resource =&gt; {&lt;br /&gt;        try {&lt;br /&gt;          val value = resource()&lt;br /&gt;          if (value != null)&lt;br /&gt;            value.close()&lt;br /&gt;        } catch {&lt;br /&gt;          case e: Exception =&gt;&lt;br /&gt;            try {&lt;br /&gt;              exceptionHandler(new ClosingException(e))&lt;br /&gt;            } catch {&lt;br /&gt;              case fatal: Throwable =&gt; fatal.printStackTrace() //last resort&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;      })&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;So now, our exception handler signature takes a ManagementException, which has the original exception as its cause - accessable by e.cause or e.getCause(). We know, based on the type of ManagementException, where it is coming from. Instead, we could define three different exception handling methods, but I think it's easier to use if we only have to define (at most) one exception handler.&lt;br /&gt;&lt;br /&gt;Let's see an example:&lt;br /&gt;&lt;div  style="background-color: gray; color: white; overflow: auto;"&gt;&lt;pre&gt;&lt;br /&gt;var reader: BufferedReader = null&lt;br /&gt;var writer: BufferedWriter = null&lt;br /&gt;&lt;br /&gt;def getReader() = reader&lt;br /&gt;def getWriter() = writer&lt;br /&gt;&lt;br /&gt;def initResources() = {&lt;br /&gt;  reader = new BufferedReader(new FileReader("test.txt"))&lt;br /&gt;  writer = new BufferedWriter(new FileWriter("test_copy.txt"))&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;def handle(e: ManagementException) = {&lt;br /&gt;  e match {&lt;br /&gt;    case ie: InitializationException =&gt;&lt;br /&gt;      println("Failed to initialize: " + ie.getCause())&lt;br /&gt;    case ee: ExecutionException =&gt;&lt;br /&gt;      println("Could not copy files: " + ee.getCause())&lt;br /&gt;    case ce: ClosingException =&gt;&lt;br /&gt;      println("Failed to close a resource: " + ce.getCause())&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;//copy a file, line by line&lt;br /&gt;manage(getReader, getWriter) {&lt;br /&gt;  var line = reader.readLine&lt;br /&gt;  while (line != null) {&lt;br /&gt;    writer.write(line)&lt;br /&gt;    writer.newLine&lt;br /&gt;    line = reader.readLine&lt;br /&gt;  }&lt;br /&gt;} (initResources, handle)&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;This one passes the methods for initialization and exception handling as explicit parameters.&lt;br /&gt;&lt;br /&gt;Here's the same example with a different approach:&lt;br /&gt;&lt;div  style="background-color: gray; color: white; overflow: auto;"&gt;&lt;pre&gt;&lt;br /&gt;var reader: BufferedReader = null&lt;br /&gt;var writer: BufferedWriter = null&lt;br /&gt;&lt;br /&gt;implicit def initResources() = {&lt;br /&gt;  reader = new BufferedReader(new FileReader("test.txt"))&lt;br /&gt;  writer = new BufferedWriter(new FileWriter("test_copy.txt"))&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;implicit def handle(e: ManagementException) = {&lt;br /&gt;  e match {&lt;br /&gt;    case ie: InitializationException =&gt;&lt;br /&gt;      println("Failed to initialize: " + ie.getCause())&lt;br /&gt;    case ee: ExecutionException =&gt;&lt;br /&gt;      println("Could not copy files: " + ee.getCause())&lt;br /&gt;    case ce: ClosingException =&gt;&lt;br /&gt;      println("Failed to close a resource: " + ce.getCause())&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;br /&gt;//copy a file, line by line&lt;br /&gt;manage(() =&gt; reader, () =&gt; writer) {&lt;br /&gt;  var line = reader.readLine&lt;br /&gt;  while (line != null) {&lt;br /&gt;    writer.write(line)&lt;br /&gt;    writer.newLine&lt;br /&gt;    line = reader.readLine&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;This one uses implicit defs for our initialization and exception handling functions. For this to work, we cannot import the implicit defs of these functions from Arm because they would conflict. I should point out that if you provide one function explicitly, you have to provide the other explicitly as well. Also, this example defines getters for reader and writer "inline".&lt;br /&gt;&lt;br /&gt;&lt;h4&gt;Room for Improvement&lt;/h4&gt;The new syntax is not nearly as easy to read as the original. This concession was necessary, though, for the sake of completeness. The problem of an exception thrown from the handler still remains from the first post, as well.&lt;br /&gt;&lt;br /&gt;A couple of readers pointed me toward scalax, which provides a &lt;a href="http://scalax.scalaforge.org/api/scalax/control/ManagedResource.html"&gt;ManagedResource class&lt;/a&gt; which provides the same functionality using for-comprehensions. I took a look at it and it looks pretty well done, but I haven't yet had an opportunity to use it so I can't comment on  how it works in practice. I would be interested to see an example of this which manages more than one resource.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1213287780097066156-7634735867491529287?l=polyglot-window.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://polyglot-window.blogspot.com/feeds/7634735867491529287/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://polyglot-window.blogspot.com/2008/02/arm-blocks-in-scala-part-2.html#comment-form' title='9 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1213287780097066156/posts/default/7634735867491529287'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1213287780097066156/posts/default/7634735867491529287'/><link rel='alternate' type='text/html' href='http://polyglot-window.blogspot.com/2008/02/arm-blocks-in-scala-part-2.html' title='ARM Blocks in Scala, Part 2'/><author><name>Chris Hansen</name><uri>https://profiles.google.com/115790156504227129392</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh4.googleusercontent.com/-QNUxAOYtD-4/AAAAAAAAAAI/AAAAAAAAA2s/P3EtmA3Xgoc/s512-c/photo.jpg'/></author><thr:total>9</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1213287780097066156.post-8221964643669188897</id><published>2008-02-12T18:28:00.000-08:00</published><updated>2009-03-26T21:06:50.559-07:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='ARM'/><category scheme='http://www.blogger.com/atom/ns#' term='Automatic Resource Management'/><category scheme='http://www.blogger.com/atom/ns#' term='Java'/><category scheme='http://www.blogger.com/atom/ns#' term='block'/><category scheme='http://www.blogger.com/atom/ns#' term='ARM block'/><category scheme='http://www.blogger.com/atom/ns#' term='scala'/><title type='text'>ARM Blocks in Scala</title><content type='html'>Update: &lt;a href="http://polyglot-window.blogspot.com/2009/03/arm-blocks-in-scala-revisited.html"&gt;Here&lt;/a&gt;'s a better approach to Automatic Resource Management in Scala.&lt;br /&gt;&lt;br /&gt;Currently, there is a proposal by Joshua Bloch for the addition of &lt;a href="http://docs.google.com/View?docid=dffxznxr_1nmsqkz"&gt;Automatic Resource Management Blocks&lt;/a&gt; (ARM Blocks) to Java, possibly as soon as version 7. The idea is that Java should take the responsibility of correctly disposing of resources out of the hands of the developer, much like it did with memory management in its initial design. Personally, I think it is a great idea that wouldn't add too much baggage to the language.&lt;br /&gt;&lt;br /&gt;After seeing a couple of implementations of this concept in Scala (&lt;a href="http://blog.omega-prime.co.uk/2007/08/25/implementing-the-disposable-pattern-in-scala/"&gt;here&lt;/a&gt; and &lt;a href="http://www.saager.org/2007/12/30/automatic-resource-management-blocks.html"&gt;here&lt;/a&gt;), I decided to give it a try myself. I think you'll see that Scala is a very flexible language that already facilitates things like ARM Blocks without explicit language support - mostly thanks to functional programming constructs like closures. In this post, I will assume you have some basic to intermediate knowledge of Scala, including a basic knowledge of its function syntax: "(ArgType1, ArgType2, ...) =&gt; ReturnType".&lt;br /&gt;&lt;br /&gt;We will construct an Arm object (singleton) which will provide a usable syntax for an ARM Block and offer correct resource disposal.&lt;br /&gt;&lt;br /&gt;Here is a first pass:&lt;br /&gt;&lt;div style="background-color: gray; color: white; overflow: auto;"&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;object Arm {&lt;br /&gt;  type CloseType = { def close() }&lt;br /&gt;&lt;br /&gt;  def manage(resource: CloseType)(block: =&gt; Unit) = {&lt;br /&gt;    try {&lt;br /&gt;      block&lt;br /&gt;    } finally {&lt;br /&gt;      resource.close()&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;...and an example:&lt;br /&gt;&lt;div style="background-color: gray; color: white; overflow: auto;"&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;import Arm.manage&lt;br /&gt;&lt;br /&gt;//read in a file&lt;br /&gt;val reader = new BufferedReader(new FileReader("test.txt"))&lt;br /&gt;manage(reader) {&lt;br /&gt;  var line: String = reader.readLine&lt;br /&gt;  while (line != null) {&lt;br /&gt;    println(line)&lt;br /&gt;    line = reader.readLine&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;Arm.manage takes a resource to manage, and a block of code (no-arg function that does not return anything) to execute. The only restriction on the resource is that it has a close() method that does not return anything (implicit return type of Unit). The definition of &lt;span style="font-style:italic;"&gt;CloseType&lt;/span&gt; is just for readability. This is a form of &lt;a href="http://neilbartlett.name/blog/2007/09/13/statically-checked-duck-typing-in-scala/"&gt;statically checked "duck typing"&lt;/a&gt;. Notice, in the example, that the block of code passed into Arm.manage looks seamless - as if &lt;span style="font-style:italic;"&gt;manage&lt;/span&gt; was a Scala keyword. The only extra bit of clutter that is necessary is the "&lt;span style="font-style:italic;"&gt;import Arm.manage&lt;/span&gt;" (or &lt;span style="font-style:italic;"&gt;Arm._&lt;/span&gt; if you prefer), but I can live with that.&lt;br /&gt;&lt;br /&gt;This is simple and does exactly what we need, but it is limited to only one resource. We can do better:&lt;br /&gt;&lt;div style="background-color: gray; color: white; overflow: auto;"&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;object Arm {&lt;br /&gt;  type CloseType = { def close() }&lt;br /&gt;&lt;br /&gt;  def manage(resources: CloseType*)(block: =&gt; Unit) = {&lt;br /&gt;    try {&lt;br /&gt;      block&lt;br /&gt;    } finally {&lt;br /&gt;      resources.foreach( resource =&gt; {&lt;br /&gt;        try {&lt;br /&gt;          resource.close()&lt;br /&gt;        } catch {&lt;br /&gt;          case e: Exception =&gt; e.printStackTrace()&lt;br /&gt;        }&lt;br /&gt;      })&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;Here we use Scala's syntax for varargs: &lt;span style="font-style:italic;"&gt;CloseType*&lt;/span&gt;. Passing zero parameters is allowed here because &lt;span style="font-style:italic;"&gt;resources.foreach()&lt;/span&gt; does not execute if &lt;span style="font-style:italic;"&gt;resources&lt;/span&gt; is empty, but I could see an argument for requiring at least one param. This version of Arm.manage solves the problem of managing several resources, but introduces a new problem - what to do when the call to close() throws an exception. These difficulties are mentioned in the ARM proposal, with no solution settled upon. I propose using an optional callback, which is easy enough to do in Scala (and a variant of that would probably work in Java too, now that I think about it):&lt;br /&gt;&lt;div style="background-color: gray; color: white; overflow: auto;"&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;object Arm {&lt;br /&gt;  type CloseType = { def close() }&lt;br /&gt;&lt;br /&gt;  def manage(resources: CloseType*)(block: =&gt; Unit)(implicit exceptionHandler: (Exception) =&gt; Unit) = {&lt;br /&gt;    try {&lt;br /&gt;      block&lt;br /&gt;    } finally {&lt;br /&gt;      resources.foreach( resource =&gt; {&lt;br /&gt;        try {&lt;br /&gt;          resource.close()&lt;br /&gt;        } catch {&lt;br /&gt;          case e: Exception =&gt;&lt;br /&gt;            try {&lt;br /&gt;              exceptionHandler(e)&lt;br /&gt;            } catch {&lt;br /&gt;              case fatal: Throwable =&gt; fatal.printStackTrace() //last resort&lt;br /&gt;            }&lt;br /&gt;        }&lt;br /&gt;      })&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;...with an example:&lt;br /&gt;&lt;div style="background-color: gray; color: white; overflow: auto;"&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;val reader = new BufferedReader(new FileReader("test.txt"))&lt;br /&gt;val writer = new BufferedWriter(new FileWriter("test_copy.txt"))&lt;br /&gt;&lt;br /&gt;//copy a file, with exception handling&lt;br /&gt;manage(reader, writer) {&lt;br /&gt;  var line = reader.readLine&lt;br /&gt;  while (line != null) {&lt;br /&gt;    writer.write(line)&lt;br /&gt;    writer.newLine&lt;br /&gt;    line = reader.readLine&lt;br /&gt;  }&lt;br /&gt;} {e =&gt; //handle it}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;...and another:&lt;br /&gt;&lt;div style="background-color: gray; color: white; overflow: auto;"&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;val reader = new BufferedReader(new FileReader("test.txt"))&lt;br /&gt;val writer = new BufferedWriter(new FileWriter("test_copy.txt"))&lt;br /&gt;&lt;br /&gt;//copy a file, no exception handler&lt;br /&gt;manage(reader, writer) {&lt;br /&gt;  var line = reader.readLine&lt;br /&gt;  while (line != null) {&lt;br /&gt;    writer.write(line)&lt;br /&gt;    writer.newLine&lt;br /&gt;    line = reader.readLine&lt;br /&gt;  }&lt;br /&gt;}&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;Here is Arm in its first non-beta version. The exception handler is declared as "&lt;span style="font-style:italic;"&gt;implicit&lt;/span&gt;", which means that it is not required - as in the second example. The callback has to take an Exception as a parameter, however, which is not as specific as one could hope for. In Scala, this does not present too much of a problem because of &lt;a href="http://www.scala-lang.org/intro/patmatch.html"&gt;pattern matching&lt;/a&gt;. The real problem is what to do when the exception handler throws an exception and we need to keep closing the resources. I don't have a good answer for that one, but the "give up and just print a stack trace" approach is not unprecedented. If you don't believe me, just run the following Java code (I think I saw this concept in a Java Puzzler once):&lt;br /&gt;&lt;div style="background-color: gray; color: white; overflow: auto;"&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;Thread currentThread = Thread.currentThread();&lt;br /&gt;currentThread.getThreadGroup().uncaughtException(currentThread, &lt;br /&gt;  new RuntimeException("Oh no!"));&lt;br /&gt;System.out.println("Moving on");&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;Furthermore, we have no way to associate an exception with the object which was the source of the exception. There is no doubt in my mind that Arm.manage in this form can be improved upon, but it satisfies our goals. It even gives us control over what to do  when an exception is thrown during disposal (within limitations).&lt;br /&gt;&lt;br /&gt;One alternative to this implementation would be to declare an overridden Arm.manage method for each type of resource that one would like to manage (e.g. java.io.Closeable, java.sql.Statement, java.sql.Connection, etc.). This gives the benefit of dealing with a more specific type of exception in the callback method, and the possibility of resources that have a method other than close() to dispose them. This comes at the cost of a bit of clutter and rigidity since it does not support an arbitrary object with a close() method. It is definitely worth considering, but in the end I think the flexibility of the "duck typing" approach wins out here.&lt;br /&gt;&lt;br /&gt;Another technique that can be used with Arm.manage is &lt;a href="http://www.artima.com/weblogs/viewpost.jsp?thread=179766"&gt;implicit type conversion&lt;/a&gt; (aka views). This could be useful if you would like Arm.manage to call a method other than close(). Of course it won't call a method other than close(), but you can achieve the same effect. For example:&lt;br /&gt;&lt;div style="background-color: gray; color: white; overflow: auto;"&gt;&lt;br /&gt;&lt;pre&gt;&lt;br /&gt;  class Disposable {&lt;br /&gt;    def dispose(): Boolean = {&lt;br /&gt;      println("Disposing")&lt;br /&gt;      return true&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  abstract class AbstractCloseType {&lt;br /&gt;    def close()&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  implicit def disposable2closeable(disposable: Disposable): CloseType = {&lt;br /&gt;    new AbstractCloseType() {&lt;br /&gt;      def close() = {&lt;br /&gt;        disposable.dispose()&lt;br /&gt;      }&lt;br /&gt;    }&lt;br /&gt;  }&lt;br /&gt;&lt;br /&gt;  val disposable = new Disposable()&lt;br /&gt;  manage(disposable) {&lt;br /&gt;    //do something&lt;br /&gt;  }&lt;br /&gt;&lt;/pre&gt;&lt;br /&gt;&lt;/div&gt;&lt;br /&gt;I hope I've shown some of the power and flexibility of Scala. Many of you already know this and it's is why you're reading posts about Scala. To the others - this is just scratching the surface of Scala's potential, I believe. Scala is malleable enough to let you do things like &lt;a href="http://etorreborre.blogspot.com/2007/11/software-design-is-like-magic-trick.html"&gt;creating DSLs&lt;/a&gt; or to write simple code that is virtually indistinguishable from Java. All while not having to give up on static typing or the JVM (or CLR for that matter). &lt;br /&gt;&lt;br /&gt;I look forward to writing more code in Scala. I don't know if it will be the "Next Big Thing(TM)", but it is certainly refreshing - and that doesn't hurt when it comes to success.&lt;br /&gt;&lt;br /&gt;Update: See the &lt;a href="http://polyglot-window.blogspot.com/2008/02/arm-blocks-in-scala-part-2.html"&gt;follow-up&lt;/a&gt;.&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1213287780097066156-8221964643669188897?l=polyglot-window.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://polyglot-window.blogspot.com/feeds/8221964643669188897/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://polyglot-window.blogspot.com/2008/02/arm-blocks-in-scala.html#comment-form' title='10 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1213287780097066156/posts/default/8221964643669188897'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1213287780097066156/posts/default/8221964643669188897'/><link rel='alternate' type='text/html' href='http://polyglot-window.blogspot.com/2008/02/arm-blocks-in-scala.html' title='ARM Blocks in Scala'/><author><name>Chris Hansen</name><uri>https://profiles.google.com/115790156504227129392</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh4.googleusercontent.com/-QNUxAOYtD-4/AAAAAAAAAAI/AAAAAAAAA2s/P3EtmA3Xgoc/s512-c/photo.jpg'/></author><thr:total>10</thr:total></entry><entry><id>tag:blogger.com,1999:blog-1213287780097066156.post-4228220917814127251</id><published>2008-02-11T23:42:00.000-08:00</published><updated>2008-02-12T00:21:57.409-08:00</updated><category scheme='http://www.blogger.com/atom/ns#' term='introduction'/><category scheme='http://www.blogger.com/atom/ns#' term='programming'/><category scheme='http://www.blogger.com/atom/ns#' term='computer science'/><title type='text'>Welcome</title><content type='html'>It's not much to look at as of yet, but welcome my blog anyway. My name is Chris W. Hansen, and I'm a computer programmer by trade. Others would demand the title "Software Developer" or "Software Engineer", and they are fine titles, but I feel that programmer is a term that sufficiently describes what it is I actually do. Besides, whenever I tell someone I'm a Software Engineer, they inevitably say something like, "Oh... so what is it exactly that you &lt;i&gt;do&lt;/i&gt;?"&lt;br /&gt;&lt;br /&gt;In future posts, I plan to discuss various aspects of computers, technology and programming, including programming languages, techniques and computer science theory (you know, the "fun stuff"). Right now, I'm in the process of learning an exciting (to me) language called &lt;a href="http://www.scala-lang.org/"&gt;Scala&lt;/a&gt;, so I imagine many of my posts (at least initially) will be on that topic.&lt;br /&gt;&lt;br /&gt;I'm relatively new to blogging in general, so any tips or advice as I go along are welcome.&lt;br /&gt;&lt;br /&gt;Before moving on to my next post (when it arrives), you may want to brush up on Scala. Here are a few links to get started (in no particular order).&lt;br /&gt;&lt;ul&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://www.scala-lang.org/intro/index.html"&gt;Scala Introduction&lt;/a&gt; - the basics, straight from the horse's mouth&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://www.codecommit.com/blog/scala/scala-for-java-refugees-part-1"&gt;Scala for Java Refugees&lt;/a&gt; - this is a very informative read, and I strongly recommend the whole (6-part) series&lt;/li&gt;&lt;br /&gt;&lt;li&gt;&lt;a href="http://www.artima.com/scalazine/articles/steps.html"&gt;First Steps to Scala&lt;/a&gt; - written by the language designers themselves&lt;/li&gt;&lt;br /&gt;&lt;/ul&gt;&lt;div class="blogger-post-footer"&gt;&lt;img width='1' height='1' src='https://blogger.googleusercontent.com/tracker/1213287780097066156-4228220917814127251?l=polyglot-window.blogspot.com' alt='' /&gt;&lt;/div&gt;</content><link rel='replies' type='application/atom+xml' href='http://polyglot-window.blogspot.com/feeds/4228220917814127251/comments/default' title='Post Comments'/><link rel='replies' type='text/html' href='http://polyglot-window.blogspot.com/2008/02/welcome.html#comment-form' title='2 Comments'/><link rel='edit' type='application/atom+xml' href='http://www.blogger.com/feeds/1213287780097066156/posts/default/4228220917814127251'/><link rel='self' type='application/atom+xml' href='http://www.blogger.com/feeds/1213287780097066156/posts/default/4228220917814127251'/><link rel='alternate' type='text/html' href='http://polyglot-window.blogspot.com/2008/02/welcome.html' title='Welcome'/><author><name>Chris Hansen</name><uri>https://profiles.google.com/115790156504227129392</uri><email>noreply@blogger.com</email><gd:image rel='http://schemas.google.com/g/2005#thumbnail' width='32' height='32' src='//lh4.googleusercontent.com/-QNUxAOYtD-4/AAAAAAAAAAI/AAAAAAAAA2s/P3EtmA3Xgoc/s512-c/photo.jpg'/></author><thr:total>2</thr:total></entry></feed>
