Tuesday, 15 February 2011

Self-encapsulate fields

Within the implementation of a class, it is common to refer directly to private fields. There is another style, in which all internal references to fields are indirect, and proceed through the appropriate get and set methods. This is called self-encapsulation.
Self-encapsulation :
  • is needed for lazy initialization
  • is slightly more difficult to read than direct field access
  • can establish a synchronization policy for the field
  • allows subclasses to override the get and set methods, and provide their own definition of how fields behave
Example
public final class Infant {

public Infant (final String aName, final int aWeight, final String aMood ){
setName( aName );
setWeight( aWeight );
setMood( aMood );
}

public void becomeHungry() {
//instead of fMood = "Cranky", use:
setMood("Cranky");
}

public String toString() {
//use get methods instead of direct access
final StringBuilder result = new StringBuilder();
result.append("Infant - Name: + ");
result.append( getName() );
result.append(" Weight: ");
result.append( getWeight() );
result.append(" Mood: ");
result.append( getMood() );
return result.toString();
}

public String getName() {
return fName;
}
public void setName( String aName ){
fName = aName;
}

public int getWeight() {
return fWeight;
}
public void setWeight( final int aWeight ){
fWeight = aWeight;
}

public String getMood() {
return fMood;
}
public void setMood( final String aMood ){
fMood = aMood;
}

//..other methods elided

// PRIVATE ////
private String fName;
private int fWeight;
private String fMood;
}

Lazy initialization

Lazy initialization is a performance optimization. It's used when data is deemed to be 'expensive' for some reason. For example:

  • if the hashCode value for an object might not actually be needed by its caller, always calculating the hashCode for all instances of the object may be felt to be unnecessary.
  • since accessing a file system or network is relatively slow, such operations should be put off until they are absolutely required.
Lazy initialization has two objectives :
  • delay an expensive operation until it's absolutely necessary
  • store the result of that expensive operation, such that you won't need to repeat it again
As usual, the size of any performance gain, if any, is highly dependent on the problem, and in many cases may not be significant. As with any optimization, this technique should be used only if there is a clear and significant benefit.
To avoid a NullPointerException, a class must self-encapsulate fields that have lazy initialization. That is, a class cannot refer directly to such fields, but must access them through a method.
The hashCode method of an immutable Model Object is a common candidate for lazy initialization.
Example 1
In this example, there are two fields with lazy initialization - fHashCode and fAwards.
import java.util.*;
public final class Athlete {
public Athlete(int aId){
//a toy implementation:
fId = aId;
fName = "Roger Bannister";
//fAwards is not set here!
}
//..elided
/**
Lazy initialization is used here; this assumes that awards
may not always be of interest to the caller,
and that for some reason it is particularly expensive to
fetch the List of Awards.
*/
public List getAwards(){
if ( fAwards == null ) {
//the fAwards field has not yet been populated
//Here is a toy implementation
List<String> awards = new ArrayList<String>();
awards.add( "Gold Medal 2006" );
awards.add( "Bronze Medal 1998" );
fAwards = awards;
}
return fAwards;
}
/**
This style applies only if the object is immutable.
Another alternative is to calculate the hashCode once, when the 
object is initially constructed (again, applies only when object is 
immutable).
*/
@Override public int hashCode(){
if ( fHashCode == 0 ) {
fHashCode = HashCodeUtil.SEED;
fHashCode = HashCodeUtil.hash(fHashCode, fId);
fHashCode = HashCodeUtil.hash(fHashCode, fName);
//self-encapusulated: fAwards is not referenced directly, 
//since it may be null:
fHashCode = HashCodeUtil.hash(fHashCode, getAwards());
}
return fHashCode;
}
// PRIVATE //
private int fId;
private String fName;
private List<String> fAwards;
private int fHashCode;//Cache the hashcode inside the class
} 
Example 2
Here, the look up of the printers available to a desktop PC is treated as an expensive operation.
import java.util.Arrays;
import java.util.List;
import javax.print.DocFlavor;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.OrientationRequested;
import javax.print.attribute.standard.Sides;
/** Printing services available to a desktop client. */
public final class Printers {
/** Print some plain text (perhaps internally converted to PDF). */
void printSomething(String aText, PrintService aPrinter) {
//...elided
}
/** Return the list of printers that can print PDFs (double-sided, portrait).*/
List<PrintService> listAvailablePrinters(){
if(fAvailablePrinters == null){
//double-sided, portrait, for PDF files.
PrintRequestAttributeSet attrs = new HashPrintRequestAttributeSet();
attrs.add(Sides.DUPLEX);
attrs.add(OrientationRequested.PORTRAIT);
//Expensive operation! This can take several seconds in some environments:
fAvailablePrinters = Arrays.asList(
PrintServiceLookup.lookupPrintServices(DocFlavor.INPUT_STREAM.PDF, attrs)
);
}
return fAvailablePrinters;
}
// PRIVATE
/**
Looked up once, the first time it's needed, and then stored using a 
static reference. If it was a non-static reference, then 
the list of available printers would not be looked up just once, 
but perhaps many times (once per 'Printers' object, and not once per 
loaded 'Printers' class).
Self-encapsulate :
If this class's implementation needs to reference this item, it must do 
so indirectly, by calling listAvailablePrinters().  
*/
private static List<PrintService> fAvailablePrinters;
}  
Example 3 Lazy initialization is particularly useful for GUIs which take a long time to construct.
There are several policies for GUI construction which a design may follow:
  • always build - construct the window many times, whenever it is demanded, and do not cache the result.
  • first-request build - construct the window once, when first requested. Cache the result for any further requests, should they occur.
  • background build - construct the window once, in a low priority worker thread, when the system is initialized. Cache the result for any requests, should they occur.
Here is an example of the first-request style, in which the fEditor field has lazy initialization (see the actionPerformed method).
package hirondelle.stocks.preferences;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.util.logging.*;
import hirondelle.stocks.util.Args;
import hirondelle.stocks.util.ui.StandardEditor;
import hirondelle.stocks.util.ui.UiUtil;
import hirondelle.stocks.preferences.PreferencesEditor;
import hirondelle.stocks.util.Util;
/**
* Present dialog to allow update of user preferences.
*
* <P>Related preferences are grouped together and placed in 
* a single pane of a <tt>JTabbedPane</tt>, which corresponds to an 
* implementation of {@link PreferencesEditor}. Values are pre-populated with 
* current values for preferences.
*
*<P>Most preferences have default values. If so, a  
* <tt>Restore Defaults</tt> button is provided for that set of related 
* preferences.
*
*<P>Preferences are not changed until the <tt>OK</tt> button is pressed. 
* Exception: the logging preferences take effect immediately, without the need 
* for hitting <tt>OK</tt>.
*/
public final class EditUserPreferencesAction extends AbstractAction {
/**
* Constructor.
*  
* @param aFrame parent window to which this dialog is attached.
* @param aPrefEditors contains implementations of {@link PreferencesEditor}, 
* each of which is placed in a pane of a <tt>JTabbedPane</tt>.
*/
public EditUserPreferencesAction (JFrame aFrame, List<PreferencesEditor> aPrefEditors) {
super("Preferences...", UiUtil.getEmptyIcon()); 
Args.checkForNull(aFrame);
Args.checkForNull(aPrefEditors);
fFrame = aFrame;
putValue(SHORT_DESCRIPTION, "Update user preferences");
putValue(LONG_DESCRIPTION, "Allows user input of preferences.");
putValue(MNEMONIC_KEY, new Integer(KeyEvent.VK_P) );    
fPrefEditors = aPrefEditors;
}
/** Display the user preferences dialog.  */
public void actionPerformed(ActionEvent event) {
fLogger.info("Showing user preferences dialog.");
//lazy construction: fEditor is created only once, when this action 
//is explicitly invoked
if ( fEditor == null ) {
fEditor = new Editor("Edit Preferences", fFrame);
}
fEditor.showDialog();
}
// PRIVATE //
private JFrame fFrame;
private java.util.List<PreferencesEditor> fPrefEditors;
private static final Logger fLogger = Util.getLogger(EditUserPreferencesAction.class);  
/**
* Specifying this as a field allows for "lazy" creation and use of the GUI, which is 
* of particular importance for a preferences dialog, since they are usually heavyweight, 
* and have a large number of components.
*/
private Editor fEditor;
/**
* Return GUI for editing all preferences, pre-populated with current 
* values.
*/
private JComponent getPrefEditors(){
JTabbedPane content = new JTabbedPane();
content.setTabPlacement(JTabbedPane.LEFT);
int idx = 0;
for(PreferencesEditor prefEditor: fPrefEditors) {
JComponent editorGui = prefEditor.getUI();
editorGui.setBorder(UiUtil.getStandardBorder());
content.addTab(prefEditor.getTitle() , editorGui);
content.setMnemonicAt(idx, prefEditor.getMnemonic());
++idx;
}
return content;
}
/** Called only when the user hits the OK button.  */
private void saveSettings(){
fLogger.fine("User selected OK. Updating table preferences.");
for(PreferencesEditor prefEditor: fPrefEditors) {
prefEditor.savePreferences();
}
}
/**
* An example of a nested class which is nested because it is attached only 
* to the enclosing class, and it cannot act as superclass since multiple 
* inheritance of implementation is not possible. 
* 
* The implementation of this nested class is kept short by calling methods 
* of the enclosing class.
*/
private final class Editor extends StandardEditor { 
Editor(String aTitle, JFrame aParent){
super(aTitle, aParent, StandardEditor.CloseAction.HIDE);
}
public JComponent getEditorUI () {
JPanel content = new JPanel();
content.setLayout( new BoxLayout(content, BoxLayout.Y_AXIS) );
content.add( getPrefEditors() );
//content.setMinimumSize(new Dimension(300,300) );
return content;
}
public void okAction() {
saveSettings();
dispose();
}
}  
}

