|
Chained Mutators
A Programming Pattern |
|
Prof. David Bernstein |
| Computer Science Department |
| bernstdh@jmu.edu |
File object that
encapsulates the current working directory and you want to
know how many characters are in its name File cwd = new File(".");
String path = cwd.getCanonicalPath();
int length = path.length();
File cwd = new File(".");
int length = cwd.getCanonicalPath().length();
getCanonicalPath() returns
(and evaluates to) a String object that has a
length() methodappend() method is a mutator?
Robot Class with Mutators that Change its Location/**
* 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);
}
}
String methods
(like toLowerCase()) return
a String object. Why? Are String
objects mutable?StringBuilder methods (like
append()) return a StringBuilder
object. Why? Are StringBuilder objects mutable?