| Sign In/My Account | View Cart |
Seven Low-Cost Ways to Improve Legacy Code
Pages: 1, 2
Chapter 11 ("References in Four Flavors") of Hardcore Java illustrates a recurring problem in many Java programs, namely the creation of circular reference trees that pin objects in memory and interfere with garbage collection. The widely held misconception that a "Java developer does not have to worry about the memory of his program" has led many Java developers to create programs that require excessive amounts of resources. The extra resources consumed by objects unintentionally pinned in memory are Java's version of a memory leak.
This kind of memory leak can be avoided by the use of weak references and weak listeners. Weak references are a special kind of reference that do not block garbage collection. This allows your data objects to hold references to GUI panels in their property change listeners without blocking the garbage collection of those panels. Furthermore, it relieves the user of the data object from having to constantly manage the addition and removal of listeners, which results in code that is easier to manage. Legacy programs can be easily converted to use weak listeners. To show how these programs can be converted, consider the following legacy code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class SomeButtonClass1 {
private final Set listeners = new HashSet();
public void addActionListener(final ActionListener l) {
listeners.add(l);
}
public void removeActionListener(final ActionListener l) {
listeners.remove(l);
}
protected void fireActionPerformed(final ActionEvent event) {
for (final Iterator iter = listeners.iterator();
iter.hasNext();) {
((ActionListener)iter).actionPerformed(event);
}
}
}
This code can easily be converted to use weak listeners with a couple of minor changes:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.Map;
import java.util.WeakHashMap;
public class SomeButtonClass {
private final Map listeners = new WeakHashMap();
public void addActionListener(final ActionListener l) {
listeners.put(l, null);
}
public void removeActionListener(final ActionListener l) {
listeners.remove(l);
}
protected void fireActionPerformed(final ActionEvent event) {
for (final Iterator iter = listeners.keySet().iterator();
iter.hasNext();) {
((ActionListener)iter).actionPerformed(event);
}
}
}
After these three small changes, the listeners don't even need to bother with removing themselves, if they don't wish to. If they remove themselves, all will be OK. If they are merely garbage collected, all will still be OK. To understand how this works in more detail, I encourage you to read Chapter 11 of Hardcore Java.
|
Related Reading Hardcore Java |
Chapter 7 ("All About Constants") of Hardcore Java talks about constants in detail. One of the most important lessons you should carry out of that chapter is that using integers for option constants is a bad idea. For example, if you want to create a class that can only take a color of the rainbow as an argument to a method, using integers for each of the seven colors is the wrong approach. We show an example of such code here:
public final class RainbowColor {
public final static int RED = 0;
public final static int ORANGE = 1;
public final static int YELLOW = 2;
public final static int GREEN = 3;
public final static int BLUE = 4;
public final static int INDIGO = 5;
public final static int VIOLET = 6;
}
When using integer constants such as these, you might write the following code:
public void doSomething(final int rainbowColor) {
// ...
}
The problem here is that the user can pass you any integer. In order to make solid code, you will have to check that integer in every piece of code against the valid integers. This checking code will have to be maintained in several places. On the other hand, the use of Enums or Constant Objects relieves you of the need to check, as we see in the revised option constant class:
public final class RainbowColor {
public final static RainbowColor RED = new RainbowColor("RED");
public final static RainbowColor ORANGE = new RainbowColor("ORANGE");
public final static RainbowColor YELLOW = new RainbowColor("YELLOW");
public final static RainbowColor GREEN = new RainbowColor("GREEN");
public final static RainbowColor BLUE = new RainbowColor("BLUE");
public final static RainbowColor INDIGO = new RainbowColor("INDIGO");
public final static RainbowColor VIOLET = new RainbowColor("VIOLET");
final String name;
private RainbowColor(final String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
With the revised class, no checking is necessary during its use:
public void doSomething(final RainbowColor rainbowColor) {
// ...
}
Since the user cannot create any more instances of the RainbowColor, there is
no need to check anything. Furthermore, since comparisons of the objects are
done by instance instead of by equality, comparisons are extremely fast.
If you have access to JDK 1.5 in your coding environment, enums are the
equivalent of Constant objects, with less code needed from the developer. If you
are stuck writing for an earlier JDK (as many corporate programmers are), you
should investigate and use the Constant object pattern extensively.
These seven techniques are fairly low cost in terms of man hours, and all are cost-free in terms of equipment and software. They can all be performed by hand or with freely available software. Although they represent only the tip of the iceberg of code-quality improvement, they offer a good place to start when time is tight and quality demands are high. Given the tools at the disposal of software engineers, there should be no excuse for writing code that is anything other than solid as stone. This will allow you to concentrate less on finding little annoying typos and more on the business your customers or employers use to make money. They will be happier with your code, and you will have to work less to accomplish the same tasks.
Robert Simmons, Jr. lives and works as a senior software architect in Germany. He is the author of O'Reilly's Hardcore Java.
O'Reilly Media recently released Hardcore Java.
Chapter 2, "The Final Story," is available for free online.
You can also look at the Table of Contents, the Index, and the full description of the book.
For more information, or to order the book, click here.
Return to ONJava.com.
Showing messages 1 through 39 of 39.
Re: 5: Removing Anonymous Inner ClassesHowever, the fact that anonymous classes can't be reused at all generally makes using them a bad idea. In addition, anonymous classes make code harder to read and bloat up the class declaration space of your program.
I'm not sure that it is always a good idea to remove inner classes. Most of my uses of anonymous inner classes are one- to three-line listeners (e.g., in a GUI). Having the handler declared in the same place as the GUI controls that use them makes the code overall more readable than having to go hunting off someplace for it. And having each GUI control's action handler in its own class avoids having a single, large, unmaintainble handler with a separate "if" clause for each of the 35 GUI controls you remembered (not to mention the two you forgot about :-) ). That style of coding is why they deprecated the 1.0 handleEvent() method, after all.
But yes, there are times when inner classes make things worse, rather than better. I prefer to avoid blanket statements like "never use ..." or "always use ...", and simply keep this as one technique among many for writing better code.
myClass.addFooListener(new FooListener() {
public void fooHappened() {
reactToFoo();
}
});
java have a check to make sure that you use Checkstyle on your code nor doesjava enforce this on all users of your classes. Adding finals to your code ensures that your code works no matter who how it is built.
readObject(ObjectOutputStream os), then all of the member variables that I will be setting in this method must be non-final. Do you have any suggestinos about how to have final methods in this case (without using readResolve)?
import java.io.Serializable;
/**
* "Typesafe enum" for the different document indicators associated with
* a transaction.
*
* Copyright 2003 Southwest Airlines
*/
public final class DocumentIndicator implements Serializable, Comparable
{
private static int nextOrdinal = 0;
private int ordinal;
private transient String name;
public static final DocumentIndicator SALES =
new DocumentIndicator("NA");
public static final DocumentIndicator SALES_EXCHANGES =
new DocumentIndicator("NE");
public static final DocumentIndicator POSITIVE_ADJUSTMENTS =
new DocumentIndicator("NY");
public static final DocumentIndicator TICKET_BY_MAIL_SALES =
new DocumentIndicator("TA");
public static final DocumentIndicator REFUNDS =
new DocumentIndicator("NR");
public static final DocumentIndicator NEGATIVE_ADJUSTMENTS =
new DocumentIndicator("NX");
public static final DocumentIndicator TICKET_BY_MAIL_REFUNDS =
new DocumentIndicator("TR");
public static final DocumentIndicator OLD_REFUNDS =
new DocumentIndicator("RF");
private static final DocumentIndicator[] PRIVATE_VALUES =
new DocumentIndicator[]
{
SALES, SALES_EXCHANGES, POSITIVE_ADJUSTMENTS, TICKET_BY_MAIL_SALES,
REFUNDS, NEGATIVE_ADJUSTMENTS, TICKET_BY_MAIL_REFUNDS, OLD_REFUNDS
};
/**
* All instances are controlled by the class.
*/
private DocumentIndicator(String name)
{
this.name = name;
this.ordinal = nextOrdinal++;
}
public int compareTo(Object o)
{
DocumentIndicator other = (DocumentIndicator) o;
return name.compareTo(other.name);
}
/**
* Returns the DocumentIndicator associated with the given string.
*
* @param indicator the String to try to match against the document
* indicators
* @return the DocumentIndicator associated with the given String
*/
public static DocumentIndicator getIndicatorFrom(String indicator)
{
if ("NA".equals(indicator))
{
return SALES;
}
else if ("NE".equals(indicator))
{
return SALES_EXCHANGES;
}
else if ("NY".equals(indicator))
{
return POSITIVE_ADJUSTMENTS;
}
else if ("TA".equals(indicator))
{
return TICKET_BY_MAIL_SALES;
}
else if ("NR".equals(indicator))
{
return REFUNDS;
}
else if ("NX".equals(indicator))
{
return NEGATIVE_ADJUSTMENTS;
}
else if ("TR".equals(indicator))
{
return TICKET_BY_MAIL_REFUNDS;
}
else if ("RF".equals(indicator))
{
return OLD_REFUNDS;
}
else
{
return null;
}
}
private Object readResolve() throws java.io.ObjectStreamException
{
return PRIVATE_VALUES[ordinal];
}
/**
* Returns a String that represents the value of this object.
*
* @return a string representation of the receiver
*/
public String toString()
{
return name;
}
}
But that's not really what this post is about. While I agree with the use of enums if you have the ability to use 1.5, the example of a "Constant Object" could cause problems for an unsuspecting developer. If any of the instances of the Rainbow class you give are serialized and then deserialized, they will create new instances of the class that are not referenced by the class members.
If you are going to provide this example as a way to avoid bugs you need to mention that a good bit of extra work is required to make it serialize and deserialize properly. The example you give will likely introduce new bugs if used with serialization.