Monday, December 24, 2012

Double Brace Initialization in Java: Pros and Cons

A month ago I’ve encountered an interesting idiom for the Java programming language – double brace initialization. I suppose it emerged because the language currently doesn’t have convenient syntax for collection literals. The double brace initialization technique do adds some syntactic sugar to the Java but there are a couple of caveats you should be aware of.

Double Brace Initialization in Action

The easiest way to explain the idiom is to show an example. Suppose you are writing a unit-test and want to make sure your DB access logic returns correct entities. You know that primary keys of entities which should be returned are 1, 2, 3, 4 and 5. The following code can be used to achieve this:
@Test
public void test() {
    final Set<Long> expectedIds = new HashSet<Long>();

    expectedIds.add(1L);
    expectedIds.add(2L);
    expectedIds.add(3L);
    expectedIds.add(4L);
    expectedIds.add(5L);

    final Set<Long> actualIds = // retrieve actual ids here

    Assert.assertEquals(expectedIds, actualIds);
}
Code used to initialize expectedIds looks pretty verbose. It can be simplified a bit using double brace initialization. The previous example could be rewritten like this:
@Test
public void testDoubleBraceInitialization() {
    final Set<Long> expectedIds = new HashSet<Long>() {{
        add(1L);
        add(2L);
        add(3L);
        add(4L);
        add(5L);
    }};

    final Set<Long> actualIds = // retrieve actual ids here

    Assert.assertEquals(expectedIds, actualIds);
}
As you can see double brace initialization makes collection instantiation a bit more compact. Moreover the code which fills the collection with values is part of the same expression which creates an instance of the HashSet class.

At first glance double brace initialization might look like a magic, but actually it is very simple. There are two Java language constructs involved in it: anonymous class and instance initializer. The outer pair of braces defines an anonymous class which extends HashSet<Long> and the inner pair of braces defines an instance initializer which is a common approach to initialize anonymous class instances.

As you might guess, this technique is not limited to collection classes. It can be used to initialize any kind of object. Another interesting example can be built by applying double brace initialization idiom to GUI objects:
JPanel panel = new JPanel() {{
    setLayout(...);
    setBorder(...);
    add(new JLabel("Submit"));
    add(new JButton("Submit"));
    add(new JPanel() {{
        setLayout(...);
        setBorder(...);
        add(new JSpinner());
        add(new JTable());
    }});
}};
As you can see, double brace initialization technique might facilitate creation of more compact code, but it comes at a price. There are a couple of caveats you should be aware of to make a deliberate decision whether to use this idiom or not.
  1. Every time you use double brace initialization you create a new class. This means you will have one additional .class file for each idiom application. Here is an example to make this more specific:
    public class DoubleBraceInitializationExample {
        public static void main(String[] args) {
            final Set<Integer> set1 = new HashSet<Integer>() {{
                add(1);
                add(2);
                add(3);
            }};
    
            final Set<Integer> set2 = new HashSet<Integer>() {{
                add(1);
                add(2);
                add(3);
            }};
    
            final List<Integer> list1 = new ArrayList<Integer>() {{
                add(4);
                add(5);
                add(6);
            }};
    
            final List<Integer> list2 = new ArrayList<Integer>() {{
                add(4);
                add(5);
                add(6);
            }};
    
            System.out.println(set1);
            System.out.println(set2);
            System.out.println(list1);
            System.out.println(list2);
        }
    }
    
    This program contains four applications of double brace initialization. After you compile this example you end up with 5 classes represented by the following .class files:

    DoubleBraceInitializationExample.class
    DoubleBraceInitializationExample$1.class
    DoubleBraceInitializationExample$2.class
    DoubleBraceInitializationExample$3.class
    DoubleBraceInitializationExample$4.class

    This doesn’t cause much harm in testing code, but overusing double brace initialization in a large project which is intended for server-side execution might bloat your application with thousands of small classes and increase deployment time as a consequence.
  2. Double brace initialization cannot be applied to final classes. Pretty obvious point the compiler will tell you about immediately. Since this technique uses inheritance to instantiate anonymous class instances the superclass should allow doing this and hence it cannot be final.
  3. Additional precautions should be taken if an object initialized with double brace initialization is going to be compared with other objects using equals(). If implementation of method equals() in superclass doesn’t accept instances of subclasses then double brace initialization can introduce subtle bugs and inconsistencies. Let’s look at an example. Here is a simplistic Person class:
    public class Person {
    
        private String firstName;
        private String lastName;
        private int age;
    
        // getters and setters are omitted
    
        @Override
        public boolean equals(Object o) {
            if (o instanceof Person) {
                Person other = (Person) o;
                return firstName.equals(other.getFirstName()) &&
                        lastName.equals(other.getLastName()) &&
                        age == other.getAge();
            }
    
            return false;
        }
    
        @Override
        public int hashCode() {
            int result = firstName.hashCode();
            result = 31 * result + lastName.hashCode();
            result = 31 * result + age;
            return result;
        }
    }
    
    In this implementation of Person class method equals() uses instanceof operator and hence accepts subclasses for equality check. Instances of Person class initialized with double brace initialization will behave as expected in this case. The following program illustrates this:
    public class DoubleBraceInitializationExample {
        public static void main(String[] args) {
            Person person1 = new Person() {{
                setAge(26);
                setFirstName("John");
                setLastName("Doe");
            }};
    
            Person person2 = new Person() {{
                setAge(26);
                setFirstName("John");
                setLastName("Doe");
            }};
    
            System.out.println(person1.equals(person2));
        }
    }
    
    This program prints true as expected. Another popular implementation of equals() method checks class objects for equality instead of using instanceof operator effectively disallowing instances of subclasses to be passed for comparison. Let’s look at this alternative implementation in the Person class context:
    public class Person {
    
        private String firstName;
        private String lastName;
        private int age;
    
        // getters and setters are omitted
    
        @Override
        public boolean equals(Object o) {
            if (o != null && o.getClass().equals(Person.class)) {
                Person other = (Person) o;
                return firstName.equals(other.getFirstName()) &&
                        lastName.equals(other.getLastName()) &&
                        age == other.getAge();
            }
    
            return false;
        }
    
        @Override
        public int hashCode() {
            int result = firstName.hashCode();
            result = 31 * result + lastName.hashCode();
            result = 31 * result + age;
            return result;
        }
    }
    
    In this implementation of Person class method equals() accepts Person instances for comparison but instances of subclasses are not allowed. Double brace initialization will not work as intended in this case. The same illustrative program can be used to verify this:
    public class DoubleBraceInitializationExample {
        public static void main(String[] args) {
            Person person1 = new Person() {{
                setAge(26);
                setFirstName("John");
                setLastName("Doe");
            }};
    
            Person person2 = new Person() {{
                setAge(26);
                setFirstName("John");
                setLastName("Doe");
            }};
    
            System.out.println(person1.equals(person2));
        }
    }
    
    This time the output will be false. As you might guess person1 and person2 objects will not work as expected with any class that relies on equals() and hashCode() contract (e.g. HashSet, HashMap, etc.).

    The bottom line is that you should be extra careful when using objects created with double brace initialization with classes that rely on equals() and hashCode() contract. The best approach in this case is to refrain from using double brace initialization at all. The benefits are small compared to potential headaches.
  4. Double brace initialization can lead to nasty memory leaks. This idiom uses anonymous classes which are never static according to JLS. Hence anonymous class always keeps a reference to its enclosing object. Let’s look at an example. Assume you need to implement an Employee class and you want to create instances of this class using Builder design pattern to emulate named parameters. One possible implementation might look like this:
    public class Employee {
    
        private String firstName;
        private String lastName;
        private String address;
    
        private Employee() {
        }
    
        public static class Builder {
    
            private String firstName;
            private String lastName;
            private String address;
    
            public Builder firstName(String firstName) {
                this.firstName = firstName;
                return this;
            }
    
            public Builder lastName(String lastName) {
                this.lastName = lastName;
                return this;
            }
    
            public Builder address(String address) {
                this.address = address;
                return this;
            }
    
            public Employee build() {
                return new Employee() {{
                    setFirstName(firstName);
                    setLastName(lastName);
                    setAddress(address);
                }};
            }
        }
    
        // public getters are omitted
    
        protected void setFirstName(String firstName) {
            this.firstName = firstName;
        }
    
        protected void setLastName(String lastName) {
            this.lastName = lastName;
        }
    
        protected void setAddress(String address) {
            this.address = address;
        }
    }
    
    This implementation introduces memory leak because build() method applies double brace initialization to create Employee object, hence it uses anonymous class which keeps a reference to the enclosing Builder instance. A typical usage of the static inner Builder class implies throwing its instance away right after the product is created. But in this case a reference to the enclosing Builder instance will be kept by anonymous subclass of Employee as long as the product is strongly reachable. This is the consequence of double brace initialization application. The following program illustrates a typical usage of the builder:
    public class DoubleBraceInitializationExample {
        public static void main(String[] args) {
            Employee employee = new Employee.Builder()
                    .address("49 Featherstone Street, London")
                    .firstName("John")
                    .lastName("Doe")
                    .build();
    
            System.out.println(employee.getFirstName());
            System.out.println(employee.getLastName());
            System.out.println(employee.getAddress());
        }
    }
    
    This program will work as expected, but will take additional memory under the hood without any good reason.