Monday, 7 February 2011

Measuring time taken by the program in java

long startTime = System.currentTimeMillis();

for (int i=0; i<1000; i++) {

methodUnderTest();

}

System.out.println("Avg. method execution time=" +

((System.currentTimeMillis() - startTime)/1000));

Wednesday, 2 February 2011

Finding the logarithm of any base in Java

Unfortunately, the only methods in Java that compute the logarithm of a number are java.lang.Math.log and java.lang.Math.log10. The former returns the natural logarithm (base e) of the number and the latter returns the base 10 logarithm of the number.

To calculate the logarithm of any base in Java, we thus have to use the following method:


  1. public double logOfBase(int base, int num) {  
  2.     return Math.log(num) / Math.log(base);  
  3. }  

Why does it work?


Let's say we want to find the base 2 logarithm of 32 (method call would be logOfBase(2, 32)), which is 5.


Now if we divide the base e logarithm (ln) of our number (32) by the base e logarithm of our base (2), we get the answer we wanted:

What is iterator?

The point of using an iterator is to allow the the client to iterate over the collection of objects, without exposing implementation details. This gives you the benefit to change what collection the Iterator iterates over and how each element is served, without making any change the client's code.


Making custom collections iterable

Let's say we have our own custom Vector-based collection, GameCollection, that stores Games and we want to make this collection iterable (over its stored Games) by making it implement the Iterator inteface:


  1. public class GameCollection implements Iterable<Game> {  
  2.  private Vector<Game> games;  
  3.    
  4.  public GameCollection() {  
  5.   games = new Vector<Game>();  
  6.  }  
  7.    
  8.  public void add(Game game) {  
  9.   games.add(game);  
  10.  }  
  11.   
  12.  @Override  
  13.  public Iterator<Game> iterator() {  
  14.   return games.iterator();  
  15.  }  
  16. }  

The client can then use the above collection as follows:


  1. GameCollection gc = new GameCollection();  
  2. Iterator<game> gameIterator = gc.iterator();  
  3.   
  4. while (gameIterator.hasNext()) {  
  5.  Game g = gameIterator.next();  
  6.  System.out.println(g.getName());  
  7. }  

Or better yet, make use of Java's for-each statement:


  1. GameCollection gc = new GameCollection();  
  2. for (Game g : gc) {  
  3.  System.out.println(g.getName());  
  4. }  

As you can see from the above code, the client doesn't know that we are using a Vector to store our Games in the GameCollection. Infact, we can later change the GameCollection to store the Games in a LinkedList or an Array, and yet the client wouldn't need to change his iteration code (code above) to suit for our changes.

