JaQu — Another Lightweight SQL Interface for Java

July 31, 2008

Following up on my earlier post, I would like to mention a new tool by the name of JaQu (Java Query) that Thomas Mueller announced in a comment to my repost on Javalobby. Meanwhile, it has been released as part of the H2 Database Engine and I’ve had a chance to try it.

Even though JaQu comes bundled with H2, it is not specific to that database. I have tested the following code example successfully with an Apache Derby database.

Read the rest of this entry »


Lightweight SQL Interfaces for Java

June 11, 2008

I previously blogged about the shortcomings of JDBC and its way of passing SQL statements as strings without any compile-time checking or type safety. The same also applies to other SQL-based database access libraries such as Microsoft’s ODBC, OLE DB and ADO.NET. None of these APIs provide proper integration of SQL with the host language. Of course you could argue that object-relational mapping (ORM) tools like Hibernate have eliminated the need to work directly with SQL, but I found that there are still situations where you want to control database operations more explicitly.

Microsoft has addressed this issue quite elegantly with the introduction of LINQ to SQL in the .NET Framework 3.5. Although there is nothing equivalent in Java, I recently came across some promising efforts to improve language integration by providing fluent interfaces or other lightweight wrappers around JDBC and SQL.

Read the rest of this entry »


Learning Python

May 31, 2008

Like many other people, I decided to learn Python so that I could give Google App Engine a try (and I did not want to “cheat” by getting my Java code automatically translated to Python). In order to get a feel for the language, I wrote a simple Tic-tac-toe game. I thought this example might be useful for others to get a quick overview of some of the highlights and peculiarities of Python, especially if you are more used to statically typed languages like I am. For a more detailed introduction, check out the official Python Tutorial or Dive Into Python.

Defining a class

Although Python is not specifically an object-oriented language, it does support OOP to a certain extent. So I created a couple of classes to represent the tic-tac-toe game. Let’s start with a class for the grid-shaped game board:


class Board:
    def __init__(self, size, symbol1, symbol2):
        self.size = size
        self.symbol1 = symbol1
        self.symbol2 = symbol2
        self.grid=[size * [' '] for i in range(size)]

Read the rest of this entry »


Contracts in Java using iContract

April 13, 2008

When searching for design by contract tools for Java, the first one I came across was iContract. There is a good article at JavaWorld that describes how to use iContract, but unfortunately the link it contains for downloading iContract no longer works. Apparently iContract has been abandoned by its creators for a while, but it has been revived as JContractS. I have used JContractS to create my example below, but I am still referring to it as iContract since this name is well established, and JContractS seems to be functionally equivalent to the original iContract.

iContract uses the special Javadoc tags @pre and @post to specify a method’s preconditions and postconditions (see my earlier post for an introduction to these terms). There is also an @invariant tag that can be used on the class level to specify a common condition that must hold before and after any of the class’s methods are executed.

Let’s See some Code

The following example code is based on the swarm robotics example described in my previous post. iContract does not support the new language features of Java 5, so I adapted my example to Java 1.4 syntax. I am only going to include some code snippets here to show how to use iContract, but you can get the full source code for this example from my Subversion repository or download it as a zip file. All you need to run this example is JDK 1.4 (or higher) and Ant.

Read the rest of this entry »


When Robots Go to Law School…

April 13, 2008

…they learn how to write contracts! Well, I wanted to use something a little different from the typical customers and orders, so I came up with an example from the field of swarm robotics for my upcoming posts on design by contract tools.

Disclaimer: This example is only for illustration and not meant to be useful for any real robotics application.

The following UML class diagram (created with NetBeans) shows a simple object model for robots and swarms. Each Robot may or may not belong to a Swarm, and a swarm can consist of any number of robots. The AbstractRobot class implements some common functionality defined by the Robot interface and serves as the base class for two concrete robot implementations: Navigator and Worker.
Robots class diagram

The Navigator is equipped with a GPS system that enables it to determine its own location. The Worker‘s unique feature is its robot arm that allows it to pick up and manipulate objects. So each of these specialized robots has only limited functionality, but when working together in a swarm they are much more powerful. For example, consider the task of picking up an object from a specific location and dropping it off somewhere else. Neither one of these two robot types could perform this task by itself, because the navigator cannot pick up objects, and the worker does not know how to get to the object’s location. But if they work together, the navigator can lead the way to the object, and the worker can then pick up the object.

Read the rest of this entry »


Smart Objects Put their Contracts in Writing

March 10, 2008

When you write a function or method that is going to be called from other people’s code, then you would want to let them know how to use it, right? If you are using Java, the typical way of doing that would be to document your method in a JavaDoc comment. As an example, consider the specification for the Arrays.binarySearch method in the Java API. It clearly states that the array that you pass into this method must be sorted in order for the method to work correctly. This is what the method expects from its caller. The documentation goes on to explain what values the method returns under which conditions. This is what the caller can expect from the method. You can think of these mutual expectations as forming a contract between the method (service provider) and the caller (client, service consumer). The service provider basically tells the client: As long as you ensure X before calling my method, I guarantee Y when my method returns. X is known as the precondition, Y as the postcondition.

Read the rest of this entry »


Lightweight Database Abstraction

February 10, 2008

Although there are object-relational mapping tools like Hibernate for persisting Java objects, there are still situations where you need or want to access the database directly using JDBC.

One thing that has always bothered me about JDBC is the disconnect between the SQL command strings and the surrounding Java code. Consider the following example (which prints a list of robots that were “born” before 1980):

    public void printClassicRobots() {
        Calendar dobThreshold =
            new GregorianCalendar(1980, 0, 1);
        PreparedStatement statement = null;
        try {
            Connection connection = getConnection();
            statement = connection.prepareStatement(
                    "SELECT ID, Name" +
                    " FROM Robots" +
                    " WHERE DateOfBirth < ?");
            statement.setDate(1, new Date(
                    dobThreshold.getTimeInMillis()));

            ResultSet rs = statement.executeQuery();
            while (rs.next()) {
                System.out.format("%08d: %s\n",
                        rs.getInt(1),
                        rs.getString(2));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            cleanup(statement);
        }
    }

What I don’t like about this kind of code:

  1. Since the SQL command is just another string, the compiler does not know anything about its meaning and cannot check if its syntax is correct or if the number and types of columns in its result set are consistent with the subsequent method calls that extract data from the result set.
  2. Different database systems use different variants of SQL, making it quite challenging to write portable SQL statements in all but the simplest cases.
  3. Refactoring the database schema can be very tedious and error-prone if you have to resort to a text search to find all the places where a certain table or column is used in your code.
  4. Read the rest of this entry »


Follow

Get every new post delivered to your Inbox.