Alternative Techniques

As you can see from the previous discussion double brace initialization do facilitates more compact code creation, but it can easily introduce a lot of confusion and subtleties into your program. Fortunately several alternative techniques exist which give you almost the same benefits avoiding all the headaches double brace initialization can create. For instance, if you have a known set of values and you need to add them to a List or a Set (as in the unit-testing example in the beginning of this post) you could easily do it like this:
Set<Integer> set = new HashSet<Integer>(Arrays.asList(1, 2, 3));
List<Integer> list = new ArrayList<Integer>(Arrays.asList(1, 2, 3));
This code is even more compact than double brace initialization and it doesn’t prone to any of the problems related to double brace initialization.

For Map it is not so easy. At the time of this writing standard JDK facilities don’t provide a convenient way of creating maps, but a couple of third-party libraries exist which do have means for this. For example Apache Commons Lang and its ArrayUtils.toMap() method can be used to simplify maps creation:
@SuppressWarnings("unchecked")
Map<Integer, String> map1 = (Map) ArrayUtils.toMap(new Object[][] {
        {1, "one"},
        {2, "two"},
        {3, "three"}
});
This also doesn’t look as good as it could. Usage of annotation and a cast just to create a map still overcomplicates the code. One way to improve on this is to introduce a static method and hide the complexity there:
@SuppressWarnings("unchecked")
private static <K, V> Map<K, V> mapOf(Object[] args) {
    return (Map) ArrayUtils.toMap(args);
}
In this case map creation can be as simple as the following:
Map<Integer, String> map2 = mapOf(new Object[][] {
        {1, "one"},
        {2, "two"},
        {3, "three"}
});
This approach doesn’t look perfect too, but it is probably the best thing we can squeeze from the current version of Java (Java 7 at the time of this writing).

Summary

So, let’s recap what we have. Double brace initialization is a nice Java language trick which can facilitate writing more compact code, but it can easily introduce a lot of confusion and subtleties in your program. Also it creates one additional .class file per usage and that can easily bloat your project with lots of additional classes. But if it is not overused and applied judiciously occasionally it can be useful (e.g. in testing code or in GUI components interconnection building).

Thanks for reading,
See you soon!

Wednesday, December 12, 2012

Breaking Nested Loops in Java

Recently I was very surprised by the fact that even experienced Java developers may not know how to break nested loops effectively in Java. Probably that’s because the usage of this language feature is relatively rare. Indeed if you have a deeply nested loop then it would be better to rework the code and introduce a couple of additional methods to divide the original one into easily conceivable parts. Occasionally though you do need to use nested loops and in that case it’s good to know the most effective ways to leverage them.