Multiple iterators for a custom collection

What if we now want our GameCollection to offer two iterable solutions? Say we want our GameCollection to iterate over both Games and also GameConsoles?

The first thing that comes to mind is to try and make the GameCollection implement two Iterator interfaces using different generic arguments:


  1. public class GameCollection implements Iterable<Game>, Iterable<GameConsole>  

but unfortunately, the above doesn't compile. Therefore, as a workaround to such an issue, we can make use of Java's ability to allow for inner classes:


  1. public class GameCollection  {  
  2.  private Vector<Game> games;  
  3.  private Vector<GameConsole> consoles;  
  4.    
  5.  private class Games implements Iterable<Game> {  
  6.   @Override  
  7.   public Iterator<Game> iterator() {  
  8.    return games.iterator();  
  9.   }  
  10.  }  
  11.    
  12.  private class Consoles implements Iterable<GameConsole> {  
  13.   @Override  
  14.   public Iterator<GameConsole> iterator() {  
  15.    return consoles.iterator();  
  16.   }  
  17.     
  18.  }  
  19.    
  20.  public GameCollection() {  
  21.   games = new Vector<Game>();  
  22.   consoles = new Vector<GameConsole>();  
  23.  }  
  24.    
  25.  public void add(Game game) {  
  26.   games.add(game);  
  27.  }  
  28.    
  29.  public void add(GameConsole console) {  
  30.   consoles.add(console);  
  31.  }  
  32.   
  33.  public Games games() {  
  34.   return new Games();  
  35.  }  
  36.    
  37.  public Consoles consoles() {  
  38.   return new Consoles();  
  39.  }  
  40. }  

With the above two inner classes and the public methods games() and consoles(), the client can iterate over the collections like such:


  1. GameCollection gc = new GameCollection();  
  2.   
  3. //Add games and consoles with gc.add()  
  4.   
  5. for (Game g : gc.games()) {  
  6.  System.out.println(g.getName());  
  7. }  
  8.   
  9. for (GameConsole g : gc.consoles()) {  
  10.  System.out.println(g.getName());  
  11. }  

Creating custom iterators

Up till this point, we have only used iterators that are in built with Java's existing collections; but what if we want our own custom iterator? We can use Java's java.util.Iterator interface to build our own iterator.

In the following example, I have created a Circular Iterator:
  1. public class CircularGamesIterator implements Iterator<Game> {  
  2.   
  3.  private Vector<Game> list;  
  4.  private int currentPosition;  
  5.    
  6.  public CircularGamesIterator(Vector<Game> games) {  
  7.   list = games;  
  8.   currentPosition = 0;  
  9.  }  
  10.    
  11.  @Override  
  12.  public boolean hasNext() {  
  13.   return currentPosition < list.size();  
  14.  }  
  15.   
  16.  @Override  
  17.  public Game next() {  
  18.   Game el = list.elementAt(currentPosition);  
  19.   currentPosition = (currentPosition + 1) % list.size();   
  20.   return el;  
  21.  }  
  22.   
  23.  @Override  
  24.  public void remove() { }  
  25. }  


The iterator() method of the GameCollection class can then be modified to return an instance of the CircularGamesIterator:


  1. public class GameCollection implements Iterable<Game> {  
  2.  private Vector<Game> games;  
  3.    
  4.  public GameCollection() {  
  5.   games = new Vector<Game>();  
  6.  }  
  7.    
  8.  public void add(Game game) {  
  9.   games.add(game);  
  10.  }  
  11.   
  12.  @Override  
  13.  public Iterator<Game> iterator() {  
  14.   return new CircularGamesIterator(games);  
  15.  }  
  16. }  

An Iterator should not be Iterable!

I have seen some examples on the internet where people make Iterators iterable by making their Iterators implement the Iterator interface and returning this in the iterator() method:
I have removed the implementation in the methods for the following code for brevity.
  1. public class CustomIterator implements Iterator<Game>, Iterable<Game> {  
  2.   
  3.  public CustomIterator(Vector<Game> games) {  
  4.   list = games;  
  5.  }  
  6.   
  7.  @Override  
  8.  public Iterator<Game> iterator() {  
  9.   return this;  
  10.  }  
  11.   
  12.  @Override  
  13.  public boolean hasNext() {  
  14.    //Implementation  
  15.  }  
  16.   
  17.  @Override  
  18.  public Game next() {  
  19.    //Implementation  
  20.  }  
  21.   
  22.  @Override  
  23.  public void remove() { }  
  24. }  


