Positive logic

20. August, 2010

I just read another great post on Daily WTF (“Boolean Illogic“). Question: Does validation occur when the status is valid?

if (statusIsNotValid.compareTo( Boolean.FALSE ) != 0) skipValidation = false;

Another great example why you should prefer positive logic.


Using the FindBugs plugin for Maven with Java 5

16. July, 2010

If you use the Maven 2 FindBugs plugin with Java 5 code, you will get a lot of errors like:

    Can't use annotations when running in JDK 1.4 mode!
    Can't use JDK 1.5 for loop syntax when running in JDK 1.4 mode!
    Can't use generics unless running in JDK 1.5 mode!
    Can't use enum as a keyword in pre-JDK 1.5 target

The solution is to set the targetJdk (even though this option isn’t mentioned in the docs and even mvn help:describe can’t find it):

                <plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>findbugs-maven-plugin</artifactId>
                    <version>2.3.1</version>
                    <configuration>
                        <targetJdk>1.5</targetJdk>
                    </configuration>
                </plugin>

Note that you should clean your project; otherwise the new option may not be used for some reason.


Jazoon 2010, day 1, part 2

7. June, 2010

Here is the rest of day 1 (cont’d from previous post):

Construction Techniques for Domain Specific Languages by Neal Ford

I’ve seen this talk before. Maybe in 2008?

Slides aren’t on Neal’s homepage nor on his github.

Do you really get class loaders? by Jevgeni Kabanov

Nice talk with lots of exceptions you’ve never seen before. It’s a good, real-world example how something simple (like class loading which is basically just loading streams of bytes from a list of places) can turn into a nightmare if you just add one single, innocent rule (like the web guys did back then with JSP 1.0 when they decided to reverse the order of lookups).

97 Things Every Programmer Should Know by Kevlin Henney

Kevlin has been busy with a new book: 97 Things Every Programmer Should Know (link goes to a page with the ToC which links to the content which is CC’d).

Some examples:

Best of all: Many of these rules date back to the 1960’s! Time to apply some of these rules 🙂

That was day 1. On to day 2!


Jazoon 2010 Day 1

2. June, 2010

So, this is the great wrap-up of Jazoon 2010, day 1. What did I have?

The keynote by Danny Coward

Java SE and JavaFX: The Road Ahead. After the acquisition by Oracle, everyone was curious as to what happens to Java. Unfortunately, the slides aren’t online, yet but from my faint memory, we might get closures after all and with a sane syntax, too. Plus all the stuff mentioned on Sun’s JDK 7 page. ATM, this stuff is a bit fluent and it’s hard to get a definitive list but something is moving at least.

From my point of view, closures and all the other language features are too late for the Java language (important companies won’t upgrade to Java 7 and time soon, some of them even cling to 1.4!) but the implementation in the main language of the Java VM will allow to build better and faster non-Java languages on top of the VM. Now if the VM would include a compiler API to build JNI code for native libraries on the fly, we would have a worthy challenger for .NET. Yeah … I know. A man can have dreams, okay?

And there was some talk about JavaFX. It seems that the technology is starting to reach its beta-phase, soon (see my notes for the second day). He showed one demo: Geo View of Vancouver 2010. It’s a world map with which country won how many medals and when you open one of the blobs, you get the names of the athletes in a fan-out widget. You can click on the name to get more information (like the photo) or you can compare the results against countries with the same number of athletes or population or closest GDP or just closest geographically. It gives a nice example how to visualize a lot of data and wade through them intuitively.

Client / Server 2.0 with Java and Flex by James Ward

James showed how you can use Flash and a Java server to build really nice web apps. He showed several examples: A few lines of code to build a UI which runs on an Android mobile phone, in the web browser and on the desktop. All with really nice performance. One was the insurance company demo. Just enter some arbitrary data until you come to the damage details and incident report. They show new ways to enter information which make the tool usable to anyone who can recognize a car and a top-view of a street.

If you like what you see, you should probably take the Tour de Flex. It shows off a whole lot of stuff. Also try the Tour de Flex Dashboard. It shows you in real time who looks at what part of the TdF right now.

Blueprint – Modern Dependency Injection for OSGi by Costin Leau

Another DI system, this time tied to OSGi. Nothing really exciting here. The talk was okay but the speaker soon lost my interest.