Assume you have a task to print the first negative element of the matrix represented by a two-dimensional array. The example is contrived a bit, but it allows illustrating the idea. I can’t even remember how many times I saw people writing the code like this to do it:
public class BreakNestedLoopsExample {
    public static void main(String[] args) {
        int[][] m = {
                {1,  2,  3},
                {4,  5,  6},
                {7, -8,  9},
        };

        for (int i = 0; i < m.length; ++i) {
            boolean isFound = false;
            
            for (int j = 0; j < m[i].length; ++j) {
                if (m[i][j] < 0) {
                    System.out.printf("m[%d][%d] = %d", i, j, m[i][j]);
                    isFound = true;
                    break;
                }
            }
            
            if (isFound) {
                break;
            }
        }                
    }
}
This code compiles and works correctly but it is awkward. A better solution exists - labeled break statement:
public class BreakNestedLoopsExample {
    public static void main(String[] args) {
        int[][] m = {
                {1,  2,  3},
                {4,  5,  6},
                {7, -8,  9},
        };
        
        OUTER_LOOP:
        for (int i = 0; i < m.length; ++i) {
            for (int j = 0; j < m[i].length; ++j) {
                if (m[i][j] < 0) {
                    System.out.printf("m[%d][%d] = %d", i, j, m[i][j]);
                    break OUTER_LOOP;
                }
            }
        }
    }
}
Usually break statement is applied to the innermost loop. But in this case the label on line 9 and a labeled break statement on line 14 allow breaking the outer loop from within nested loop easily. This code looks much cleaner and avoids the usage of isFound local variable whose only purpose is to break the outer loop if a negative element is found.

The same approach can be used with continue statement. I will use contrived but illustrative example again. Assume you have a three-dimensional array to represent an array of matrices and you want to find the indices of all matrices which have at least one negative element. You can do it using something like this:
public class ContinueNestedLoopsExample {
    public static void main(String[] args) {
        int[][][] m = {
            {
                {0,  7,  2},
                {1, -5,  3},
                {4,  2,  2},
            },                
            {
                {1,  2,  3},
                {4,  5,  6},
                {7,  8,  9},                    
            },
            {
                {6, -2,  3},
                {4,  3,  6},
                {1,  0,  5},
            }
        };

        List<Integer> indices = new ArrayList<Integer>();

        OUTER_LOOP:
        for (int i = 0; i < m.length; ++i) {
            for (int j = 0; j < m[i].length; ++j) {
                for (int k = 0; k < m[i][j].length; ++k) {
                    if (m[i][j][k] < 0) {
                        indices.add(i);
                        continue OUTER_LOOP;
                    }
                }
            }
        }

        System.out.println(indices);
    } 
}
This program will print the following output:

[0, 2]

Obviously the same result can be achieved by rewriting the nested loop in terms of break statement:
public class ContinueNestedLoopsExample {
    public static void main(String[] args) {
        int[][][] m = {
            {
                {0,  7,  2},
                {1, -5,  3},
                {4,  2,  2},
            },                
            {
                {1,  2,  3},
                {4,  5,  6},
                {7,  8,  9},                    
            },
            {
                {6, -2,  3},
                {4,  3,  6},
                {1,  0,  5},
            }
        };

        List<Integer> indices = new ArrayList<Integer>();

        for (int i = 0; i < m.length; ++i) {
            MATRIX_LOOP:
            for (int j = 0; j < m[i].length; ++j) {
                for (int k = 0; k < m[i][j].length; ++k) {
                    if (m[i][j][k] < 0) {
                        indices.add(i);
                        break MATRIX_LOOP;
                    }
                }
            }
        }

        System.out.println(indices);
    }
}
Which labeled statement to use is a matter of personal taste and a particular task in hand, but any of them is certainly better than using clunky isFound-style.

Thanks for reading,
See you soon!

Sunday, December 9, 2012

Get Sources and Javadocs with Maven

If you are using Maven and IDE to develop your Java projects, you can leverage a very easy way to get sources and javadocs for all your dependencies. Here it is:

# mvn dependency:sources
# mvn dependency:resolve -Dclassifier=javadoc

The first command will attempt to download source code for each of the dependencies in your pom file.

The second command will attempt to download the Javadocs.

Maven is at the mercy of the library packagers here. So some of them won’t have source code packaged and many of them won’t have Javadocs.

The original post was written by Ted Wise.
Thanks for sharing, Ted!

Friday, December 7, 2012

Joda-Time Tutorial

Introduction

Joda-Time is a quality implementation of the date/time library for Java. It is intended to be a replacement for out-of-the-box JDK Date and Calendar classes. The design of Joda-Time allows for multiple calendar systems while still providing a simple API. By the time of this writing eight calendar systems were supported by the library including the following ones: Gregorian, Julian, Buddhist, Ethiopic, Coptic, and Islamic. Supporting classes include time zone, duration, format and parsing.

Why Joda-Time?

Joda-Time has been carefully designed to overcome all the issues the standard JDK date/time classes are blamed for. It is under active development since 2002 and has the mature and reliable code base. There are lots of reasons to use Joda-Time, in particular:
  • It is easy to use. The standard JDK Calendar makes accessing “normal” dates difficult due to the lack of simple methods. Joda-Time has straightforward field accessors such as getYear() or getDayOfWeek().
  • It is easy to extend. The JDK supports multiple calendar systems via subclasses of Calendar. This is clunky, and in practice it is very difficult to write another calendar system. Joda-Time supports multiple calendar systems via a pluggable system based on the Chronology class.
  • It comprises comprehensive feature set. The library is intended to provide all the functionality that is required for date/time calculations. It already provides out-of-the-box features, such as support for oddball date formats, which are difficult to replicate with the JDK.
  • It incorporates up-to-date time zone calculations. The time zone implementation is based on the public tz database, which is updated several times a year. New Joda-Time releases incorporate all the changes made to this database. Should the changes be needed earlier, manually updating the zone data is easy.
  • It performs better than standard JDK date/time classes. The standard JDK Calendar has strange performance characteristics as it recalculates fields at unexpected moments. Joda-Time does only the minimal calculation for the field that is being accessed.
  • It is free and open source. The last but not the least. Joda-Time is free and licensed under the business friendly Apache License Version 2.0.

Core Concepts

The major building blocks of Joda-Time are the concepts of instant, partial, interval, duration, period, chronology and time zone. They are briefly described in the following sections. For more detailed information regarding each concept you are encouraged to visit the corresponding official documentation page.

Instants

Instant is the most frequently used concept in Joda-Time. An Instant is defined as a moment in the datetime continuum specified as a number of milliseconds from 1970-01-01T00:00Z. This definition of milliseconds is consistent with that of the JDK in Date or Calendar making interoperating between the two APIs simple and straightforward. An instant is represented by the ReadableInstant interface within Joda-Time. Currently there are four implementations of the interface:
  • Instant – A simple immutable implementation which is restricted to the UTC time zone and is intended for time zone and calendar neutral data transfer.
  • DateTime – The most commonly used class in the library, and an immutable representation of a date and time with calendar and time zone.
  • DateMidnight – Similar to DateTime and also immutable but with the time component forced to be midnight (at the start of a day).
  • MutableDateTime – A mutable representation of date and time with calendar and time zone.
