Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

The Main() Conspiracy

Typical Java

I was browsing StackOverflow this evening when I came across this question. The question itself isn't anything special, but the quote from the Thread JavaDoc caught my eye:

"When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class)."

"Typically" calls main()? I mean, sure, you could call java SomeClassWithoutAMainMethod and the JVM would start up, cough, and die. But that hardly seems worth a parenthetical shout out in the JavaDocs, right? There's got to be more to it than that.

Static Initialization

So, how can we write a Java program that runs without a main() method ever being called? We'll need code that exists outside of a named method that we can get to run before the JVM discovers the main method is missing. What happens before main() is called? The class that is supposed to contain main() gets loaded. And how do you run code when a class is loaded? Static initialization!

public class Mainless {
        static {
                System.out.println("Mainless!");
                System.exit(0);
        }
}

And there you have it: a Java program with no main() method. The static initialization block runs when the Mainless class is loaded, before the JVM tries to call main (which, you'll note, doesn't exist). "But wait," you say, "I was taught in Java 101 that every program has a main() method!" And like much of what we learn in school, that isn't strictly true. Why the conspiracy to keep Java developers writing public static void main(String[] args)? Well, it does have practical uses. For example, you can't pass arguments to the static initialization block. You could set environment variables before running Mainless and access those variables, but that's just ugly. And, you have to call System.exit() at some point or you'll get an error message about the missing main() method.

The big question: why?

But, is there any point to this? Not as far as I can tell. There's no practical use of this technique that I know of. You save a little bit of typing and get an obscure piece of code that might confuse a lot of Java developers. And I'm sure somebody, somewhere, uses this fact in an obnoxious "gotcha" interview question. I hate those.

Richmond Java User Group - October

I gave a presentation on GWT at the Richmond JUG last night. There were about 20 people in attendance. Apart from some technical difficulties while demonstrating debugging in Development Mode, everything went well. We looked at the Google Plugin for Eclipse, some example GWT code created by the New Web Application wizard, and also briefly discussed Google App Engine.
I enjoyed having a chance to speak about a subject that is very exciting for me. I want to thank Remi Pelletier, Chris Allport, and the rest of the RJUG steering committee for organizing this and other RJUG events, and giving me a chance to speak. Thanks also to everyone who attended, listened, and asked questions.
I have granted access on Google Docs to a copy of the presentation I gave for anyone who wants to see it.

GWT, and AppEngine, and Eclipse - oh my!

There's much to be happy about for Java web developers this morning. Google has announced support for Java on AppEngine. Early access is being granted on a FIFO basis, however you can download the SDK now. But wait, there's more! This SDK includes the long-awaited Eclipse plugin for GWT! Read all about it on the GWT blog.

That's made my day.

NullPointerException

Why write about NullPointerExceptions?

NullPointerExceptions are one of the most basic runtime errors encountered in Java programming. Learning how to fix NullPointerExceptions is a vital skill for anyone programming in Java, as any student or amateur Java programmer will encounter these errors eventually. Sadly, even some professional Java programmers are stumped by them. I hope that this article will help programmers understand what NullPointerExceptions are, why they happen, and how to fix them. And for when all else fails, I'll offer a few pointers on asking for assistance with a NullPointerException.

What is a NullPointerException?

A NullPointerException is an unchecked runtime error. As such, NullPointerExceptions do not have to be declared in a method's throws clause. Because they are not checked exceptions, it is easy to forget about them and many programmers will not make any effort to handle or avoid NullPointerExceptions until they start occurring. A NullPointerException may indicate a logical error, improper data validation, incorrect use of an API, or some other programming problem.

Why do NullPointerExceptions happen?

A NullPointerException is caused by an attempt to dereference a pointer that doesn't point to anything; the pointer is null. Here are a couple of common scenarios where NullPointerExceptions can be found:

1.    String myString = null;
2.    System.out.println(myString.length());

Here a variable, myString, is declared and initialized to null on line #1. When line #2 attempts to deference the variable myString in order to print the string's length, a NullPointerException is thrown because myString doesn't point to anything.

1.    System.out.println(aMethodThatReturnsNull().toString());

This second example is a little trickier. No variable was declared, but there is still a pointer: the return value of the method aMethodThatReturnsNull(). That fictitious (and seemingly useless) method will always return null. As we saw in the first example, attempting to dereference a null pointer and call a method on the referenced object (which is null) results in a NullPointerException.

How do you track down a NullPointerException?

To find the source of a NullPointerException, start with the stack trace. In your Java console or log file, you'll see something like this:

Exception in thread "main" java.lang.NullPointerException
	at com.foo.example.NullPointerExample.main(NullPointerExample.java:21)