One thing to note: Eclipse 4 comes with a different DI system. I wonder if they will drop that in favor of the new OSGi standard in 4.1.

Patterns and Best Practices for building large GWT applications by Heiko Braun

I went to see this but quickly realized that I’ve heard the talk before at the JUGS. Here is the link to the slides. As a result of his experience he started project errai which collects best practices to build large GWT applications.

Objects of Value by Kevlin Henney

One of the main weak points on software development is that we don’t know what we’re talking about. When my project manager comes to me and asks “When are you done?” my answer is “Soon” … Right 😉 Or think about strings. Everyone else on the planet calls it “text”.

Obviously, Kevlin had a lot of fun on stage and so had we. In essence, “Objects of Value” or “Value Objects” are even more simple than POJOs (think Integer class). The main reason to use them is to make your code more expressive and readable. Instead of

public User (String name, String firstName, int age, String zipCode, String city)

you (can) create a couple of value objects:

public User (Name name, FirstName firstName, Age age, ZipCode zipCode, City city)

This may sound ridiculous (and it is in this example) but in a lot of places, using String is just a form of bad laziness (the kind of laziness which leads to maintenance problems later). One of the advantages of the approach above is that you notice when you mix last and first name because the compiler will tell you. The major disadvantage is that it leads to a class explosion. Not to an instance explosion since we just replace a String value object with something that tells us what we have, though.

In addition to that, Java isn’t really meant for these kinds of objects. There is a lot of boiler plate code to define value objects and to use them. But if you have a system that is sufficiently complex and you use a value with a unit in many places (think of a currency value), you should really consider to replace the String+BigDecimal combination with a value object.

Many important points of his talk can be found in the paper Objects of Value on his homepage.

This concludes the first part of my Jazoon 2010 report. Go on with part 2.


Fluent Java library for collections: op4j

29. May, 2010

op4j is a nice little library for all those of us who need to work with collections. Here is a little example:

  Calendar now = Calendar.getInstance();
  Set<Calendar> set = 
      Op.on(list)
      .toSet()
      .map(FnString.toCalendar("dd/MM/yyyy"))
      .removeAllNullOrTrue(FnCalendar.after(now))
      .get();

That takes a list of strings, converts them to Calendar instances and removes all dates which are null or in the future. Questions?


Type-safe object map

28. May, 2010

Wouldn’t it be nice if you could do this:

        TypedMap map = new TypedMap();
        
        String expected = "Hallo";
        map.set( KEY1, expected );
        String value = map.get( KEY1 ); // Look Ma, no cast!
        assertEquals( expected, value );
        
        List<String> list = new ArrayList<String> ();
        map.set( KEY2, list );
        List<String> valueList = map.get( KEY2 ); // Even with generics
        assertEquals( list, valueList );

Note: The type checking is at compile time. No runtime cost!

As you can see, I get different types from the map without casting. How is that possible? Well, Generics can be your friends. The magic is in the key:

    final static TypedMapKey<String> KEY1 = new TypedMapKey<String>( "key1" );
    final static TypedMapKey<List<String>> KEY2 = new TypedMapKey<List<String>>( "key2" );

The keys contains two pieces of information: The actual key (a string) and the type which the value of the key has. The class for the key is completely braindead:

public class TypedMapKey<T> {
    private String name;
    
    public TypedMapKey(String name) {
        this.name = name;
    }
    
    public String name() {
        return name;
    }
}

The trick is to use the auto-resolution of the type at compile time in TypedMap. As you can see below, I need to suppress warnings about a typecast but the nice thing is: I only have to do it in this central place and the annotation is always correct (well, until you start to use set(String)).