For general usage immutable implementations are recommended. To get more information about instants please visit Official User Guide and Instant Key Concept pages.

Partials

A partial as its name implies is a partial date and time representation. All implementations represent local dates and times, and do not reference a time zone. Hence they only partially represent a date or time in the datetime continuum. It is not possible to directly interoperate between a partial and instant because a partial does not fully specify a single point in the datetime continuum, but instead may match multiple points. A partial is represented by the ReadablePartial interface within Joda-Time. Currently there are six implementations of the interface:
  • LocalDate – an immutable implementation that represents a date without a time or time zone.
  • LocalTime – an immutable implementation that represents a time without a date or time zone.
  • LocalDateTime – an immutable implementation that represents date and time without a time zone.
  • YearMonth – an immutable implementation that represents a year and month (it can be useful for credit card expiry dates).
  • MonthDay – an immutable implementation that represents a month and day (it can be useful for birthdays without years).
  • Partial – An immutable implementation that can store any combination of date and time fields (for example, using this class you could create a YearMonth or DayOfWeekDayOfMonth partial).
A partial can be converted to a full instant by specifying the missing values. At least time zone is required. It may be necessary to specify other missing fields. For example, conversion from a LocalDate to a DateTime requires filling in the time fields and the time zone. In terms of date/time math it means the following:

Partial + Missing Fields + Time Zone = Instant

For more information about partials please visit Partial Key Concept page.

Intervals

An interval in Joda-Time represents an interval of time from one instant to another instant. They are both fully specified instants in the datetime continuum (i.e. each instant is set up with a time zone). Intervals are implemented as half-open, which means the start instant is included in the interval but the end one is excluded. The end is always greater than or equal to the start. Both end-points are restricted to having the same chronology and the same time zone. An interval is represented by the ReadableInterval interface. Currently there are two implementations of the interface:
As usual, immutable implementation is recommended for general usage. To get more information about intervals please visit Official User Guide and Interval Key Concept pages.

Durations

Duration in Joda-Time represents duration of time measured in milliseconds. The duration is often obtained from an interval. Durations are a very simple concept, and the implementation is also simple. They have no chronology or time zone, and consist solely of the millisecond duration. Duration is represented by the ReadableDuration interface and currently there is only one implementation of the ReadableDuration interface: Duration. Durations can be added to an instant, or to either end of an interval to change those objects. In date/time math it means the following:

Instant + Duration = Instant

For more information about durations please visit Official User Guide and Duration Key Concept pages.

Periods

A period in Joda-Time represents a period of time defined in terms of fields, for example, 5 years 2 months 4 days and 7 hours. This differs from duration in that it is inexact in terms of milliseconds. A period can only be resolved to an exact number of milliseconds by specifying the instant (including chronology and time zone) it is relative to.

For example, consider a period of a month. If you add this period to the 1st of February (ISO) then you will get the 1st of March. If you add the same period to the 1st of March you will get the 1st of April. But the duration added (in milliseconds) in these two cases is very different.

As a second example, consider adding 1 day at the daylight savings boundary. If you use a period to do the addition then either 23 or 25 hours will be added as appropriate. If you had created duration equal to 24 hours, then you would end up with the wrong result.

Period is represented by the ReadablePeriod interface. The implementations of the period concept can be divided into two groups. The first one contains implementations which can store a single field only, such as days or hours, but not both. The second group is comprised of implementations which can store multiple fields and hence can express values like 5 months 3 days and 11 hours.

The first group contains seven implementations:
  • Years – an immutable years-only implementation.
  • Months – an immutable months-only implementation.
  • Weeks – an immutable weeks-only implementation.
  • Days – an immutable days-only implementation.
  • Hours – an immutable hours-only implementation.
  • Minutes – an immutable minutes-only implementation.
  • Seconds – an immutable seconds-only implementation.
The second group contains two implementations:
Periods are not associated with either a chronology or a time zone. Periods can be added to an instant, or to either end of an interval to change those objects. In date/time math it means the following:

Instant + Period = Instant

For more information about periods please visit Official User Guide and Period Key Concept pages.

Chronology

A chronology in Joda-Time is a pluggable calendar system. The JDK supports multiple calendar systems via subclasses of Calendar. This is clunky, and in practice it is very difficult to write another calendar system. Joda-Time supports multiple calendar systems by designing a pluggable system.

The default chronology in Joda-Time is ISO. This calendar system is the same as that used by business in the majority of the world today. The ISO system is unsuitable for historical work before 1583 as it applies the leap year rules from today back in time (it is a proleptic calendar). As a result, users requiring a more historically accurate calendar system are forced to think about their actual requirements.

Internally, all the chronology, field and time zone classes are maintained as singletons. Thus there is an initial setup cost when using Joda-Time, but after that only the main API instance classes (DateTime, Interval, Period, etc.) have creation and garbage collector costs.

The Chronology class is the key to the Joda-Time design, but it is not the key to using the API however. For most applications, the Chronology can be ignored as it will default to the ISOChronology.

For more information about chronologies please visit Official User Guide and Chronology Key Concept pages.

Time Zones

The chronology class also supports the time zone functionality. This is applied to the underlying chronology via the decorator design pattern. The DateTimeZone class provides access to the zones primarily through one factory method, as follows:
DateTimeZone zone = DateTimeZone.forID("Europe/London");
In addition to named time zones, Joda-Time also supports fixed time zones. The simplest of these is UTC, which is defined as a constant:
DateTimeZone zoneUTC = DateTimeZone.UTC;
Joda-Time provides a default time zone which is used in many operations when a time zone is not specified. This is similar in concept to the default time zone of the java.util.TimeZone class. The value can be accessed and updated via static methods:
DateTimeZone defaultZone = DateTimeZone.getDefault();
DateTimeZone.setDefault(myZone);
For more information about time zones and tz database (aka Olson database) please visit Official User Guide and Time Zone Update pages.

Examples