The problem with the above code can be clearly illustrated with such a method:


  1. public static void iterateTwice(Iterable<Game> games) {  
  2.  for (Game g : games) {  
  3.   System.out.println(g.getName());  
  4.  }  
  5.    
  6.  for (Game g : games) {  
  7.   System.out.println(g.getName());  
  8.  }  
  9.  System.out.println();  
  10. }  

If you directly pass in your iterable iterator to the above method, the Games will only be printed once.

To illustrate this, let's assume that we will use the custom iterator mentioned above, CustomIterator, that implements both Iterator<Game> and Iterable<Game>. Our GameCollection implements Iterable<Game>, and its iterator() method returns new CustomIterator(games);. Now, let's also say that GameCollection also provides a method games() that also returns new CustomIterator(games);.

Here's an example that illustrates this:

  1. GameCollection gc = new GameCollection();  
  2.   
  3. gc.add(new Game("Broken Sword"));  
  4. gc.add(new Game("Grim Fandango"));  
  5. gc.add(new Game("Manic Mansion"));  
  6.   
  7. System.out.println("Printing the iterable collection, GameCollection");  
  8. iterateTwice(gc);  
  9.   
  10. System.out.println("Printing the iterable iterator, CustomIterator");  
  11. CustomIterator gamesIterator = gc.games();  
  12. iterateTwice(gamesIterator);  

The output of the above code is as follows:
Printing the iterable collection, GameCollection
Broken Sword
Grim Fandango
Manic Mansion
Broken Sword
Grim Fandango
Manic Mansion

Printing the iterable iterator, CustomIterator
Broken Sword
Grim Fandango
Manic Mansion

Notice how when passing the iterable CustomIterator iterator to the method, the Games were only printed once, whereas when we passed in the GameCollection that implements Iterable, the Games were printed twice.

This is because when CustomIterator was passed in, the second for loop terminated immediately.

Tuesday, 1 February 2011

Composition vs Inheritance

The composition alternative
Given that the inheritance relationship makes it hard to change the interface of a superclass, it is worth looking at an alternative approach provided by composition. It turns out that when your goal is code reuse, composition provides an approach that yields easier-to-change code.
Code reuse via inheritance
For an illustration of how inheritance compares to composition in the code reuse department, consider this very simple example:

class Fruit {

// Return int number of pieces of peel that
// resulted from the peeling activity.
public int peel() {

System.out.println("Peeling is appealing.");
return 1;
}
}

class Apple extends Fruit {
}

class Example1 {

public static void main(String[] args) {

Apple apple = new Apple();
int pieces = apple.peel();
}
}
When you run the Example1 application, it will print out "Peeling is appealing.", because Apple inherits (reuses) Fruit's implementation of peel(). If at some point in the future, however, you wish to change the return value of peel() to type Peel, you will break the code for Example1. Your change to Fruit breaks Example1's code even though Example1 uses Apple directly and never explicitly mentions Fruit.
Here's what that would look like:

class Peel {

private int peelCount;

public Peel(int peelCount) {
this.peelCount = peelCount;
}

public int getPeelCount() {

return peelCount;
}
//...
}

class Fruit {

// Return a Peel object that
// results from the peeling activity.
public Peel peel() {

System.out.println("Peeling is appealing.");
return new Peel(1);
}
}

// Apple still compiles and works fine
class Apple extends Fruit {
}

// This old implementation of Example1
// is broken and won't compile.
class Example1 {

public static void main(String[] args) {

Apple apple = new Apple();
int pieces = apple.peel();
}
}
Code reuse via composition
Composition provides an alternative way for Apple to reuse Fruit's implementation of peel(). Instead of extending Fruit, Apple can hold a reference to a Fruit instance and define its own peel() method that simply invokes peel() on the Fruit. Here's the code:

class Fruit {

// Return int number of pieces of peel that
// resulted from the peeling activity.
public int peel() {

System.out.println("Peeling is appealing.");
return 1;
}
}

