Sunday, June 6, 2010

Java Generics and Synthetic Bridge Method

I'll take you to a Java-landia magical mystery tour, this time it's got something to do with generics.

Take a look at the example below.

MeanMeter.java:


public interface MeanMeter < T > {
boolean isMean(T t);
}


Compile this class and run "javap -c MeanMeter" produces:


Compiled from "MeanMeter.java"
public interface MeanMeter{
public abstract boolean isMean(java.lang.Object);

}


What happened to our parameter type T?!

OK. Park that for now. Let's look at another example.

JimsCreation.java:


public class JimsCreation implements MeanMeter< JimsCreation.Garfield > {
public boolean isMean(Garfield garfield) {
return true;
}

public static void main(String[] args) {
JimsCreation jimsCreation = new JimsCreation();
jimsCreation.isMean(new Garfield());
}

public static class Garfield {
}
}


Now, take a deep breath. Compile then run "javap -p JimsCreation" from command line.

Below is the result:


Compiled from "JimsCreation.java"
public class JimsCreation extends java.lang.Object implements MeanMeter{
public JimsCreation();
public boolean isMean(JimsCreation$Garfield);
public static void main(java.lang.String[]);
public boolean isMean(java.lang.Object);
}


We got 2 "isMean" methods?!!! What's going on here?!

Rub your eyes. Yes, Javac gave us 2 methods with different argument type!

"Is this some kind of black magic?"


So what happened here was that the compiler tricked us by introducing a "bridge" method - another word for "smart-overloaded-method-created-by-javac". It cleverly erased our generic type "T" and replaced it with "java.lang.Object" in MeanMeter interface; it also inserted the said signature into JimsCreation class. This is because Java promised backward compatibility to support non-generic sources from pre-JDK5 days.

By typing "javap -c JimsCreation" produces:


Compiled from "JimsCreation.java"
public class JimsCreation extends java.lang.Object implements MeanMeter{
public JimsCreation();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."< init >":()V
4: return

public boolean isMean(JimsCreation$Garfield);
Code:
0: iconst_1
1: ireturn

public static void main(java.lang.String[]);
Code:
0: new #2; //class JimsCreation
3: dup
4: invokespecial #3; //Method "< init >":()V
7: astore_1
8: aload_1
9: new #4; //class JimsCreation$Garfield
12: dup
13: invokespecial #5; //Method JimsCreation$Garfield."< init >":()V
16: invokevirtual #6; //Method isMean:(LJimsCreation$Garfield;)Z
19: pop
20: return

public boolean isMean(java.lang.Object);
Code:
0: aload_0
1: aload_1
2: checkcast #4; //class JimsCreation$Garfield
5: invokevirtual #6; //Method isMean:(LJimsCreation$Garfield;)Z
8: ireturn

}


LO AND BEHOLD!!!"


Look at the last method at line 28! It casts the object type parameter to JimsCreation$Garfield^ at line 32 and invokes the overloaded method at line 33!

So the main question is what happens if we invoke JimsCreation.isMean(Garfield) method? Does it invoke the bridge method or the original method? Answer - it still invokes the original method. See line 24.


^JimsCreation$Garfield represents Garfield as static class to JimsCreation.

Wednesday, June 2, 2010

My DeLorean Package

I'm tasked by Dr. Emmett Brown to help Marty McFly travel to different time periods successfully on Doc's time machine - DeLorean!

However, I must ensure DeLorean must at least hit the speed of 88 miles per hour (142 km/h) for the flux capacitor to kick-in, then a big ZAP and vanishes from sight.

Below is the source code:
package delorean;
import java.util.Date;

public class DeLorean {
private static final int MAX_SPEED_MPH = 88;

public boolean timeTravel(Date date, int speedMPH) {
System.out.println("Setting DeLorean target date " + date);

if (prepareTimeTravel(speedMPH)) {
System.out.println("Time travel was successful, we are now on " + date);
return true;
}

System.out.println("Time travel failed");
return false;
}

private boolean prepareTimeTravel(int speedMPH) {
// we need at least 88 mph or equivalent to 142 km/h
// to activate flux capacitor for time travel
if (speedMPH >= MAX_SPEED_MPH) {
System.out.println("Activating flux capacitor");
return true;
}

return false;
}
}


I also wrote a unit-test to ensure the flux capacitor activates once speed is at 88 mph during Marty's travel:

package delorean;
import java.util.Calendar;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;

public class DeLoreanTest {
private static Calendar future;
private DeLorean deLorean;

static {
future = Calendar.getInstance();
future.set(Calendar.YEAR, 2015);
future.set(Calendar.DAY_OF_MONTH, 21);
future.set(Calendar.MONTH, Calendar.OCTOBER);
}

@Before
public void init() {
deLorean = new DeLorean();
}

@Test
public void testTimeTravelSuccess() {
Assert.assertTrue(deLorean.timeTravel(future.getTime(), 88));
}

@Test
public void testTimeTravelFailed() {
Assert.assertFalse(deLorean.timeTravel(future.getTime(), 87));
}
}


Below is the result of the test:

Setting DeLorean target date Wed Oct 21 03:03:50 EST 2015
Activating flux capacitor
Time travel was successful, we are now on Wed Oct 21 03:03:50 EST 2015
Setting DeLorean target date Wed Oct 21 03:03:50 EST 2015
Time travel failed

Everything looks fine, but...