As you can also see, I use delegation. I could have extended map but I wanted to show a pattern which you can use in other places … like HttpRequest or HttpSession.

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class TypedMap implements Map<String, Object> {
    private Map<String, Object> delegate;
    
    public TypedMap( Map<String, Object> delegate ) {
        this.delegate = delegate;
    }

    public TypedMap() {
        this.delegate = new HashMap<String, Object>();
    }
    
    @SuppressWarnings( "unchecked" )
    public <T> T get( TypedMapKey<T> key ) {
        return (T) delegate.get( key.name() );
    }
    
    @SuppressWarnings( "unchecked" )
    public <T> T remove( TypedMapKey<T> key ) {
        return (T) delegate.remove( key.name() );
    }
    
    public <T> void put( TypedMapKey<T> key, T value ) {
        delegate.put( key.name(), value );
    }
    
    // --- Only calls to delegates below
    
    public void clear() {
        delegate.clear();
    }

    public boolean containsKey( Object key ) {
        return delegate.containsKey( key );
    }

    public boolean containsValue( Object value ) {
        return delegate.containsValue( value );
    }

    public Set<java.util.Map.Entry<String, Object>> entrySet() {
        return delegate.entrySet();
    }

    public boolean equals( Object o ) {
        return delegate.equals( o );
    }

    public Object get( Object key ) {
        return delegate.get( key );
    }

    public int hashCode() {
        return delegate.hashCode();
    }

    public boolean isEmpty() {
        return delegate.isEmpty();
    }

    public Set<String> keySet() {
        return delegate.keySet();
    }

    public Object put( String key, Object value ) {
        return delegate.put( key, value );
    }

    public void putAll( Map<? extends String, ? extends Object> m ) {
        delegate.putAll( m );
    }

    public Object remove( Object key ) {
        return delegate.remove( key );
    }

    public int size() {
        return delegate.size();
    }

    public Collection<Object> values() {
        return delegate.values();
    }
}

Update 28. June 2010: As noticed by a couple of people on StackOverflow, this isn’t type safe if you define two keys with the same name.

Note that the code above is to wrap an existing map with a more type-safe API. If you want to make this even more type safe, create the map like so:

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class TypedMap implements Map<TypedMapKey<?>, Object> {
    private Map<TypedMapKey<?>, Object> delegate;
    
    public TypedMap( Map<TypedMapKey<?>, Object> delegate ) {
        this.delegate = delegate;
    }

    public TypedMap() {
        this.delegate = new HashMap<TypedMapKey<?>, Object>();
    }
    
    @SuppressWarnings( "unchecked" )
    public <T> T get( TypedMapKey<T> key ) {
        return (T) delegate.get( key.name() );
    }
...
}

Java Tricks: Lazy initialization

4. March, 2010

If you’re a Java developer and you’re concerned about performance, you’ve probably encountered the (broken) double checked locking pattern (which I won’t reproduce here to make sure no one copies it accidentally. If you care, read the Wikipedia article).

Joshua Block has proposed a solution but there are a couple of fine points to it. If you don’t get it right, things are going to break in odd ways. So this should go into a helper class which handles all the boiler plate code. A post about final variables pointed me in the right direction. So without further ado, the LazyInit class:

/** Lazy initialization of a field value based on the (correct)
 * double checked locking idiom by Joschua Bloch
 * 
 * <p>See "Effective Java, Second Edition", p. 283
 */
public abstract class LazyInit<T>
{
    private volatile T field;
    
    /** Return the value.
     * 
     *  <p>If the value is still <code>null</code>, the method will block and
     *  invoke <code>computeValue()</code>. Calls from other threads will wait
     *  until the call from the first thread will complete.
     */
    public T get ()
    {
        T result = field;
        if (result == null) // First check (no locking)
        {
            synchronized (this)
            {
                result = field;
                if (result == null) // Second check (with locking)
                {
                    field = result = computeValue ();
                }
            }
        }
        return result;
    }

    protected abstract T computeValue ();
    
    /** Setter for tests */
    public synchronized void set (T value)
    {
        field = value;
    }
}

As an additional goodie, it allows you to override the value in tests. Here is how to use this code:

    private LazyInit<String> field1 = new LazyInit<String> () {
        
        @Override
        protected String computeValue ()
        {
            return "value";
        }
    };

    @Test
    public void testLazyInit () throws Exception
    {
        assertEquals ("value", field1.get ());
    }

Simple, isn’t it?


OO 2.0: Reuse

25. February, 2010

What’s the most important feature of OO? Reuse.

What’s the biggest problem of Java? Reuse.

In Java, it’s considered good practice to make everything private or even final. This goes along the lines “when I open part of my API, someone might use it and this might cause problems for me later when I have to change the API”. So all fields are private. Which leads to huge lists of getters and setters which you don’t need most of the time. But you can’t omit them because if you need them, you can’t retrofit them. I guess all of us have a story where we wanted to use a class and everything was fine until we needed one more thing from that class and that thing wasn’t public or protected.

