Thursday, July 31, 2008

Progress in Functional Java

I have been happy lately to see the progress in Functional Java. A project truly arrives when it becomes the inspiration for other clever ideas. Witness Lazy Error Handling in Java, Part 1: The Thrower Functor.

Every few days comes another fun bit of functional programming creeping its way in to my workaday language, Java. Current wish list item: the fj team deploys to a public Maven repository so I can just say:

<dependency>
    <groupId>fj</groupId>
    <artifactId>functionaljava</artifactId>
    <version>2.8</version>
</dependency>

UPDATE: This just gets more interesting: Lazy Error Handling in Java, Part 2: Thrower is a Monad and Lazy Error Handling in Java, Part 3: Throwing Away Throws.

Thursday, July 10, 2008

Guice, main and startup configuration flags

Here is a small trick we use in an in-house program wired with Google Guice. The goal is to pick the wiring configuration from the command-line without too many contortions.

The idea is to use enums to represent the wiring, and using the command-line to pick the enum. Thus:

enum WhichOne {
   /** Uses module "A", defined elsewhere. */
   ONE(new ModuleA()),
   /** Uses module "A" and "B", defined elsewhere. */
   TWO(new ModuleA(), new ModuleB());

   private final Module module;

   WhichOne(final Module... modules) {
       module = new CompoundModule(modules);
   }

   public Module getModule() {
       return module;
   }
}

class CompoundModule extends AbstractModule {
   private final Module[] modules;

   CompoundModule(final Module... modules) {
       this.modules = modules;
   }

   @Override
   public void configure() {
       for (final Module module : modules)
           install(module);
   }
}

class Main {
    public static void main(final String... arguments) {
        // Real programs use args4j
        final WhichOne whichOne = WhichOne.valueOf(arguments[0]);
        final Module module = whichOne.getModule();
        final Injector injector = Guice.createInjector(module);

        injector.createInstance(MyProgram.class);
   }
}

Now I can pick configuration on the command line:

$ my_program ONE # use module "A"
$ my_program TWO # use module "A" and "B"

Friday, June 20, 2008

Guice support in IntelliJ IDEA

I just had a surprise reply from Dmitriy Demerov of JetBrains:

The latest Early Access Preview builds of Diana (available at http://www.jetbrains.net/confluence/display/IDEADEV/Diana+EAP ) include a plugin for Guice support. You're very much welcome to give it a try and submit your feedback on it.

I had responded to a sales manager at JetBrains that one item on my wish list for IDEA was direct Guice support.

Yippee!

Thursday, May 08, 2008

Bad concurrency advice: interned Strings

I just read Thread Signaling from Jacob Jenkov. It is fine as far as it goes to introduce the reader to Object.wait() and Object.notify().

But it has one fatal flaw: it uses a literal java.lang.String for coordinating between threads. Why is this wrong?

Strings are interned by the compiler. To quote the javadocs: All literal strings and string-valued constant expressions are interned. Using a literal string means that any other code anywhere in the JVM, even in other libraries, which use the same String literal value all share the same object for wait() and notify(). This code:

public void dastardly() {
    "".notify();  
}

will wake up a thread waiting on empty string, including one in utterly unrelated code.

Don't do that. Instead, create a fresh Object for coordinating threads. This age-worn advice for lock objects (synchronize(lock)) applies just as much to objects used to coordinate threads.

Wednesday, May 07, 2008

Friday, May 02, 2008

Good News - JavaOne 2008

JPMorgan is sending me to JavaOne 2008!

Sorry for no posts since November — work has been inordinately busy. I will post from San Francisco.

Thursday, November 22, 2007

Followup to Feature request for JDK7: delegation

A followup to Feature request for JDK7: delegation.

In the comments to my post requesting better IOC support in JDK7 Sam asks, "The keyword *is* needed... what if the delegate is editing the behaviour of one of the methods? Perhaps to do some logging. You can't do that with the original code." For some context, he refers to code like this:

class Scout implements Camper {
    public void camp() { ... }
}

class BoyScout implements Camper {
    BoyScout(Scout scout) {
        this = scout;
    }

    public void camp() {
        callHomeFirst();
        ??? // How to forward to delegate?
    }
}

I've thought about this for a bit and I think I would go with this:

public void camp() {
    callHomeFirst();
    Camper.this.camp();
}

Why?

I have several reasons:

  1. It introduces no new syntax or keywords.
  2. It does not collide with any existing use.
  3. It is reminiscent of inner class access to their outer containing class this.

My first impulse was for some kind of casting:

((Camper) this).camp();

But this is just ugly! Then using the JLS calls qualified this occurred to me, this:

Camper.this.camp();

Wednesday, October 31, 2007

Immutable objects in Java

I just read a clever post from JP Moresmau on a functional language he is writing which translates to Java.

One idea which lept out at me was how to provide setters to immutable objects in Java: the setters are instance factory methods, thus:

class DontTreadOnMe {
    public final String species;
    public final int length;

    DontTreadOnMe(String species, int length) {
        this.species = species;
        this.length = length;
    }

    // Snakes can grow but cannot change species
    DontTreadOnMe setLength(int length) {
        return new DontTreadOnMe(length);
    }
}

This works rather nicely for code which uses the convention. Unfortunately, the getter/setter idea is so firmly embedded in the fingertips of Java coders, that I expect this bug frequently:

final DontTreadOnMe copperhead
        = new DontTreadOnMe("Copperhead", 1);
// Grow in length
copperhead.setLength(2);
// Oops! Does not work as expected but compiles

My preference is for the bean properties proposal. Make immutables with read-only properties; use copy-construction to make new objects with different field values (fortunately Java copy construction is vastly simpler than C++).

Saturday, October 27, 2007

Hamcrest matchers

I missed this post from Joe Walnes a while ago on using Hamcrest matchers for more than testing.

I appreciate their DSL-like quality and clever mixture of literate class names, static factory methods and Java generics.

In his post Joe Walnes references HÃ¥kan RÃ¥berg's nice idea for filtering collections with Hamcrest matchers, but unfortunately that post links to no code, usage examples. select and reject are trivial to code:

public static <T> List<T> select(
        final Collection<T> c,
        final Matcher<T> matcher) {
    final List<T> select = new ArrayList<T>();

    for (final T t : c)
        if (matcher.matches(t))
            select.add(t);

    return select;
}

public static <T> List<T> reject(
        final Collection<T> c,
        final Matcher<T> matcher) {
    return select(c, not(matcher));
}

The statically-typed query API is not so trivial to toss off early in the morning. Hopefully HÃ¥kan RÃ¥berg will release code at some point.

UPDATE: Nat Pryce was kind enough to point to Hamcrest Collections, itself inspired by HÃ¥kan RÃ¥berg's post. Thanks, Nat!

Tuesday, October 23, 2007

Feature request for JDK7: delegation

Some while back I wrote about delegation for Java. Delegation? By this I mean direct language support for constructor-based dependency injection of interface implementation, a.k.a. mixins.

Many interesting proposals for JDK7 are in the air: the smell of change is replacing the mustiness of an aging language and I want my chance to improve Java while there is a open window of opportunity.

About delegation

For more details follow my three-year old posting. In a nutshell, delegation is assignment to this in a constructor to inject an interface implementation without the need for manually coding boilerplate forwarding methods.

An example makes this more clear:

interface Blogger {
    boolean post(final String entry);
}

// Without delegation
class MessyCoder implements Blogger {
    private final Blogger bloggerDelegate;

    MessageCodeBlogger(Blogger bloggerDelegate) {
        this.bloggerDelegate = bloggerDelegate;
    }

    public boolean post(final String entry) {
        return bloggerDelegate.post(entry);
    }
}

// With delegation
class CleanCoder implements Blogger {
    CleanCoder(Blogger bloggerDelegate) {
        this = bloggerDelegate;
    }
}

In an example this small, the gain in clarity and bug-avoidance is limited, but for larger interfaces or for multiple interfaces, the gain is proportionately larger.

The bigger picture

Providing cleaner code is only a small benefit of delegates. A larger benefit is that of mixins: dynamic implementation inheritance without breaking the single-inheritance contract of Java. Extension by composition—rather than inheritance—becomes a first-class syntax citizen of the language.

Delegates solve the mixin problem raised by Bruce Eckels about Java generics, and do so without needing aspects. (Although, behind the scenes, the compiler very well may use aspects to implement delegates. But you the over-committed programmer need not spend your short time on this point.)

Of course, you could always just fake it or do it the hard way.

UPDATE: More thoughts here and another solution.

Thursday, October 11, 2007

Java data validation trick with bit-twiddling

I have a specialized value object with the property that fields can be null but only in a particular order:

class Data {
    private final String field1;
    private final String field2;
    private final String field3;

    public Data(String field1, String field2,
            String field3) {
        if (!valid(field1, field2, field3))
            throw new IllegalArgumentException();

        this.field1 = field1;
        this.field2 = field2;
        this.field3 = field3;
    }

    // ...
}

The rule is simple: Given the order of the fields 1-4, any later field may be null provided that no earlier field is null. That is, "abc", "def", null is ok but "abc", null, "ghi" is invalid.

So the question becomes, How to code up valid?.

The straight-forward approach of nested if-else blocks becomes particularly unwieldy as more fields are added. But it turns out there is a clever solution using bit-twiddling:

private static boolean valid(String... fields) {
    byte flag = 0; // Fails after 8 fields

    // Sets the i-th bit for each non-null field
    for (int i = 0; i < fields.length; ++i)
        if (null != fields[i])
            flag |= (1 << i);

    // Math trick: 2n ∧ 2n-1 = 0
    return 0 == (flag & flag + 1);
}

In words: the flag has a 1-bit for each non-null field in argument order. The validation condition only holds when the 1 bits are in sequence starting at the 0-th position with no gaps, e.g., 00000111. That particular bit pattern is the same as one less than some power of two. Use the math fact that in bit arithmetic, 2n ∧ 2n-1 = 0 to check the condition.

Thanks to this powers-of-two problem for pointing the way.

Wednesday, October 10, 2007

Dethreading a chicken

Anyone who has tried knows what messy task deboning a chicken is (unless you are Morou Ouattara.) Likewise I face the messy task of protecting multi-threaded legacy code from itself.

I face a complex graph with an elaborate API. It is thread-safe in that individual nodes are locked, but it is not thread-consistent: changes traversing the graph are not isolated from each other.

What to do?

One approach which is of general application is to dethread the data structure. That is, turn it from multi-threaded access to single-threaded.

The task is made much simpler by the JDK5 concurrency library. First, create a facade for the original API:

interface Complexity {
    void methodOne(int argOne);
    int methodTwo();
    // ... ad nauseum
}

Next create command classes for each method call in the API:

class MethodOne
        extends Runnable {
    private final Complexity realGraph;
    private final int argOne;

    MethodOne(Complexity realGraph, int argOne) {
        this.realGraph = realGraph;
        this.argOne = argOne;
    }

    void run() {
        realGraph.methodOne(argOne);
    }
}

class MethodTwo
        extends Callable<Integer> {
    private final Complexity realGraphy;

    MethodTwo(final Complexity realGraph) {
        this.realGraph = realGraph;
    }

    Integer call() {
        return realGraph.methodTwo();
    }
}

// ... ad nauseum

Finally, wire the facade to forward calls to a queue for replay into the real graph with a dedicated single thread:

class SingleThreadComplexity implements Complexity {
    private final ExecutorService commands
            = Executors.newSingleThreadExecutor();
    private final Complexity realGraph
            = new OriginalMultiThreadComplexity();

    public void methodOne(int argOne) {
        commands.submit(new MethodOne(realGraph, argOne);
    }

    public int methodTwo() {
        try {
            return commands.submit(new MethodTwo(realGraph)).get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    // ... ad nauseum
}

Finishing up

Unless the caller has special latency needs violated by the queueing of commands, the facade is a drop-in replacement for the original complex graph but with the new property that the original is always accessed sequentially from the same thread. Goetz calls this property thread confinement.

The complex, messy graph—a fowl thing indeed—is now dethreaded.

Friday, September 14, 2007

Running "N" foreground tasks in Java

A handy helper method for running "N" foreground tasks in Java with a timeout. A more sophisticated technique would permit examination of job status:

/**
 * Invokes <var>n</var> copies of the given <var>runnable</var>, timing out
 * after <strong>10 unit</strong> with {@code InterruptedException}.
 *
 * @param n the number of threads to run
 * @param runnable the thread body to execute
 * @param timeout the timeout
 * @param unit the timeout unit
 *
 * @throws InterruptedException if timed out
 */
public static void invokeNCopiesWithTimeout(final int n,
        final Runnable runnable, final long timeout, final TimeUnit unit)
        throws InterruptedException {
    final ExecutorService pool = newFixedThreadPool(n);

    pool.invokeAll(
            Collections.<Callable<Void>>nCopies(n, new Callable<Void>() {
                public Void call() {
                    runnable.run();
                    return null;
                }
            }));

    pool.awaitTermination(timeout, unit);
}

I find this particularly useful for blackbox concurrency testing. I run, say, 100 threads which both read and write to a common data structure, and accept the lack of exceptions as empirical evidence of safeness. (In truth, it only provides a comfort zone, not a proof. Reasoning about threads is difficult when maintaining disparate interacting components.)

Monday, September 10, 2007

Performing fixed amounts of work with blocking queues

A colleague of mine showed me a nice idiom with BlockingQueue for performing a fixed amount of work:

final List<T> work = new ArrayList<T>(N);

for (;;) {
    // Wait until there is some work
    work.add(queue.take());
    // Get more work, if available
    queue.drainTo(work, N - 1);

    for (final T item : work)
        process(item);

    work.clear();
}

This idiom works on 1 to N chunks at a time efficiently and succinctly.

An example use is batching SQL updates. At the top of the loop begin the batch transaction after take() and finish the batch after the processing loop.

UPDATE: This idiom is also more efficient when unbounded amounts of work:

queue.drainTo(work);

Every call to take() is blocking and checks a lock — essentially giving up any remaining thread time slice. Using drainTo(work) avoids this lost thread work, cutting down on lock checks.

Tuesday, August 21, 2007

Cygwin BASH wrapper for Maven deploy:deploy-file

I frequently use Maven's deploy:deploy-file mojo for building project-local repositories.

Many interesting 3rd-party Java libraries are not (yet) available from public Maven repositories (the otherwise excellent dev.java.net projects are particularly weak in this respect), but I want to use them in my project POM. What to do?

I store them with my project. This is not an ideal solution, but it is practical.

To help me deploying jars, sources and javadocs I wrote a simple BASH wrapper script for Cygwin (to run under Linux/UNIX requires a trivial change). Here is typical use:

$ mvn-file-deploy ~/IdeaProjects/Scratch/lib cool-library-1.0.4.jar org.cool.library:cool-library:1.0.4
$ mvn-file-deploy -S ~/IdeaProjects/Scratch/lib cool-library-1.0.4-sources.jar org.cool.library:cool-library:1.0.4
$ mvn-file-deploy -J ~/IdeaProjects/Scratch/lib cool-library-1.0.4-javadocs.jar org.cool.library:cool-library:1.0.4

And the script itself:

#!/bin/bash

function help()
{
    cat <<'EOH' | fmt
Usage: mvn-file-deploy [options] REPO_PATH FILE_PATH DESCRIPTOR [CLASSIFIER]

Use mvn-file-deploy as a helper for 'mvn deploy:deploy-file' when using Cygwin.

EOH
    cat <<'EOH'
Options:
  -h, --help          Print this help message
      --version       Print program version
  -S, --sources       Deploy sources
  -J, --javadocs      Deploy javadocs
  -q, --quiet         Do not print maven command
EOH
    cat <<'EOH' | fmt

Other options are passed to Maven.  (BROKEN)

Examples:

The most common use is to run it like this:

    $ mvn-file-deploy C:/my/project/lib C:/some/interesting.jar groupId:artifactId:version

Or if you use a classifier (e.g., jdk5):

But sometimes like this.

    $ mvn-file-deploy C:/my/project/lib C:/some/interesting.jar groupId:artifactId:version classifier

Report bugs to <binkley@alumni.rice.edu>.
EOH
}

function version()
{
    cat <<'EOV' | fmt
mvn-file-deploy 1.0
Copyright (C) 2007 JPMorganChase, Inc.  All rights reserved.
EOV
}

function fatal()
{
    echo "$0: $*" >&2
    exit 2
}

function usage() 
{
    cat <<'EOU' | fmt >&2
usage: mvn-file-deploy [options] REPO_PATH FILE_PATH DESCRIPTOR [CLASSIFIER]
EOU
}

eval set -- "$(getopt -o hJSq --long help,javadocs,sources,quiet,version -n "$0" -- "$@")"

declare -a maven_opts
declare -a args

for opt
do
    shift
    case "$opt" in
        -h|--help ) help ; exit 0 ;;
        -J|--javadocs ) classifier=-Dclassifier=javadocs ;;
        -S|--sources ) classifier=-Dclassifier=sources ;;
        --version ) version ; exit 0 ;;
        -q|--quiet ) quiet=t ; maven_opts=("${maven_opts[@]}" "$opt") ;;
        -- ) break ;;
        -* ) maven_opts=("${maven_opts[@]}" "$opt") ;;
    esac
done

case $# in
    3 ) repo_path="$1"
        file_path="$2"
        descriptor="$3" ;;
    4 ) repo_path="$1"
        file_path="$2"
        descriptor="$3"
        classifier=-Dclassifier="$4" ;;
    * ) usage ; exit 2 ;;
esac

(cd "$repo_path" 2>/dev/null) || \
    fatal "No such repository path: $repo_path"

repo_url="file://$(cygpath -am "$repo_path")"
file_path="$(cygpath -am "$file_path")"

[[ -r "$file_path" ]] || \
    fatal "No such artifact: $file_path"

triplet=($(echo $descriptor | tr : ' '))

(( 3 == ${#triplet[*]} )) || \
    fatal "Descriptor not groupId:artifactId:version format: $descriptor"

packaging=-Dpackaging="${file_path##*.}"

[[ -n "$quiet" ]] ||
    echo mvn "${maven_opts[@]}" deploy:deploy-file -Durl="$repo_url" \
        -DrepositoryId=project -Dfile="$file_path" -DgroupId=${triplet[0]} \
        -DartifactId=${triplet[1]} -Dversion=${triplet[2]} \
        $packaging $classifier
exec mvn "${maven_opts[@]}" deploy:deploy-file -Durl="$repo_url" \
    -DrepositoryId=project -Dfile="$file_path" -DgroupId=${triplet[0]} \
    -DartifactId=${triplet[1]} -Dversion=${triplet[2]} \
    $packaging $classifier

Sunday, August 19, 2007

Recursive "toString"

Sometimes for debugging I want to dump an object recursively. That is, I'd like to see not just an Apache Commons Lang-style toString, but a recursive version which descends fields to display their inner bits as well.

Rather than complain, I coded my own. Enjoy!

public static String recursiveToString(final Object o) {
    final StringBuilder buffer = new StringBuilder();

    recursiveToString(new StringBuilder(), o, buffer,
            new HashSet<Object>());

    return buffer.toString();
}

private static void recursiveToString(final StringBuilder prefix,
        final Object o, final StringBuilder buffer,
        final Set<Object> seen) {
    if (null == o) {
        buffer.append("null\n");
        return;
    }

    // Mark back references with angle brackets
    if (seen.contains(o)) {
        buffer.append('<');
        objectToString(o, buffer);
        buffer.append(">\n");
        return;
    }

    seen.add(o);

    objectToString(o, buffer);

    // TODO: More clever to see if protection domain is in the JDK
    if (shouldNotRecurse(o, o.getClass().getPackage().getName())) {
        buffer.append('=');
        buffer.append(o);
        buffer.append('\n');
        return;
    }

    buffer.append("={");
    buffer.append('\n');

    final StringBuilder fieldPrefix = new StringBuilder(prefix);
    fieldPrefix.append("  ");

    for (final Field field : o.getClass().getDeclaredFields()) {
        field.setAccessible(true);
        buffer.append(fieldPrefix);
        buffer.append(field.getName());
        buffer.append('(');
        buffer.append(Modifier.toString(field.getModifiers()));
        buffer.append(")=");

        try {
            recursiveToString(fieldPrefix, field.get(o), buffer, seen);
        } catch (final IllegalAccessException e) {
            buffer.append("? (");
            buffer.append(e.getMessage());
            buffer.append(')');
        }
    }

    buffer.append(prefix);
    buffer.append("}\n");
}

private static boolean shouldNotRecurse(final Object o,
        final String packageName) {
    try {
        return (packageName.startsWith("java.") || packageName
                .startsWith("javax.")) && !Object.class
                .getMethod("toString")
                .equals(o.getClass().getMethod("toString"));
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    }
}

private static void objectToString(final Object o,
        final StringBuilder buffer) {
    buffer.append(o.getClass().getName());
    buffer.append('@');
    buffer.append(Integer.toHexString(System.identityHashCode(o)));
}

Luboš Motl answers some physics questions

Wow! I miss physics sometimes.

Wednesday, July 25, 2007

Monday, July 09, 2007

More with Java enums: simulating inheritance

One drawback to the Java enum is the lack of inheritance. Java uses inheritance for many reasons, one of which is implementation inheritance. (In C++ you would use private inheritance for the same reason.)

To recapture implementation inheritance with enums, use the visitor pattern:

class Convert {
    public interface Vivid {
        char character();
    }

    public static <E extends Enum<E> & Vivid> E from(
            E[] values, char character) {
        for (E e : values)
            if (e.character() == character)
                return e;

        throw new IllegalArgumentException("Boring: " + character);
    }
}

enum Men implements Convert.Vivid {
    OLIVIER('L'), WAYNE('J');

    private final char character;

    Men(char character) {
        this.character = character;
    }

    public char character() {
        return character;
    }

    public static Men valueOf(char character) {
        return Convert.from(values(), character);
    }
}

The implementation of valueOf(char):Men is handled in Convert and can be reused in other enum classes.

Thursday, June 14, 2007

Download web pages in BASH

BASH is quite amazing. From Bhaskar V. Karambelkar comes Bash shell tricks and this gem (with some small corrections):

function headers()
{
    server=$1
    port=${2:-80}
    exec 5<>/dev/tcp/$server/$port
    echo -ne "HEAD / HTTP/1.0\r\nHost: $server:$port\r\n\r\n" >&5
    cat <&5
    exec 5<&-;
}

I work behind a corporate firewall, so I need web proxy settings. No problem, BASH is still amazing:

function webget()
{
    declare -a parts
    parts=($(echo $1 | tr / ' '))
    protocol=${parts[0]}
    server=${parts[1]}
    path=$(echo $1 | sed "s,$protocol//$server,,")

    exec 5<>/dev/tcp/$http_proxy_server/$http_proxy_port
    echo -ne "GET $path HTTP/1.0\r\nHost: $server\r\n\r\n" >&5
    cat <&5
    exec 5<&-;
}

Usage is obvious:

$ webget http://www.ccil.org/jargon/
# Out pops the top page for Jargon File Resources

UPDATE: Also useful for talking to SMTP (email) servers:

$ exec 5<>/dev/tcp/localhost/smtp
$ read -u 5 line
$ echo $line
220 my.full.host.name ESMTP ...
$ echo QUIT >&5
$ read -u 5 line
$ echo $line
221 2.0.0 my.full.host.name closing connection

This also shows that BASH knows to map the SMTP service to port 25.

Monday, June 11, 2007

Excellent advice on Java exceptions

Excellent advice on avoiding exception anti-patterns in Java from Tim McCune, Exception-Handling Antipatterns. Particularly noxious are the anti-patterns which swallow exceptions.

Quick trivial quiz.

  1. Does this code compile?
  2. If it compiles, what happens at runtime?
try {
    throw null;
} catch (final Throwable t) {
    System.out.println("t = " + t);
}

Before you chuckle too hard, recall that this is a perfectly valid C++ program, if contrived, and prints Something integral: 0:

#include <iostream>

int
main(const int argc, const char *argv[])
{
  try {
    throw 0;
  } catch (const int i) {
    std::cout << "Something integral: " << i << std::endl;
  } catch (...) {
    std::cout << "Something exceptional." << std::endl;
  }
}

UPDATE: I fixed the title.

Friday, June 08, 2007

Style, taste, sensibilities in coding

Chris Aston has an eminently sensible post on programming in the small (not his words[*]), Coding Against the Grain, on some coding style and taste points that have been part of my habits nearly as long as I have programmed.

He emphasizes balance and clarity and cautions against turning objects into stand-ins for global variables: the function is given its due.

To elaborate on his points, I often treat objects as small bundles of encapsulated state with public methods that tie private fields to private functions. A simple example illustrates:

class UsefulExample {
    private int count;

    public String repeatMessage(String message) {
        return repeatMessage(message, count);
    }

    static String repeatMessage(String message,
            int count) {
        StringBuilder builder = new StringBuilder(message);

        for (int i = 1; i < count; ++i)
            builder.append(' ').append(message);

        return builder.toString();
    }
}

This example is not very interseting, but it makes it easy to list benefits:

  • Testing the functions independent of the encapsulated state is easy.
  • Changing the algorithm of functions does not affect public methods.
  • If the functions are common across classes, refactoring them out to a common utility class is simple.
  • Design changes in the encapsulated state do not impact functions.

In effect, the I have decoupled encapsulated state within the object from implementation algorithms within the functions, and use public methods to connect them together.

This is carrying a common design pattern from "programming in the large" into "programming in the small", with the same advantages. The decoupling of state from algorithm is an old idea [PDF].

More on programming in the small

Ivan Moore has a delightful series of posts on Programming in the Small well worth reading.

The all-dancing, all-singing LockSmith plugin for IntelliJ

I've never been willing to pay for IntelliJ plugins, but LockSmith from the very clever Sixth & Red River may change my mind.

This is a list of features which made me look twice:

  • Split Lock
  • Merge Locks
  • Make Class Thread-Safe
  • Convert Field to Atomic
  • Convert Field to ThreadLocal
  • Lock Call-Sites of Method
  • Convert Simple Lock to Read-Write Lock
  • Convert Read-Write Lock to Simple Lock
  • Convert Synchronization Field to Lock
  • Split Critical Section
  • Shrink Critical Section
  • Merge Critical Sections

Fortunately, I work for an excellent employer, and may be able to wrangle a group bulk license for my team for LockSmith and other wonderful plugins.