The stack trace tells you what happened (NullPointerException) and where (line 21 of NullPointerExample.java). Look at that line and see if you can recognize one of the two patterns given above. Ask yourself these questions:

  1. Are you calling a method on a variable that might be null?
  2. Are you calling a method on the return value of another method, where the first method might return null?
  3. Are you absolutely sure the answer to the first two questions was "no?" NullPointerExceptions can happen for other reasons, but these two are by far the most common.

How do you ask for help with a NullPointerException?

First, put some effort into it. Although most developer communities are ready and willing to help with problems relating to the community's subject area, NullPointerExceptions are very often simple programming errors and probably off topic for anything except a Java beginners forum. So before posting and asking for help, determine if the problem is in your own code.

Once you're certain that the exception isn't arising from your code, take a look at the code that is causing the exception (see above). You might be using an API improperly. Third-party libraries may not support null parameters, for example.

If you still need help, be sure to follow these guidelines when posting on a forum or emailing colleagues directly:

  • Be polite. You're asking for other people's time, generally without paying for it.
  • Be thorough.
    • Include the stack trace from the exception.
    • Include any of your code that is relevant to the stack trace.
    • Explain what you've done to troubleshoot and detail your findings.
  • Be patient. People are busy and have their own priorities. It may take hours or days to get a reply from the community, and longer to get a free solution. If you need immediate, devoted attention, you should expect to pay for it. If you want to "bump" your message to get more attention, don't just post "bump" or "can anyone help" -- offer up some additional information to demonstrate that you're taking ownership of the problem and still working on it (nobody wants to do your job for you!). Your new findings may elicit a response. Whining about not getting a response is unlikely to help matters and can alienate the community members who could assist you.

GWT 1.6 Milestone 1 Announced

Scott Blum from the GWT team announced the release of GWT 1.6 Milestone 1 on the GWT Contributor's forum yesteday evening. 1.6 will include, among other things, many bug fixes, support for a new project structure that more closely resembles a standard WAR file, and a new event system that originated in the GWT Incubator.

GWT in Eclipse

I came across this video last week. It's a presentation by Bruce Johnson, Technical Lead for the Google Web Toolkit on developing GWT applications with the Eclipse IDE. The first part of the presentation covers some basic introduction to GWT, followed by a little more detail on the inner workings of JSNI and hosted mode. The part I found most interesting was Bruce's discussion of the Eclipse plugin for GWT that Google has been working on internally but has not, as of yet, released to the general developer population. Some Q&A finishes out the session, as usual.

We've seen teasers about the plugin before on the GWT forums on Google Groups and some of the Eclipse project configuration files in SVN contain references to a "gwtNature" in a com.google package. This presentation went a tantalizing step further and included actual demonstration of the plugin's JSNI syntax highlighting and refactoring abilities, among other things. I wish we could get our hands on an early release version of the plugin, even an alpha or pre-alpha quality, just to try it out. So far, I haven't seen any firm commitment to a release date.

Several other informative presentations on GWT were given at Google I/O back in May. The GWT sessions are listed in the "APIs & Tools" track. The live sessions were a pleasure to attend and I highly recommend the videos, which I've referred back to on occasion since.

Introducing GwtCompilerTask

One of the first things I did when I started working with GWT was to figure out how to compile an application. I don't mean running the myApp-compile.[cmd|sh] that the setup utilities create. I mean ripping apart those compile scripts and writing an Ant script to do it. Here's how in a nutshell:

<target name="gwtc">
  <java 
      classname="com.google.gwt.dev.GWTCompiler" 
      classpathref="classpath.gwt" 
      fork="true">
    <arg value="com.foo.gwt.myapp.MyApp" />
  </java>
</target>

But this past weekend, I found I needed something a little more powerful. I was writing a build target to compile all of the demos in the GWT Incubator. I wanted to avoid having to explicitly list all of the demo modules and use a <java> task call for each one. The best way to find demo modules seemed to be starting from the demo source root directory and scanning for .gwt.xml files. Ant has a <foreach> task that will do just that. The problem then was that <foreach> identifies the module files (com/foo/gwt/myapp/MyApp.gwt.xml), but GWTCompiler requires the logical module name (com.foo.gwt.myapp.MyApp). Ant is great for manipulating files, but it doesn't have much to offer in the way of runtime String manipulation. The solution? Leverage a more full-bodied programming environment. Like Java.

So I wrote a custom Ant task to handle invoking the GWTCompiler and to bridge the gap between the module's file name and it's logical name. Here's what the demo build looks like:

<target name="gwtc" depends="compile">
  <!-- define the GwtCompilerTask -->
  <taskdef 
      name="gwtc" 
      classname="com.google.ant.GwtCompilerTask">
    <classpath>
      <path path="${project.bin}" />
      <pathelement location="${gwt.dev.jar}" />
    </classpath>
  </taskdef>

  <property name="gwtc.vm.maxMemory" value="512m" />

  <!-- gwtc supports compiling with moduleName or moduleFile.
       Use of moduleFile requires setting src so that the 
       logical module name can be determined by comparing the
       moduleFile path to the source root path. vmMaxMemory
       sets the -Xmx VM argument. -->
  <gwtc src="${gwtc.src.dir}"
        out="${gwtc.out.dir}"
        moduleFile="${gwtc.module.file}"
        style="${gwtc.js.style}"
        vmMaxMemory="${gwtc.vm.maxMemory}">
    <!-- gwtc supports nested classpath -->
    <classpath>
      <path path="${gwtc.src.dir}" />
      <path path="${project.src}" />
      <path path="${project.bin}" />
      <pathelement location="${gwt.user.jar}" />
      <pathelement location="${gwt.dev.jar}" />
      <pathelement 
        location="${gwt.tools}/lib/w3c/sac/sac-1.3.jar" />
      <pathelement 
        location="${gwt.tools}/lib/w3c/flute/flute-1.3.jar" />
    </classpath>
  </gwtc>
</target>

<target name="build.demos">
  <property 
      name="demo.src.dir"
      value="${project.root}/src-demo" />
  <property name="demo.out.dir" value="${project.root}/demo" />
  <property name="demo.js.style" value="PRETTY" />

  <!-- Scan for any file under src-demo ending in .gwt.xml. For
       each file, invoke the gwtc target. The full path to the
       file is passed to gwtc target as gwtc.module.file -->
  <foreach target="gwtc" param="gwtc.module.file">
    <param name="gwtc.src.dir" value="${demo.src.dir}" />
    <param name="gwtc.out.dir" value="${demo.out.dir}" />
    <param name="gwtc.js.style" value="${demo.js.style}" />
    <path>
      <fileset dir="src-demo">
        <include name="**/*.gwt.xml" />
      </fileset>
    </path>
  </foreach>
</target>

GwtCompilerTask can also be used for building regular single-module GWT applications. GwtCompilerTask is available in the GWT Incubator. You will need to build gwt-incubator.jar from trunk at revision 1133 or later.

Taking Command of Your GWT Application

I love interfaces in Java. When used properly, they make for code that is highly cohesive and loosely coupled. Classes that implement interfaces or declare method parameters with interfaces are easier to reuse. One of my favorite interfaces in the Google Web Toolkit is Command. Command has one method:

public void execute();

That's it. A Command can be executed. Command, like the HasValue interface in the GWT Incubator is a very simple interface. So often in programming it is these simple building blocks that give us the greatest opportunities. Let's build on Command and another basic component, Button.

public class CommandButton extends Button {
  public CommandButton(final String html, final Command command) {
    super(html);
    addClickListener(new ClickListener() {
      public void onClick(Widget sender) {
        command.execute();
      }
    });
  }
}

There. Now we can create Buttons that execute a Command when clicked. If your application uses a lot of Buttons, that saves a lot of code for adding ClickListeners. And the code you might've put in those anonymous ClickListeners is now safely encapsulated inside a reusable Command class. I use some variation on CommandButton in almost every application I build. Here's another one I use:

public class CommandLabel extends Label {
  public CommandButton(final String text, final Command command) {
    super(html);
    addClickListener(new ClickListener() {
      public void onClick(Widget sender) {
        command.execute();
      }
    });
  }
}

Almost identical to CommandButton, isn't it? This one just uses a text Label instead of a Button. You can do the same with an Image if you want (and I have). I even wrote one with a ToggleButton.

At some point, I'm going to find the time to start a library project with all of these simple Widget extensions.

public int getValue()

This week I committed my first change as a member of the GWT Incubator project. That change was to introduce an interface, HasValue. This by itself is no monumental achievement. The interface is very simple:

public interface HasValue<T> {
 T getValue();
 void setValue(T value);
}

But this simple interface will facilitate the creation of more complex features such as libraries for data binding or validation.

HasValue provides a layer of abstraction around Widgets, allowing access to the underlying data model through a common API. HasValue works with simple Widgets and data types as well as complex data types and composite Widgets.

Consider two Widgets (both from the Incubator) for selecting a Date value:

DatePicker picker = new DatePicker();
DropDownListBox<Date> dropDown = new DropDownListBox<Date>();

Both implement HasValue<Date> so you could, for example, write a BirthdayValidator that ensures the selected Date is before today. This validator would have a HasValue<Date> parameter and could validate either of the two Widgets above, or any other Widget implementing the HasValue<Date> interface, without additional coding to support those Widgets.

Right now HasValue exists only in the Incubator, but there is support for including it in the next GWT release, version 1.6. Hopefully that release will see HasValue implemented by most of the standard GWT Widgets. In the mean time, I would love to see how GWT application developers use HasValue in their own projects. If you haven't worked with the Incubator before, you'll want to setup the project locally so you can build the latest features. Here's where to start:

Setting up the GWT Incubator project