If Then (If Then Else) Else (If Then Else)

April 23, 2008

In the same series than Andy Maleh post to-if-else-or-not-to-if-else and after discussions with colleagues I am wondering how you write the following problem using Java If-Else.

Object a;
Object b;
a == null and b == null -> method1()
a == null and b != null -> method2()
a != null and b != null -> method3()
a != null and b == null -> method4()

Which method to choose taking into account performances and redability between:

if (a == null && b == null) {
method1();
} else if (a == null && b != null) {
method2();
} else if (a != null && b != null) {
method3();
} else {
method4();
}

Or

if (a == null) {
if (b == null) {
method1();
} else {
method2();
}
} else {
if (b != null) {
method3();
} else {
method4();
}
}

About readability I’ll personally choose the first solution. About performances … I am not sure there is a difference after JVm’s optimizations … ??


Java Fields Visibility / Public - Private - Protected ….

February 14, 2008

For a long time, my understanding of Java fields visibility was wrong !!!

Here are the right visibilities for public, private, protected and package fields

private : can be accessed only from the class declaring the field

public : can be accessed from everywhere

package (when no visibility is specified) : can be accessed from every class within the same package

protected : can be accessed from any subclass OR from any class within the same package (protected = package + subclasses)


Integer- -

January 18, 2008

What’s hapen when writting using Java langage :

Integer myInt = new Integer(2);
myInt- -;

??

In fact, i had a Map and i was doing this on it :

Integer mynt = Map.get(myString);
myInt- -;

thinking that it would modified the map entry associated to myString.

I was wrong !!!!! Here the Java VM behaves the same way than writting :
myInt = new Integer(myInt.getValue() - 1);

What do you think about that ? To my eyes it’s quite confusing …