The underlying problem is that Java is based on the idea that the code is simple to parse and read. Which means that things like templates, patterns or pre-compilers aren’t supported. Even when you use annotations, you can’t modify the output at compile time. You can use load time byte-code manipulation but at compile time, the code is about as flexible as a bridge pillar.

But there is hope. The guys from the Object Teams project (OT) have created a Java-like language where you can reach into existing code and manipulate it in various ways. If you’re wondering if this is AOP with a new name or just delegation on steroids, this post will help to understand what OT is and what it’s not.

In a nutshell, OT is about reuse. If some class doesn’t provide a getter for a private field, OT can insert one for you. To get a feeling if OT can help you, I suggest to browse the blog and the examples. The stop watch example is probably the most simple to understand. The other examples look a bit incomplete or they might show that OT still has some issues with the syntax (which you’ll remember from AOP but it’s certainly not as extreme).

I, for one, will keep an eye on this project.


ePen 0.7 Status Update

9. January, 2010

I’ve pushed the code for ePen into a new set of Mercurial repositories: signal (a signal/event handling library, new BSD license), JaSpell (fork of the project jaspell.sourceforge.net; mainly a port to Java 5 and Maven 2, BSD-License) and ePen (the main editor, Eclipse Public License 1.0 since I had to copy code from the Eclipse code base).

The editor is pretty usable and I hope to wrap up 0.8 next week which should fix the following issues:

  1. Create new projects and open existing ones. The main problem here is that an ePen project is a directory and SWT doesn’t offer very good dialogs to select directories. Right now, the editor will create a demo project when you start it the first time.
  2. The translation mode is too slow
  3. Editing is sluggish.
  4. HTML export should support filtering by state (to allow to export only “final” scenes).
  5. Setting up the development environment is too complex. Especially the part where you need to copy the Eclipse plugins into the Maven repository. 0.8 will come as one huge JAR which you can start with a double click.

After that, I plan to resume work on my story “Haul” and post the first scenes in my old, desolate Philmann Dark site.


Making web development a bit more simple

3. January, 2010

When someone starts to make a path, most people tend to follow the trail. So when Sun introduced the Servlet API, most people were uneasy about the design problems:

  • Servlets are singletons (which are evil; this is due to performance problems in Java 1.2 which have been fixed about ten years ago).
  • The resulting code smells (feature envy since you call many methods of HttpServletRequest/Response, long method since you can’t call subdivide the doGet() without passing at least two parameters to each new method, duplicated code since you have to walk instance trees to get at a lot of information, …)

Whenever I see Java servlet code, I always wonder why people don’t solve this. It’s so simple:

public abstract class ServletRequestHandler {
    protected HttpServlet servlet;
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected String contentType = "text/html";

    public void init(
        HttpServlet servlet, 
        HttpServletRequest request, 
        HttpServletResponse response
    ) {
        this.servlet = servlet;
        this.request = request;
        this.response = response;
    }

    public abstract void process();

    public PrintWriter out() {
        if( null == out ) {
            response.setContentType( contentType );
            
            try {
                out = response.getWriter();
            } catch( IOException e ) {
                throw new RuntimeException( 
                    "Can't get writer", e 
                );
            }
        }
        return out;
    }
    
    public ServletRequestHandler html( String html ) {
        out().print( html );
        return this;
    }
    
    public ServletRequestHandler attribute( String value ) {
        out().print( escape( value ) );
        return this;
    }
    
    public ServletRequestHandler attribute(
        String name,
        String value
    ) {
        if( StringUtils.isBlank( value ) ) {
            return this;
        }
        
        PrintWriter out = out();
        out.print( ' ' );
        out.print( name );
        out.print( "=\"" );
        out.print( escape( value ) );
        out.print( "\"" );
        return this;
    }
    
    public ServletRequestHandler text( String value ) {
        out().print( escape( value ) );
        return this;
    }
    
    // Add more methods to support your favorite
    // web design patterns
}

Now, all your servlets look the same: They accept the request, create a new instance of the right implementation of ServletRequestHandler, and call init() plus process(). With a bit of glue code, you can even use Spring to manage all your servlets for you. No more dabbling with web.xml!

And the best part: This pattern allows you to test the servlet code from a unit test without any container. Just use Spring or Mockrunner to get mock-ups for the J2EE API classes.