Ok, that’s enough for the theory. Now let’s look at several examples of Joda-Time usage. At the time of this writing the most recent version of the library was 2.1. All the examples are based on that version.

Example 1

Enterprise applications almost always should store the date and time for some of its entities: date of user registration, date of the last user login, dates of payments, etc. Later that information might be displayed in the UI. Having users of the application residing in different time zones is more a rule than an exception. Hence it is important to display the date values in a time zone relevant for a certain user. A commonly used approach is to store the values in the UTC and convert them to the relevant time zone when preparing data for the UI. This example demonstrates how easily it can be implemented using Joda-Time.

The following code snippet shows how to convert the date from UTC time zone to another one:
DateTimeZone localTimeZone = DateTimeZone.forID("Europe/Kiev");

DateTime utcTime = new DateTime(2012, 11, 29, 11, 40,
        DateTimeZone.UTC);
DateTime localTime = utcTime.withZone(localTimeZone);
        
System.out.println(utcTime);
System.out.println(localTime);
This program will print the following (the output is in the ISO 8601 format):

2012-11-29T11:40:00.000Z
2012-11-29T13:40:00.000+02:00

To save the modifications which could be done via UI the reverse conversion is necessary:
DateTimeZone localTimeZone = DateTimeZone.forID("Europe/Kiev");

DateTime localTime = new DateTime(2012, 11, 29, 13, 40,
        localTimeZone);
DateTime utcTime = localTime.withZone(DateTimeZone.UTC);

System.out.println(localTime);
System.out.println(utcTime);
This program will print the following (the output is in the ISO 8601 format):

2012-11-29T13:40:00.000+02:00
2012-11-29T11:40:00.000Z

As you can see, Joda-Time greatly facilitates the common task of date conversion from UTC time zone to the local one and vice versa.

Example 2

The ISO 8601 standard contains a lot of different formats. The one used by default in Joda-Time contains the most complete date/time information but it is not readable enough. A user can easily make a mistake trying to decipher it. That’s why Joda-Time provides rich set of facilities to format the output. This example shows how to use them.

The Joda-Time library contains implementations of all ISO 8601 standard formats. They reside in the ISODateTimeFormat class. The formatters it provides should be enough for the vast majority of use-cases. So before trying any other means of date formatting you are strongly encouraged to explore the facilities of the aforementioned class. The following code snippet demonstrates a couple of them. For a full list of available formatters please consider ISODateTimeFormat javadoc.
DateTime dateTime = new DateTime(2012, 12, 1, 11, 30,
        DateTimeZone.UTC);

System.out.println(ISODateTimeFormat.yearMonthDay().print(dateTime));
System.out.println(ISODateTimeFormat.hourMinuteSecond()
        .print(dateTime));
System.out.println(ISODateTimeFormat.dateHourMinuteSecond()
        .print(dateTime));
The program will print the following output:

2012-12-01
11:30:00
2012-12-01T11:30:00

If the facilities provided by ISODateTimeFormat class don’t suit you well, you can create a custom formatter. In case the required format can be described in terms of a format pattern you can use DateTimeFormat#forPattern factory method. The pattern string is compatible with JDK date patterns. If you need to use a particular locale you can leverage formatter’s withLocale method which returns another formatter based on the original. The example code snippet follows.
DateTime dateTime = new DateTime(2012, 12, 1, 12, 15,
        DateTimeZone.UTC);

DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy/MMM/dd");
DateTimeFormatter frenchFmt = fmt.withLocale(Locale.FRENCH);
DateTimeFormatter germanFmt = fmt.withLocale(Locale.GERMAN);
The program will print the following output:

2012/Dec/01
2012/déc./01
2012/Dez/01

If you need a really exotic date format you can easily create it with Joda-Time. The library contains DateTimeFormatterBuilder class which allows you to build a formatter programmatically. To unleash the full power of DateTimeFormatterBuilder please consider its javadoc. The following code snippet shows just the top of the iceberg:
DateTime dateTime = new DateTime(2012, 12, 1, 12, 15,
        DateTimeZone.UTC);

DateTimeFormatter formatter = new DateTimeFormatterBuilder()
        .appendDayOfWeekShortText()
        .appendLiteral(", ")
        .appendDayOfMonth(2)
        .appendLiteral('-')
        .appendMonthOfYearShortText()
        .appendLiteral('-')
        .appendYear(4, 4)
        .appendLiteral(", ")
        .appendEraText()
        .toFormatter();

System.out.println(formatter.print(dateTime));
The program will print the following output:

Sat, 01-Dec-2012, AD

The last but not the least: formatters can also be used to parse date from string. In other words every formatter is able to perform date to string conversion and vice versa. The expected format for string to date conversion is the same the formatter has been initially configured with. The following code snippet parses a string in a custom format and then prints it using one of the default formatters:
String strDateTime = "01.12.2012";
DateTimeFormatter formatter = DateTimeFormat
        .forPattern("dd.MM.yyyy");
DateTime dateTime = formatter.parseDateTime(strDateTime);

System.out.println(strDateTime);
System.out.println(ISODateTimeFormat.yearMonthDay()
        .print(dateTime));
The program will print the following output:

01.12.2012
2012-12-01

Example 3

From time to time you can be faced with a task which requires you to consider only date component of a certain event effectively ignoring its time. For example assume you want to build a SQL query which would return all the purchases which were shipped between 5th and 7th of November of 2012. If you work with JDK standard Date and Calendar classes then you manually have to set the time component to 00:00. Joda-Time provides much easier way to implement such tasks: DateMidnight class. It is effectively the same as DateTime class, but, as its name implies, it has the time component set to 00:00. Thus assuming you have parameterized your SQL query with half-open date interval (start date included, end date excluded) and all dates are stored on the server in UTC time zone you can use the following code to build date parameters for the query:
DateMidnight startDate = new DateMidnight(2012, 11, 5,
        DateTimeZone.UTC);
DateMidnight endDate = new DateMidnight(2012, 11, 8,
        DateTimeZone.UTC);
If you are working with JPA or directly with some ORM framework to query the database then you probably will have to give it instances of the standard JDK java.util.Date class. You can easily convert DateMidnight objects to java.util.Date instances:
java.util.Date startDate = new DateMidnight(
        2012, 11, 5, DateTimeZone.UTC).toDate();

java.util.Date endDate = new DateMidnight(
        2012, 11, 8, DateTimeZone.UTC).toDate();