class Apple {

private Fruit fruit = new Fruit();

public int peel() {
return fruit.peel();
}
}

class Example2 {

public static void main(String[] args) {

Apple apple = new Apple();
int pieces = apple.peel();
}
}
In the composition approach, the subclass becomes the "front-end class," and the superclass becomes the "back-end class." With inheritance, a subclass automatically inherits an implemenation of any non-private superclass method that it doesn't override. With composition, by contrast, the front-end class must explicitly invoke a corresponding method in the back-end class from its own implementation of the method. This explicit call is sometimes called "forwarding" or "delegating" the method invocation to the back-end object.
The composition approach to code reuse provides stronger encapsulation than inheritance, because a change to a back-end class needn't break any code that relies only on the front-end class. For example, changing the return type of Fruit's peel() method from the previous example doesn't force a change in Apple's interface and therefore needn't break Example2's code.
Here's how the changed code would look:

class Peel {

private int peelCount;

public Peel(int peelCount) {
this.peelCount = peelCount;
}

public int getPeelCount() {

return peelCount;
}
//...
}

class Fruit {

// Return int number of pieces of peel that
// resulted from the peeling activity.
public Peel peel() {

System.out.println("Peeling is appealing.");
return new Peel(1);
}
}

// Apple must be changed to accomodate
// the change to Fruit
class Apple {

private Fruit fruit = new Fruit();

public int peel() {

Peel peel = fruit.peel();
return peel.getPeelCount();
}
}

// This old implementation of Example2
// still works fine.
class Example1 {

public static void main(String[] args) {

Apple apple = new Apple();
int pieces = apple.peel();
}
}
This example illustrates that the ripple effect caused by changing a back-end class stops (or at least can stop) at the front-end class. Although Apple's peel() method had to be updated to accommodate the change to Fruit, Example2 required no changes.

Composition vs Inheritance 2

Dynamic binding, polymorphism, and change
When you establish an inheritance relationship between two classes, you get to take advantage of dynamic binding and polymorphism. Dynamic binding means the JVM will decide at runtime which method implementation to invoke based on the class of the object. Polymorphism means you can use a variable of a superclass type to hold a reference to an object whose class is the superclass or any of its subclasses.
One of the prime benefits of dynamic binding and polymorphism is that they can help make code easier to change. If you have a fragment of code that uses a variable of a superclass type, such as Fruit, you could later create a brand new subclass, such as Banana, and the old code fragment will work without change with instances of the new subclass. If Banana overrides any of Fruit's methods that are invoked by the code fragment, dynamic binding will ensure that Banana's implementation of those methods gets executed. This will be true even though class Banana didn't exist when the code fragment was written and compiled.
Thus, inheritance helps make code easier to change if the needed change involves adding a new subclass. This, however, is not the only kind of change you may need to make.
Changing the superclass interface
In an inheritance relationship, superclasses are often said to be "fragile," because one little change to a superclass can ripple out and require changes in many other places in the application's code. To be more specific, what is actually fragile about a superclass is its interface. If the superclass is well-designed, with a clean separation of interface and implementation in the object-oriented style, any changes to the superclass's implementation shouldn't ripple at all. Changes to the superclass's interface, however, can ripple out and break any code that uses the superclass or any of its subclasses. What's more, a change in the superclass interface can break the code that defines any of its subclasses.
For example, if you change the return type of a public method in class Fruit (a part of Fruit's interface), you can break the code that invokes that method on any reference of type Fruit or any subclass of Fruit. In addition, you break the code that defines any subclass of Fruit that overrides the method. Such subclasses won't compile until you go and change the return value of the overridden method to match the changed method in superclass Fruit.
Inheritance is also sometimes said to provide "weak encapsulation," because if you have code that directly uses a subclass, such as Apple, that code can be broken by changes to a superclass, such as Fruit. One of the ways to look at inheritance is that it allows subclass code to reuse superclass code. For example, if Apple doesn't override a method defined in its superclass Fruit, Apple is in a sense reusing Fruit's implementation of the method. But Apple only "weakly encapsulates" the Fruit code it is reusing, because changes to Fruit's interface can break code that directly uses Apple.