Showing posts with label if. Show all posts
Showing posts with label if. Show all posts

Thursday 20 September 2007

To be null or not to be ?


Book myBook = getBookFromSomeWhere();
System.out.println("myBook: " + myBook);

if (myBook == null) {
System.out.println("myBook is null");
}
else {
System.out.println("myBook is not null");
}


Run it ! And that display :

myBook: null
myBook is not null


How is it possible ?

Hahaha.

It is because we have:

Book {
...

public String toString() {
return "null";
}


Funny, isn't it ?

Wednesday 20 June 2007

Constant++


// FYI: Constants is a class (not an interface)

if (ts != null && ts.getTs().intValue() == 1){
nbPc = Constants.CONST1A;
Constants.CONST1A = Constants.CONST1A + 1;

nbPs = Constants.CONST1B;
Constants.CONST1B = Constants.CONST1B + 1;
} else if (ts != null && ts.getTs().intValue() == 2){
nbPc = Constants.CONST2A;
Constants.CONST2A = Constants.CONST2A + 1;

nbPs = Constants.CONST2B;
Constants.CONST2B = Constants.CONST2B + 1;
} else if (ts != null && ts.getTs().intValue() == 3){
nbPc = Constants.CONST3A;
Constants.CONST3A = Constants.CONST3A + 1;

nbPs = Constants.CONST3B;
Constants.CONST3B = Constants.CONST3B + 1;
} else if (ts != null && ts.getTs().intValue() == 4){
nbPc = Constants.CONST4A;
Constants.CONST4A = Constants.CONST4A + 1;

nbPs = Constants.CONST4B;
Constants.CONST4B = Constants.CONST4B + 1;
}

Oh that ignominious code.
First, it appears that if some fields were in a Class named Constants, they will be final.
The ts variable can be tested different from null only once.
Use myVariable++ instead of myVariable = myVariable + 1
At last, the use of if-statement to compare ts.getTs().intValue() to an int is not the best technic.

No brackets !

Let's have:


if (condition)
doSomething();

And later, add doOtherThing() method to the condition.

if (condition)
doSomething();
doOtherThing();

And later, it appends. Ooops. I forgot the brackets.
So, I don't know why it is not required in every languages, BUT you MUST always use brackets.

if (condition) {
doSomething();
}

And then

if (condition) {
doSomething();
doOtherThing();
}

This time I didn't forget the brackets 8-))