Monday, October 22, 2007

JavaSpecialists Notes - I

This is the first part of a series of blogs that I would write in order to keep the crux of all the JavaSpecialists Newsletters at one place for a quick reference. It would include the links and excerpts from the original newsletter.

Issue 1: Deadlocks

In Swing, all GUI components have to be changed from within the Swing thread.
This means that you cannot execute jLabel1.setText("blabla") from within any thread
besides the Swing thread.
If you have change any GUI from another thread you should rather say:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
jLabel1.setText("blabla");
}
}

Issue 2: Anonymous Inner Classes

If you wanted to pass in a Collection instead of an array it would look as follows:

Collection temp_names = new Vector(3);
temp_names.add("Heinz");
temp_names.add("John");
temp_names.add("Anton");
universityRegistration.addNames(temp_names);

The ability to avoid local temporary variables with arrays was always a strong
deciding factor in defining interfaces to my classes because I could get away with
one line of code instead of five, and the less lines of code the better. I would
therefore rather define addNames(String[] names) than addNames(Collection names) even
if it meant I would have to convert backwards and forwards between arrays and
collections. However, with anonymous inner classes we can get the same effect seen
above but with collections:

universityRegistration.addNames(new Vector(3)
{{ add("Heinz"); add("John"); add("Anton"); }});

Issue 8: boolean comparisons

boolean pentiumTMcpu = Utils.isCpuAPentium();
if (pentiumTMcpu == true) {
/* work out incorrect salary using double */
}

This will compile fine in Java, but so will the following, which assigns true to
pentiumTMcpu and will always work out the salary using the Pentium bug (younger
readers would not remember):

boolean pentiumTMcpu = Utils.isCpuAPentium();
if (pentiumTMcpu = true) {
/* this code will always be executed */
}

Instead, it would be a lot safer to write

boolean pentiumTMcpu = Utils.isCpuAPentium();
if (pentiumTMcpu) {
/* work out incorrect salary using double */
}
.........
.........
.........
There is a technique used alot in Microsoft's C++ libraries in which they would have
written the comparison as:

boolean pentiumTMcpu = Utils.isCpuAPentium();
if (true == pentiumTMcpu) {
/* work out incorrect salary using double */
}

More would follow as and when I would read other issues. :)

No comments: