Women in Technology

Hear us Roar



Article:
  Seven Low-Cost Ways to Improve Legacy Code
Subject:   using final with Serializable classes
Date:   2005-04-13 14:34:32
From:   Mith
Response to: using final with Serializable classes

Try this on for size:

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;
}
}