If you prefer to use pure JDBC then you probably will have to give it instances of java.sql.Date class. Fortunately this is also easy to do:
java.sql.Date startDate = new java.sql.Date(
        new DateMidnight(2012, 11, 5, DateTimeZone.UTC).getMillis());

java.sql.Date endDate = new java.sql.Date(
        new DateMidnight(2012, 11, 8, DateTimeZone.UTC).getMillis());

Example 4

The Joda-Time library provides very powerful facilities for date/time arithmetic. For example assume you have the current time instant (now) and you want to know what date will be the first Wednesday of the next year. I don’t want even try to do this with standard JDK classes, but with Joda-Time it is as easy as the following (UTC time zone assumed):
DateTime newYear = new DateTime(DateTimeZone.UTC).dayOfYear()
        .withMaximumValue().plusDays(1);

DateTime firstWednesday = newYear.plusDays(
        DateTimeConstants.WEDNESDAY - newYear.getDayOfWeek());

System.out.println(ISODateTimeFormat.dateHourMinuteSecond()
        .print(firstWednesday)); 
At the time of this writing the program printed the following output:

2013-01-02T15:01:13

As you can see, the first Wednesday of 2013 is the 2nd of January.

Example 5

Sometimes it can be useful to store date/time information independently of a certain time zone. The Joda-Time library has convenient ways to do this: partials. One of the most frequent operations being done with partials is conversion from partials to instants and vice versa. A couple of listings showing how to do that follow.

The following code snippet shows how to assemble a DateTime instance using UTC time zone, LocalDate, and LocalTime objects:
LocalDate partialDate = new LocalDate(2012, 12, 3);
LocalTime partialTime = new LocalTime(12, 50);
DateTime dateTime = partialDate.toDateTime(partialTime,
        DateTimeZone.UTC);

System.out.println(ISODateTimeFormat.dateHourMinuteSecond()
        .print(dateTime));
The program will print the following output:

2012-12-03T12:50:00

The next code snippet shows how to assemble a DateTime instance using current time instant in UTC time zone and LocalTime object representing 23:30:
LocalTime partialTime = new LocalTime(23, 30);
DateTime dateTime = partialTime.toDateTime(
        new DateTime(DateTimeZone.UTC));

System.out.println(ISODateTimeFormat.dateHourMinuteSecond()
        .print(dateTime));
At the time of this writing the program printed the following output:

2012-12-03T23:30:00

Joda-Time contains YearMonth partial implementation. This class stores only year and month information as its name implies. It is useful to represent credit card expiration dates for example. Assume you have a credit card which expires in the December of 2014. Here is an easy way to determine which day of week it will be:
YearMonth expirationDate = new YearMonth(2014, 12);

String expirationDay = expirationDate.toDateTime(
        new DateTime(DateTimeZone.UTC).dayOfMonth().withMinimumValue())
                .dayOfWeek().getAsText();

System.out.println(expirationDay);
The program will print the following output:

Monday

Joda-Time has an easy way to represent day and month: MonthDay partial implementation. It is a convenient approach to store birthdays for example. Assume you have a friend whose birthday is the 1st of July. To find out which day of week will it be in the next year you could use the following code:
MonthDay birthday = new MonthDay(7, 1);

String dayOfWeek = birthday.toDateTime(new DateTime(DateTimeZone.UTC)
        .plusYears(1)).dayOfWeek().getAsText();

System.out.println(dayOfWeek);
At the time of this writing (year 2012) the program printed the following output:

Monday

A couple of previous code snippets showed how to convert partials to instants. The reverse conversion is even easier: partials’ constructors can be used to do that. The following code snippet shows some examples:
DateTime instant = new DateTime(2012, 12, 21, 8, 15,
        DateTimeZone.UTC);

LocalDate partialDate = new LocalDate(instant);
LocalTime partialTime = new LocalTime(instant);
LocalDateTime partialDateTime = new LocalDateTime(instant);
YearMonth yearMonth = new YearMonth(instant);
MonthDay monthDay = new MonthDay(instant);

System.out.println(partialDate.toString(
        ISODateTimeFormat.yearMonthDay()));
System.out.println(partialTime.toString(
        ISODateTimeFormat.hourMinute()));
System.out.println(partialDateTime.toString("yyyy.MM.dd/HH:mm:ss"));
System.out.println(yearMonth.toString("yyyy\\MMM"));
System.out.println(monthDay.toString("dd-MMM"));
The program will print the following output:

2012-12-21
08:15
2012.12.21/08:15:00
2012\Dec
21-Dec

Example 6

Sometimes you may need to work with time intervals (e.g. to implement time management application). You can use Interval class within Joda-Time to do this. The great thing about this class is that it provides an easy way of determining relationships between time intervals (gaps, overlaps, abuts). Here are a couple of examples:
DateTime today = new DateTime(DateTimeZone.UTC);

Interval firstMeeting = new Interval(
        new LocalTime(9, 0).toDateTime(today),
        new LocalTime(10, 0).toDateTime(today));

Interval coffeeBreak = new Interval(
        new LocalTime(10, 0).toDateTime(today),
        new LocalTime(10, 30).toDateTime(today));

Interval secondMeeting = new Interval(
        new LocalTime(10, 30).toDateTime(today),
        new LocalTime(12, 0).toDateTime(today));

Interval lunchTime = new Interval(
        new LocalTime(13, 0).toDateTime(today),
        new LocalTime(14, 0).toDateTime(today));

Interval thirdMeeting = new Interval(
        new LocalTime(16, 0).toDateTime(today),
        new LocalTime(18, 0).toDateTime(today));

Interval sportEvent = new Interval(
        new LocalTime(17, 0).toDateTime(today),
        new LocalTime(19, 0).toDateTime(today));

System.out.printf(
        "First meeting abuts coffee break: %b\n",
        firstMeeting.abuts(coffeeBreak));
System.out.printf(
        "Lunch time is before second meeting: %b\n",
        lunchTime.isBefore(secondMeeting));
System.out.printf(
        "Sport event is after the lunch: %b\n",
        sportEvent.isAfter(lunchTime));
System.out.printf(
        "Sport event overlaps with the third meeting: %b\n",
        sportEvent.overlaps(thirdMeeting));

Interval gap = thirdMeeting.gap(lunchTime);
Interval overlap = thirdMeeting.overlap(sportEvent);

