Mobile JUnit: Java ME Unit Testing

I’ve been playing around with Mobile JUnit, a great new tool from Sony Ericsson. If you’re a Java SE or EE programmer, you’re probably familiar with the JUnit project, an open source unit testing framework for Java. With JUnit you write simple classes (test cases) that have a number of methods that use assertions to test various aspects of your code:

import com.sonyericsson.junit.framework.*;

public class MyTest extends TestCase {
    public void testOnePlusOne(){
        assertBoolean( 1 + 1 = 2 );
    }
}

You can build entire test suites of test cases and automatically run the tests using test runners that display their results either on the console or in a window (there are runners for AWT and for Swing).

Mobile JUnit is a rewrite of JUnit specifically for CLDC-based platforms. Because JUnit depends on reflection and reflection is not available with the CLDC, Mobile JUnit takes a different approach and gathers testing information at compile time and generating helper classes to actually run the tests. (As a side note, Mobile JUnit is based on JUnit 3.8.1 — later versions of JUnit have dependencies on Java 1.5 features like annotations.) It then compiles everything into a MIDlet and runs the MIDlet in the emulator for you. You can even do on-device testing (for Sony Ericsson phones) if necessary, without having to install the MIDlet on the device — Mobile JUnit takes care of that for you.

Even though Mobile JUnit is from Sony Ericsson and by default assumes you’re using it with the Sony Ericsson SDK for CLDC programming, Mobile JUnit can be used with any tool that is based on Sun’s Wireless Toolkit (WTK). If you’re looking to add some automated testing to your build procedure (Mobile JUnit integrates well with Ant) then check it out.

Technorati Tags: , , , , ,

Share and Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
  • blinkbits
  • BlinkList
  • blogmarks
  • co.mments
  • connotea
  • del.icio.us
  • De.lirio.us
  • digg
  • Fark
  • feedmelinks
  • Furl
  • LinkaGoGo
  • Ma.gnolia
  • NewsVine
  • Netvouz
  • RawSugar
  • Reddit
  • scuttle
  • Shadows
  • Simpy
  • Smarking
  • Spurl
  • TailRank
  • Wists
  • YahooMyWeb

Revisiting J2ME Object Serialization

A couple of weeks ago I received an email from someone who had read my J2ME Tech Tip Object Serialization in CLDC-based Profiles, written in 2002. As most of you probably know, object serialization — persisting the state of an object so that you can recreate the object later — is one of the things missing from the CLDC. Given that most devices these days are CLDC-based (with MIDP support), that tech tip was meant to solve a common problem that developers face when writing Java ME applications that need to store or communicate their state.

The basic idea is quite simple: define a common interface (Persistent) with methods that are invoked whenever the application wants the object to save or restore its state. It’s not automatic by any means, because the creator of the class has to write the code that does the saving (persist) and the restoring (resurrect). But with our trusty friends DataInputStream and DataOutputStream it’s pretty easy to do and with some forethought (put a version number at the start of the serialization stream) you can even write persistence code that is upwardly compatible.

Restoring the object is not as elegant as it could be, however. This is because we can only create objects via the newInstance method of the Class object. So what we do is create a prototype object using the null constructor (which, due to the lack of reflection, is the only one available to us) and then invoke resurrect to initialize the new object’s state.

This particular reader was having problems with the speed of the object restoration in my VectorHelper class. VectorHelper is a convenience class used to persist and restore Vector objects, as long as the Vector contained nothing but strings, integers or objects that implement Persistent.

Here’s the restoration code in question:

   public static Vector resurrect( byte[] persisted )
                            throws IOException {
        ByteArrayInputStream bin =
                    new ByteArrayInputStream( persisted );
        DataInputStream      din =
                    new DataInputStream( bin );

        Vector v = new Vector();
        int n = din.readInt();

        for( int i = 0; i < n; ++i ){
            int type = din.readByte();
            if( type == NULL ){
                v.addElement( null );
            } else if( type == INTEGER ){
                v.addElement( new Integer( din.readInt() ) );
            } else if( type == STRING ){
                v.addElement( din.readUTF() );
            } else if( type == PERSISTENT ){
                String cname = din.readUTF();
                int    len = din.readInt();
                byte[] tmp = new byte[ len ];

                din.readFully( tmp );

                try {
                    Class cl = Class.forName( cname );
                    Object o = cl.newInstance();
                    ((Persistent) o).resurrect( tmp );
                    v.addElement( o );
                }
                catch( IOException e ){
                    throw e;
                }
                catch( Exception e ){
                    throw new IOException( "Exception " +
                        e.toString() );
                }
            } else {
                throw new IOException( "Unknown " +
                   "type " + type );
            }
        }

        return v;
    }

Can you guess where the bottleneck might be?

It’s the code that restores Persistent objects:

    Class cl = Class.forName( cname );
    Object o = cl.newInstance();
    ((Persistent) o).resurrect( tmp );
    v.addElement( o );

