Saturday, August 27, 2011

Keeping Barbarians at the Gate

My workstation sits at the further end of five workstations aligned adjacently in a row. The walls of the entire floor are painted in white, seemingly dull but immaculate. The dark grey carpet covered across the floor adds sombre to the yet harsh cold August winter.

Looking at the distant window from where I sit,
        I know it’s another bleak day.


I can’t remember if I had seen sunlight two or three days ago. Perhaps four? Maybe there was one yesterday. Seriously, I can’t recall and I can’t be bothered at all.

I’m glued to my screen that I can’t hear the noise around me – because I’m busy keeping the barbarians at the gate.


class User {
private TimeInterval accessibleTime;
private Set<String> accessCodes;

public User(TimeInterval accessibleTime) {
this.accessibleTime = accessibleTime;
}
}


Add null pointer check to parameter and ensure the API validates against incorrect time interval:

public User(TimeInterval accessibleTime) {
if (accessibleTime== null) {
throw new IllegalArgumentException(
"accessibleTime parameter cannot be null");
if (accessibleTime.getFromTime() > accessibleTime.getToTime()) {
throw new IllegalArgumentException("accessibleTime time from [" + acc
essibleTime.getTimeFrom() + "] is later than time to [" + accessibleTime.getTime
To() + "]");
this.accessibleTime = accessibleTime;
}


Generate getter and setter methods:

@YetAnotherNotNullValidation(message = "access codes cannot be null")
public String getAccessCodes() {
return accessCodes;
}

public String setAccessCodes(Set<String> accessCodes) {
this.accessCodes = accessCodes;
}



Hang on, should I expose this setter method even though I have a validation annotation of NotNull hoisted up there? It should be alright I guess, as the validation framework should catch this during runtime. But then again, it requires extra effort to check null values.


// Someone accidentally wipes out accessCodes somewhere in the code
user.setAccessCodes(null);

// and I need to add null check to prevent NPE
if (user.getAccessCodes() == null) {
user.setAccessCodes(new HashSet<String>());
}


Do I want to see this sprinkled everywhere? Perhaps not. It is easy to misuse the setter method and leave accessCode variable in limbo. Better get rid of this, I would rather not have "Midas Touch" effect here.


doSomething(user.getAccessCodes());
// to clear out values
user.getAccessCodes().clear();


Tuesday, April 26, 2011

Java Inner Class vs Static Inner Class

On one lazy Friday afternoon, I find myself mesmerised by the fact that I subconsciously write statically nested inner class as oppose to writing the usual nested class in Java. For every small nestable class that I can think of, I somehow feel obliged to prepend it with a static keyword.

If my recollection serves me right, it was from a code review that I had years ago. A colleague pointed his finger on my screen and loudly exclaimed, “This nested class is inefficient!”

Yes, he is right! But how inefficient is inefficient? How does the instance look like if I were to draw it on a piece of paper? How big does this affect the VM’s memory?

"See Colonel Sartoris. I have no taxes in Jefferson."


Time to roll up our sleeves and have a look under the hood.

OuterEmily.java
package aroseforemily;

public class OuterEmily {
public void dontPayTax() {
}

public class InnerEmily {
public void buyArsenic() {
}
}
}


Running javap -c aroseforemily.OuterEmily gives us:

Compiled from "OuterEmily.java"
public class aroseforemily.OuterEmily extends java.lang.Object{
public aroseforemily.OuterEmily();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: return

public void dontPayTax();
Code:
0: return
}

Running javap -c aroseforemily.OuterEmily\$InnerEmily gives us:
Compiled from "OuterEmily.java"
public class aroseforemily.OuterEmily$InnerEmily extends java.lang.Object{
final aroseforemily.OuterEmily this$0;

public aroseforemily.OuterEmily$InnerEmily(aroseforemily.OuterEmily);
Code:
0: aload_0
1: aload_1
2: putfield #1; //Field this$0:Laroseforemily/OuterEmily;
5: aload_0
6: invokespecial #2; //Method java/lang/Object."":()V
9: return

public void buyArsenic();
Code:
0: return
}


By looking at aroseforemily.OuterEmily$InnerEmily, the compiler inserts a synthetic final OuterEmily member variable this$0, at the same time adds a synthetic non-default constructor. From line 7-9 we can see that it assigns the final member variable from the constructor parameter.

The druggist named several. "They'll kill anything up to an elephant. But what you want is—"

"Arsenic," Miss Emily said. "Is that a good one?"


What happens if we set the inner class to static?

package aroseforemily;

public class OuterEmily {
public void dontPayTax() {
}

public static class InnerEmily {
public void buyArsenic() {
}
}
}


Rerunning javap -c aroseforemily.OuterEmily\$InnerEmily yields:
Compiled from "OuterEmily.java"
public class aroseforemily.OuterEmily$InnerEmily extends java.lang.Object{
public aroseforemily.OuterEmily$InnerEmily();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: return

public void buyArsenic();
Code:
0: return
}


The second disassembled code suggests that for every instance of inner class, they will always contain an extra reference to the outer class; hence nested classes are less optimal compared to static nested classes, especially when inner classes are strongly referenced and prevents weak referenced outer class from GCed.