System.out.printf(
        "I will miss the part of sport event: from %s to %s\n",
        ISODateTimeFormat.hourMinute().print(overlap.getStart()),
        ISODateTimeFormat.hourMinute().print(overlap.getEnd()));

System.out.printf(
        "I have spare time after lunch: from %s to %s\n",
        ISODateTimeFormat.hourMinute().print(gap.getStart()),
        ISODateTimeFormat.hourMinute().print(gap.getEnd()));
The program will print the following output:

First meeting abuts coffee break: true
Lunch time is before second meeting: false
Sport event is after the lunch: true
Sport event overlaps with the third meeting: true
I will miss the part of sport event: from 17:00 to 18:00
I have spare time after lunch: from 14:00 to 16:00

This listing is only a small subset of what can be achieved using Interval class. Please consider its javadoc for additional information about the API it provides.

Example 7

The Joda-Time library doesn’t allow you to compare intervals (i.e. Interval class doesn’t implement Comparable interface). But you do can compare their durations. The following example shows how to build a sorted set of intervals which sorts them by duration (starting from the shortest):
DateTime today = new DateTime(DateTimeZone.UTC);

Set<Interval> events = new TreeSet<Interval>(
        new Comparator<Interval>() {
            public int compare(Interval o1, Interval o2) {
                return o1.toDuration().compareTo(o2.toDuration());
            }
        });

events.add(new Interval(
        new LocalTime(9, 0).toDateTime(today),
        new LocalTime(11, 0).toDateTime(today)));

events.add(new Interval(
        new LocalTime(10, 0).toDateTime(today),
        new LocalTime(15, 0).toDateTime(today)));

events.add(new Interval(
        new LocalTime(13, 0).toDateTime(today),
        new LocalTime(16, 0).toDateTime(today)));

events.add(new Interval(
        new LocalTime(8, 0).toDateTime(today),
        new LocalTime(18, 0).toDateTime(today)));

events.add(new Interval(
        new LocalTime(16, 0).toDateTime(today),
        new LocalTime(17, 0).toDateTime(today)));

for (Interval event : events) {
    DateTimeFormatter formatter = ISODateTimeFormat.hourMinute();

    System.out.printf("event: %s-%s, duration: %d\n",
            formatter.print(event.getStart()),
            formatter.print(event.getEnd()),
            event.toDurationMillis());
}
The program will print the following output:

event: 16:00-17:00, duration: 3600000
event: 09:00-11:00, duration: 7200000
event: 13:00-16:00, duration: 10800000
event: 10:00-15:00, duration: 18000000
event: 08:00-18:00, duration: 36000000

Example 8

The concept of periods allows you to operate easily on periods of time defined in terms of fields (e.g. 4 years, 3 months, 5 days and 2 hours) instead of milliseconds. This implies that periods are inexact in terms of milliseconds and cannot be resolved to an exact number of milliseconds without an instant. Periods are useful when time period as a whole is important rather than its duration in terms of milliseconds. The following code snippet shows how the same period can yield totally different millisecond amount depending on the context:
DateMidnight firstOfFebruary = new DateMidnight(
        2012, 2, 1, DateTimeZone.UTC);
DateMidnight firstOfMarch = new DateMidnight(
        2012, 3, 1, DateTimeZone.UTC);

DateTimeFormatter formatter = ISODateTimeFormat.yearMonthDay();

System.out.println(formatter.print(firstOfFebruary.plus(Months.ONE)));
System.out.println(formatter.print(firstOfMarch.plus(Months.ONE)));
The program will print the following output:

2012-03-01
2012-04-01

The next code snippet shows a simple example of generic period implementation (Period class) usage:
DateTimeFormatter formatter = ISODateTimeFormat.yearMonthDay();

DateMidnight start = new DateMidnight(2013, 1, 1, DateTimeZone.UTC);
DateMidnight end = new DateMidnight(2014, 8, 1, DateTimeZone.UTC);

Period period = new Period(start, end);

DateMidnight startMinusPeriod = start.minus(period);
DateMidnight endPlusPeriod = end.plus(period);

System.out.printf("before start: %s\n", formatter
        .print(startMinusPeriod));
System.out.printf("period start: %s\n", formatter.print(start));
System.out.printf("period end:   %s\n", formatter.print(end));
System.out.printf("after  end:   %s\n", formatter
        .print(endPlusPeriod));
The program will print the following output:

before start: 2011-06-01
period start: 2013-01-01
period end:   2014-08-01
after  end:   2016-03-01

Example 9

And finally the last but not the least: this example is about JDK interoperability. From time to time you may need to fall back to standard Date class (e.g. your favorite framework works in its terms or you may have some legacy/integration code which you cannot modify). The closest analogue of standard Date class in Joda-Time is the notion of instant. Not surprisingly all instant implementations can be easily converted to JDK Date. The reverse conversion is also straightforward. The following code snippet shows how to do both:
DateTime dateTime = new DateTime(
        2013, 1, 1, 11, 15, DateTimeZone.UTC);

Date instantToDate = dateTime.toInstant().toDate();
Date dateTimeToDate = dateTime.toDate();
Date dateMidnightToDate = dateTime.toDateMidnight().toDate();
Date mutableDateTimeToDate = dateTime.toMutableDateTime().toDate();

Instant dateToInstant = new Instant(instantToDate.getTime());
DateTime dateToDateTime = new DateTime(dateTimeToDate.getTime());
DateMidnight dateToDateMidnight = new DateMidnight(
        dateMidnightToDate.getTime());
MutableDateTime dateToMutableDateTime = new MutableDateTime(
        mutableDateTimeToDate.getTime());
As you can see, streamlined interoperability between JDK standard date/time facilities and Joda-Time library allows you to write most of your application logic in terms of much more convenient Joda-Time API and fall back to standard means only when absolutely necessary.

Conclusion

Thank you for working through this tutorial. I hope it was useful and gave you the necessary basis to start using Joda-Time library in your software development efforts. This tutorial is not claimed to be an exhaustive Joda-Time guide so you are encouraged to explore the documentation to get more information about the library. Any comments and suggestions are appreciated.

See you soon!

Friday, August 17, 2012

Book Review: “Real World Java EE Patterns Rethinking Best Practices”