The problem is that dynamically looking up a class (Class.forName) and/or instantiating it (cl.newInstance) is very slow on some devices. The solution for my reader was to speed up this process by removing the generic class lookup and instantiation code and replacing it with code specific to his application. For example, say you had two classes Employee and Student that both implemented Persistent. Then you could code:

    Object o;
    if( cname.equals( "com.mypackage.Employee" ) ){
        o = new Employee();
    } else if( cname.equals( "com.mypackage.Student" ) ){
        o = new Student();
    } else {
        throw new UnknownClassException(); // oops!
    }
    ((Persistent) o).resurrect( tmp );
    v.addElement( o );

And suddenly the restoration code is much faster.

The whole point of this example is that Java ME programming often boils down to writing specialized code instead of writing generic code. The examples in my J2ME Tech Tips and other articles tend to be generic because they need to work over a wide variety of platforms. And writing generic code often feels like the “right” or “correct” thing to do. But correctness in programming isn’t about conforming to abstract notions of what’s good and what’s bad, it’s about writing code that works and meets user expectations. This is particularly true with Java ME programming. You can get away with a lot of fat on desktop or server Java — you just run it on a faster machine or give the VM more memory. You can’t do that with Java ME applications.

Somedays when I’m feeling prickly I think that all Java programmers should learn Java on an old Motorola or Nokia phone with a 50K limit to the size of the application. Because it really forces you to think carefully about your algorithms and how you’re using memory. And in the end I think it makes you a better programmer. If I had to choose between hiring someone who’d learned Java by doing J2ME programming versus someone who’d learned it doing J2EE programming, I’d hire the J2ME coder.

Any Java coder can learn new APIs, but learning the mindset of efficient and effective Java coding is much harder to do if it’s not ingrained from day one.


Technorati Tags: , , , , , ,

Share and Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
  • blinkbits
  • BlinkList
  • blogmarks
  • co.mments
  • connotea
  • del.icio.us
  • De.lirio.us
  • digg
  • Fark
  • feedmelinks
  • Furl
  • LinkaGoGo
  • Ma.gnolia
  • NewsVine
  • Netvouz
  • RawSugar
  • Reddit
  • scuttle
  • Shadows
  • Simpy
  • Smarking
  • Spurl
  • TailRank
  • Wists
  • YahooMyWeb

The J2ME Programming Guide

Welcome to Eric Giguere’s J2ME programming guide. Technically, I should say “Java ME programming” instead of “J2ME programming”, but I still have a soft spot for the term J2ME. Let me explain and give you some idea of what I plan to do with this site.

What Does J2ME Stand For?

J2ME is an acronym for Java 2 Micro Edition, known more formally as Java 2 Platform, Micro Edition. When Java 2 was introduced in 1999 as the formal name for the Java programming environment (renaming what until then had been known simply as “Java 1.2″), the Java platform was split into three variants:

  • Java 2 Standard Edition (J2SE), aka “desktop Java” — the Java we all knew and loved
  • Java 2 Micro Edition (J2ME), aka “wireless Java” — Java for mobile phones, handheld devices, and other constrained environments
  • Java 2 Enterprise Edition (J2EE), aka “server-side Java” — Java for server-side, database- and message-centric computing

Of course, if a name changes once, there’s nothing to prevent it from changing twice…

What does Java ME Stand For?

In 2005, Sun decided that the “2″ in “Java 2″ no longer made any sense as a platform designation, given that Java 5 (aka Java 1.5) was now the standard and that Java 6 was in development. Henceforth, the three variants of the Java platform would be known as:

  • Java Standard Edition (Java SE)
  • Java Micro Edition (Java ME)
  • Java Enterprise Edition (Java EE)

So J2ME officially became Java ME. Sun sucked it in and went and renamed all references to these technologies on its websites and documents.

J2ME Just Sounds Better

So given that Java ME is the official shorthand term for wireless Java, why do I still refer to J2ME?

Call it force of habit… I’ve been writing about J2ME since 1999, when I first started writing Java 2 Micro Edition: Professional Developer’s Guide. This continued with the publication of my J2ME Tech Tips and various articles on Sun’s developer site. And of course the second book. In short, the term is ingrained.

But I also find that “J2ME” rolls off the tongue much more easily, at least in English. “Java ME” is longer, and “JME” sounds like someone’s name. So that’s another reason to stick with J2ME. I suspect many of the old-timers (hello everyone on the KVM-INTEREST mailing list) feel the same way, though I’ve never asked anyone else.

What To Expect From This Guide

The Java ME Programming Guide J2ME Programming Guide is my new site for J2ME-related material, a replacement of sort for Eric’s J2ME Pages, which I never really fleshed out. Rather than refashion those pages, I’ve decided to start anew.

What you can expect here is the occasional post with tips, tutorials and news about J2ME programming. I’ll be updating some of my older material, announcing the publication of new material, and posting the occasional comment or essay about J2ME.

It’s my new window into the world of Java ME programming, and I hope you’ll ride along with me.

Technorati Tags: , , , , ,

Share and Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
  • blinkbits
  • BlinkList
  • blogmarks
  • co.mments
  • connotea
  • del.icio.us
  • De.lirio.us
  • digg
  • Fark
  • feedmelinks
  • Furl
  • LinkaGoGo
  • Ma.gnolia
  • NewsVine
  • Netvouz
  • RawSugar
  • Reddit
  • scuttle
  • Shadows
  • Simpy
  • Smarking
  • Spurl
  • TailRank
  • Wists
  • YahooMyWeb