JMU
Chained Mutators
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu


Motivation
Motivation (cont.)
Motivation (cont.)
Review
Review (cont.)
Thinking About the Problem
The Pattern
An Example

A Robot Class with Mutators that Change its Location

javaexamples/programmingpatterns/chainedmutators/Robot.java
/**
 * A simple encapsulation of a Robot that demonstrates
 * how mutators can support invocation chaining.
 *
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0
 */
public class Robot {
    private int x, y;

    /**
     * Default Constructor.
     */
    public Robot() {
        x = 0;
        y = 0;
    }
    
    /**
     * Move backward one unit.
     *
     * @return A reference to this Robot (so invocations can be chained)
     */
    public Robot moveBackward() {
        y--;
        return this;
    }
    
    /**
     * Move to forward one unit.
     *
     * @return A reference to this Robot (so invocations can be chained)
     */
    public Robot moveForward() {
        y++;
        return this;
    }
    
    /**
     * Move to the left one unit.
     *
     * @return A reference to this Robot (so invocations can be chained)
     */
    public Robot moveLeft() {
        x--;
        return this;
    }
    
    /**
     * Move to the right one unit.
     *
     * @return A reference to this Robot (so invocations can be chained)
     */
    public Robot moveRight() {
        x++;
        return this;
    }

    /**
     * Return a String representation of this Robot.
     *
     * @return  The String representation
     */
    public String toString() {
        return String.format("I am at (%d, %d).", x, y);
    }
}

        
An Example (cont.)

Using a Robot Object

javaexamples/programmingpatterns/chainedmutators/InvocationChaining.java (Fragment: robotchained)
        Robot bender = new Robot();
        bender.moveForward().moveForward().moveRight().moveForward();
        
A Warning