Recently I finished reading the book “RealWorld Java EE Patterns Rethinking Best Practices” by Adam Bien. Generally speaking, the book is nice. It contains plenty of useful information, but you have to strain yourself to understand this. The book is not easy to read. It is divided into six parts. The brief description of each part follows.

The first part of the book gives you a brief history of the J2EE. It starts with the description of applets, J2EE application server predecessor JWS (the latter stands for Java Web Server which I wasn’t even aware of before reading this book) and driving forces which gave birth to EJB, JMS and single-threaded programming model. Then author gives a nice introduction to core enterprise application development principles and discusses them in the context of Java EE 5/6. This lesson of history is useful enough to establish a clear understanding of what J2EE was from the very beginning, why it had been considered “heavyweight” and how Spring, Hibernate and other frameworks pushed the standards to the new “lightweight” development model – Java EE. Also this part develops the basic terminology to build upon in the next chapters.

The second part of the book is called “Understanding Java EE Core Concepts”. But I would rather call it “Understanding EJB 3.1 Core Concepts” or “Understanding EJB 3.1 and JPA 2.0 Core Concepts” because these are the topics this part is actually about. It gives you the understanding of Convention over Configuration (aka Configuration by Exception) principle, Dependency Injection (aka Inversion of Control) principle and gives you the basic knowledge about interceptors, stateless and stateful session beans and JPA persistence context modes. It doesn’t give you any kind of information about for example SOAP or RESTful web-services which are both the important parts of Java EE spec. The title of the chapter and its content makes me think that Java EE is all about EJB and JPA which is certainly not the case. But anyway, despite the misleading title the second part gives you the basic knowledge about EJB and JPA you need to proceed with the book.

The third part of the book helps to “rethink” the principles of business tier architectural design. It describes many business-tier-related patterns and best practices using well-defined approach which is kept for the rest of the book. The problem description comes first followed by the properties (or “forces” as the author used to call them) which are the distinguishable signs of successful pattern application. The solution (the pattern itself) goes next. The author compares the original pattern description (targeted to J2EE) with the modern one (targeted to Java EE) quite often. This is the biggest part of the book which adds many valuable instruments to the toolset of a Java EE developer.

If you’re working on an enterprise application which has been started from scratch – you are lucky. It’s not a secret that the vast majority of modern enterprise applications must be integrated with legacy information systems. This often implies writing some ugly code and communicating with Java EE-incompliant resources. The fourth part of the book describes patterns and best practices which would streamline the integration code and make it seamless. The text contains a lot of interesting ideas. One of them is a Generic JCA implementation example which demonstrates how to communicate with a file system in a transactional way (i.e. how to seamlessly integrate a Java EE-incompatible resource with the Java EE ecosystem). Another one, taking to account the huge amount of legacy J2EE code, is EJB 2 Integration and Migration which shows how to evolve the code to use EJB 3 in a step-by-step fashion.

The fifth part of the book tells the reader about infrastructural patterns and utilities. These patterns cannot be related to any specific application layer. Actually they are not parts of the application architecture but rather implementation artifacts. Each of them is carefully crafted to provide an elegant solution for a specific kind of problem. One of my favorite patterns in this part of the book is Dependency Injection Extender. It shows how to tie together Java EE dependency injection capabilities with the ones from other frameworks (for example, how and when Guice dependencies in EJB should be resolved to fit Guice dependency resolution process in the EJB lifecycle correctly). These patterns are probably not the ones to be used on day-by-day basis, but they worth your attention, because as soon as you encounter one of the problems covered by them you will be pleased to know that you already have an effective solution.

The sixth part of the book is about pragmatic Java EE architectures. It describes two radically different application design approaches: service-oriented and domain-driven. This is the place where pieces of puzzle come together at last. The thing is that you can find patterns contradicting to each other while reading the book (e.g. Service Façade and Gateway). To understand the reason of this contradiction you have to be strong enough to get to the final part of the book: the aforementioned patterns belong to different application design approaches. This part of the book helps to stop thinking in terms of fine-grained self-contained patterns. It gives you the high-level view of how the patterns work together. In my opinion this part should be made the third one, not the sixth. In this case a reader may not understand all the material of this part in detail during the first reading of the book, but the high-level view would be established from the very beginning. This is the approach taken by Bjarne Stroustrup in his book “The C++Programming Language: Special Edition”. The second and the third chapters give you a quick tour (high-level view) of C++ and standard library while the rest of the book fills in technical details. So my suggestion is to read the sixth part of the “Real World Java EE Patterns Rethinking Best Practices” right after the second one.

Summary

To summarize, the book is nice, but it has its shortcomings. They are mostly related to poor editing of the text and could be easily fixed. Despite plenty of disadvantages I would recommend to read this book to every software developer who encounters Java EE in the day-to-day work. The list of pros and cons follows.

Advantages:
  • The book contains a lot of useful design patterns which can enrich the toolset of every Java EE developer. A lot of them are general enough to be applied even outside Java EE ecosystem.
  • Pattern descriptions often contain comparison of J2EE version with Java EE version. This helps to understand not only how to apply the pattern in the Java EE context but also why it has been evolved to the new form.
Disadvantages:
  • The text contains a lot of grammatical, syntactical, and lexicographical mistakes. That’s why the book is not as easy to read as it should.
  • There are a lot of errors in source code (but if you read carefully and understand the subject you could easily cope with them).
  • Personal opinion: I would put the sixth part of the book between the second and the third to develop the high-level view as early as possible.

I hope this review was helpful.
See you soon!

Wednesday, August 15, 2012

Introduction

Hi there!

My name is Andrii Polunin. I’m a software developer. I decided to create this blog to publish my personal thoughts and different kinds of technical information related to software development. I’m doing commercial enterprise software development using mostly Java technologies for six years and I like many other seasoned software developers concluded that it can be quite a burden. We all know lots of reasons why commercial software development is pain, so I won’t bother you by repeating them (for young software developers who believe in the bright future I would recommend a book “Death March” by Edward Yourdon, which clearly describes the actual state of affairs in the field).

But I’m still strongly convinced that computer programming is more than that. I believe that it’s an art. I believe that every software developer is a creative person to some extent who can unleash the creativity despite the commercial programming pain. That’s why I decided to post here everything I considered useful and interesting when it comes to software development.

Ok, that’s enough for the intro :)
See you soon!