Java

9 articles

Java 8

Published by Marco on in Java

 This article discusses and compares the initial version of Java 8 and C# 4.5.1. I have not used Java 8 and I have not tested that any of the examples—Java or C#—even compile, but they should be pretty close to valid.

Java 8 has finally been released and—drum roll, please—it has closures/lambdas, as promised! I would be greeting this as champagne-cork–popping news if I were still a Java programmer.[1] As an ex-Java developer, I greet this news more with an ambivalent shrug than with any overarching joy. It’s a sunny morning and I’m in a good mood, so I’m able to suppress what would be a more than appropriate comment: “it’s about time”.

Since I’m a C# programmer, I’m more interested in peering over the fence at the pile of goodies that Java just received for its eighth birthday and see if it got something “what I ain’t got”. I found a concise list of new features in the article Will Java 8 Kill Scala? by Ahmed Soliman and was distraught/pleased[2] to discover that Java had in fact gotten two... [More]

Versioned Objects with Hibernate

Published by Marco on in Java

Hibernate is a persistence framework for Java. Among the many perks it purports to bring to the table is automatic versioning for objects in the database. That is, when saving an object to the database, it increments a version number. Any process that attempts to store a different version of the same object is rejected. This is all extremely flexible and can be added to a POJO using an annotation:

  @Version
  private int version;

Nice … a single annotation takes care of people overwriting each other’s data. The exercise of handling the ensuing StaleObjectStateException in the user interface is left up to the reader.

The Trouble Begins…

Now, imagine that we have an object—call it a Book—in memory and we render it to a web page. On that page is a button which attaches more information to the object—say an Author—then saves and rerenders the same book in the page. The user can add and save authors or change other book properties and save the book to exit edit mode for... [More]

Sorting Generic Collections

Published by Marco on in Java

One of the features we expect from a collections library is sorting. You should be able to use generic library mechanisms to sort a list of any kind of element. Most libraries include a generic sort function, to which a comparison functor (object or function pointer) is passed. This functor is called repeatedly on pairs of elements until the list is sorted.

Let’s define the simple class we’ll use in the ensuing examples.

class A {
  String fileName;
  
  function getFileName() {
    return fileName;
  }
}

Now, let’s sort a List<A>. Is there a sort function on the list object itself? No. Why not? Legacy reasons. In order to avoid breaking existing code, Java has not made any changes to the List interface. Ever. Therefore, you will have to search for any new functionality in the global function unit masquerading as a class[1] called Collections.

There are two sorting functions defined in this class, shown below:

public static <T extends Comparable<? super T>> void sort(List<T>... [More]

Wildcard Generics

Published by Marco on in Java

As of version 1.5, Java has blessed its developers with generics, which increase expressiveness through improved static typing. With generics, Java programmers should be able to get away from the “casting orgy” to which Java programming heretofore typically devolved. The implementation in 1.5 does not affect the JVm at all and is restricted to a syntactic sugar wherein the compiler simply performs the casts for you.

Let’s build a class hierarchy and see how much casting Java saves us. Assume that you have defined a generic hierarchy using the following class:

public class DataObject {
  private String name;
  private List<DataObject> subObjects = new ArrayList<DataObject>();

  public String getName() {
    return name;
  }

  public List<DataObject> getSubObjects() {
    return subObjects;
  }
}

Well, now that’s an improvement! The class can express its intent in a relatively clear syntax without creating a specialized list class for the private field and result type. Assume... [More]

Inherited Method Annotations

Published by Marco on in Java

See Finding Conforming Methods for part one of this two-part article.

The problem we’re working on is as follows:

  1. Given an object, a method name and a list of parameters, execute the matching method on the given object.
  2. Determine from the object’s class whether the given method can be executed from the given context (web, command-line, etc.)

We will use annotations to mark up methods as callable or not. Given the Method we obtained in part one, it shouldn’t be too hard to find its annotations. Simply pass the class of the desired annotation to getAnnotation(); if the annotation was specified for that method, we check its contents to determine whether the method can be called or not.

These are not the Annotations you’re Looking For

In part one, calling getConformingMethod( “giveCommandTo”, {new Assistant()}, Manager.getClass()) returns the overridden method from the Manager class. Unfortunately, a call to getAnnotations() on this method returns an empty list. Why?

The Java... [More]

Finding Conforming Methods

Published by Marco on in Java

This is a two part post illustrating some tricks for working with the Java reflection API. Part two is available here.

Java reflection provides a wealth of information about your code. One interesting use of this information is to layer scriptability on top of an application, calling code dynamically. Suppose we wanted to do the following:

  1. Given an object, a method name and a list of parameters, execute the matching method on the given object.
  2. Determine from the object’s class whether the given method can be executed from the given context (web, command-line, etc.)

Let’s tackle step one first: a logical approach is to get the Class for the target object and call getMethod() with the method name and list of parameters to get the desired Method object.

Sounds pretty easy, right? The Java reflection API puts a few stumbling blocks in the way.

Conforming, not Exact

getMethod() finds only methods whose parameter lists are an exact match for the one given, not methods, which can... [More]

Immutable Collections

Published by Marco on in Java

Java supports immutable collections of all kinds, but not in the way you would expect. A naive implementation would declare the immutable (unmodifiable in Java parlance) interface as follows[1]:

interface UnmodifiableList<T> {
  function T get();
  function int size();
}

There is no way to modify this list—the API is simply not available. That done, we can now create the modifiable version of the list as follows:

interface List<T> extends UnmodifiableList<T> {
  function void add(T);
  function remove(T);
}

A class can now use these interfaces to carefully control access to a list as follows:

class SomeClass {
  private List<SomeOtherClass> list;

  function UnmodifiableList<SomeOtherClass> getList() {
    return list;
  }
}

That would be pretty cool, right? Unfortunately, even if you declared these interfaces yourself, the example above does not work. Java’s generics support amounts to little more than syntactic sugar, so List<SomeOtherClass> does not conform to... [More]

Investigating Cayenne

Published by Marco on in Java

Cayenne has nice-looking modeling tools and a decent API, but has other interesting limitations in their prefetching

Here are a few things I noticed about the framework:

  1. Their explanation of how many queries it takes to get a list of objects, each with 1-n sublink is confusing, at best. I expect it to take exactly one (1) query … they say two? … oh, Lord, check out the lovely syntax they have in the “advanced” section below:

    query.addPrefetch("paintingArray").setSemantics(
                    PrefetchTreeNode.JOINT_PREFETCH_SEMANTICS);

    Intuitive and beautiful.

  2. No aliased links … programmer is advised to avoid this problem … “To-many relationships should not be prefetched if a query qualifier can potentially reduce a number of related objects, resulting in incorrect relationship list.”

    Transaction support is pretty unwieldy—it’s automatic in most cases, but the “best practices” code creating one on your own and handling it is unwieldy, at best:

    Transaction.bindThreadTransaction(tx);
    
    try... [More]

Drawbacks to Hibernate

Published by Marco on in Java

The comment, Re: iBATIS vs Hibernate, offers some good advice for when to use iBATIS and when to use Hibernate. The damning sentence for Hibernate follows:

“If you try to shoehorn hibernate into a relational model created by a DBA who could care less about objects and thinks in terms of tables, columns, relationships and record sets, then you will get along better with your DBA if you use iBATIS, especially if the model is complex and may entail queries with outer joins and nested subqueries.”

Since when did outer joins or sub-queries become “complex”? These are exactly the drawbacks we’ve discovered in Hibernate, as well. You have to do handstands to get it to do an outer join; once you’ve got one, the object-structure returned by Hibernate is different than it was before and your processing code is useless. Which takes us to this next sentence:

“iBATIS is more flexible, has a shorter learning curve, but can take more time to develop and maintain, since you have to write all your... [More]”