OK I admit I'm test infected and I really feel the urge to also test "prepareTimeTravel" method alone by itself. However, how am I suppose to do this when it's defined as a private method? Surely I can turn this to public but I'd rather keep this abstracted away from Marty as he doesn't need to know the nitty-gritty details between the car's acceleration and the flux capacitor. All he needs to know is to step on accelerator pedal to reach 88 miles per hour and *poof* he goes.



*Thinking, thinking, thinking...*



What about setting this method as package scope? This means "prepareTimeTravel" method will only be visible to classes of the same package, including DeLoreanTest class (same package name)^. This also ensure classes from other packages won't see this method. This sounds like what I'm looking for.


package delorean;
import java.util.Date;

public class DeLorean {
private static final int MAX_SPEED_MPH = 88;

public boolean timeTravel(Date date, int speedMPH) {
System.out.println("Setting DeLorean target date " + date);

if (prepareTimeTravel(speedMPH)) {
System.out.println("Time travel was successful, we are now on " + date);
return true;
}

System.out.println("Time travel failed");
return false;
}

boolean prepareTimeTravel(int speedMPH) {
// we need at least 88 mph or equivalent to 142 km/h
// to activate flux capacitor for time travel
if (speedMPH >= MAX_SPEED_MPH) {
System.out.println("Activating flux capacitor");
return true;
}

return false;
}
}



The updated unit-test looks like this:

package delorean;
import java.util.Calendar;
import junit.framework.Assert;
import org.junit.Before;
import org.junit.Test;

public class DeLoreanTest {
private static Calendar future;
private DeLorean deLorean;

static {
future = Calendar.getInstance();
future.set(Calendar.YEAR, 2015);
future.set(Calendar.DAY_OF_MONTH, 21);
future.set(Calendar.MONTH, Calendar.OCTOBER);
}

@Before
public void init() {
deLorean = new DeLorean();
}

@Test
public void testTimeTravelSuccess() {
Assert.assertTrue(deLorean.timeTravel(future.getTime(), 88));
}

@Test
public void testTimeTravelFailed() {
Assert.assertFalse(deLorean.timeTravel(future.getTime(), 87));
}

@Test
public void testPrepareTimeTravelSuccess() {
Assert.assertTrue(deLorean.prepareTimeTravel(88));
Assert.assertTrue(deLorean.prepareTimeTravel(89));
Assert.assertTrue(deLorean.prepareTimeTravel(90));
}

@Test
public void testPrepareTimeTravelFailed() {
Assert.assertFalse(deLorean.prepareTimeTravel(87));
Assert.assertFalse(deLorean.prepareTimeTravel(86));
}
}

Vroooom... ZAP - *poof*



^ When using Maven, DeLorean class sits under "src/main/java directory" and DeLoreanTest class sits under "src/test/java" directory. Both classes contains same package name, hence package-scope method "prepareTimeTravel" will be visible to test class.

Saturday, April 17, 2010

Identity Crisis: JPA @Id

Who am I?

Allow me to show you a simple JPA mapping,

@MappedSuperclass
public class Domain implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ID_SEQ")
private Integer id;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}
}



Do you see the thorny issue here?

Look again.

Yes, you're right - the setter method!

@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ID_SEQ")

public void setId(Integer id) {
this.id = id;
}



In my view, the setter method should not be there at all as id property is marked as "sequence". How often do you invoke setId(Integer) method? I believe rarely or almost never.

A question emerges from the back of your mind - "But I need that for my unit test?!".

If you populate this property yourself, then there's something wrong with your unit test and I strongly suggest that you rethink the way you write your test code.

I admit I've done this before many times. You are not alone my friend.

"Who is it that can tell me who I am?"

Sunday, February 21, 2010

I Wanna Be A JavaDoc Writer

Dear Sir or Madam will you read my JavaDoc?
It took me 'while to write, agonise will you take a look?
It's based on a spec by a person very dear
And I need a job and I wanna be a JavaDoc writer,
JavaDoc writer...


Do you write JavaDocs? I'm not sure how productive this would be to you, but I personally find writing JavaDoc for trivial methods, especially those requires a little thinking, ensures that I fully understood what I need to do before I start my Pee Wee's big adventure.

Once upon a time, on one lazy Friday afternoon, I restricted myself with TDD approach, that is write test code before implementation. It occurred to me that my input field will be populated by a name thus, I need to break them down into first name and last name. Easy-peasy, invoke split method from String class and pass space character as delimeter! The first element of returned String array will always represent the first name and second element will always represent the last name.

Before I started the name-parser method implementation, I wrote a small documentation right on top instead. Since I never had a poetic license in my entire life, let alone enrolled myself in three semesters of English-lit during my Uni days, my JavaDoc documentation was, is and will never be written as technical, as formal as I want it to be. I always end up with mediocre technical English documentation. I know I'm useless.

"Oh Uncle Bob, where art thou?"

One thing struck me as I happily started typing my doco - clackity-clack, what happens when someone calls himself "Donkey Kong Jr."? Clackity-clack.

(For argument's sake, let's put the spec aside for now.)

Surely, I can assume his first name is "Donkey" and last name is "Kong Jr." What about "King Henry VIII" and "Don Quixote de la Mancha"?

Hmmm, doesn't sound right, does it...?

I found myself dumbstruck at that particular instance, not to the problem nor to the solution, but to myself - a sudden self-pity, self-realisation of how naive and simple-minded I was.

So, do you want to be a JavaDoc writer?

Clackity-clack.