Re: Beginner, this will be a quick fix, so please check it out!!
venu wrote:
[snip]
Please initialize all variables to 0 in a
Java program. Well the last part is just my superstition.
Please do NOT initialize all variables to 0 in a Java program!
You should not declare your variables until they are first needed and
can be assigned. If possible, its good practice to declare them final.
This ensures that they will only ever be initialized once, even if you
go through different branches to initialize them.
final int pageSize;
if (pageNumber == 0) {
pageSize = 10;
} else {
pageSize = 20;
}
someOtherObject.doSomethingWithPageSize(pageSize);
Better yet, if you can initialize a variable to two different values,
but only use one, make it into a method:
private int getPageSize() {
if (pageNumber == 0) {
return 10;
} else {
return 20;
}
}
// then you can use:
final int pageSize = getPageSize();
someOtherObject.doSomethingWithPageSize(pageSize);
Or even better, "inline" that variable (don't use the variable, just use
what you assigned to it, since it has a meaningful name now)
someOtherObject.doSomethingWithPageSize(getPageSize());
Even if you call getPageSize a few times, its better design. If and
only if you find that calling that method slows down your application
beyond a reasonable level should you "optimize" to saving the value.
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>