- Forward


Chained Mutators
A Programming Pattern


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • A Common Situation:
    • A method is invoked on the value returned by another method, without assigning the returned value to an intermediate variable
  • The Idea:
    • You should consider this when writing methods
Motivation (cont.)
Back SMYC Forward
  • An Example:
    • You need to construct an email address
  • One Implementation:
    • javaexamples/programmingpatterns/chainedmutators/InvocationChaining.java (Fragment: sbintermediate)
       
Motivation (cont.)
Back SMYC Forward
  • An Observation:
    • This is messier than String concatenation
  • Using Invocation Chaining:
    • javaexamples/programmingpatterns/chainedmutators/InvocationChaining.java (Fragment: sbchain)
       
Review
Back SMYC Forward
  • A Related Example:
    • You are working with a File object that encapsulates the current working directory and you want to know how many characters are in its name
  • One Solution:
    • javaexamples/programmingpatterns/chainedmutators/InvocationChaining.java (Fragment: intermediate)
       
Review (cont.)
Back SMYC Forward
  • An Observation:
    • There's no need for the intermediate variable
  • Using Invocation Chaining:
    • javaexamples/programmingpatterns/chainedmutators/InvocationChaining.java (Fragment: chain)
       
  • Why It Works:
    • getCanonicalPath() returns (and evaluates to) a String object that has a length() method
Thinking About the Problem
Back SMYC Forward
  • An Important Difference in the Two Examples:
    • In the path example, the methods do not change the state of their owning objects (i.e., they are accessors not mutators)
  • A Question?
    • Why can you use invocation chaining in the email example given that the append() method is a mutator?
The Pattern
Back SMYC Forward
  • The Idea:
    • Mutators that are to be chained need to return something that a subsequent method can be invoked on
  • Specifically:
    • It must return the owning object
An Example
Back SMYC Forward

A Robot Class with Mutators that Change its Location

javaexamples/programmingpatterns/chainedmutators/Robot.java
 
An Example (cont.)
Back SMYC Forward

Using a Robot Object

javaexamples/programmingpatterns/chainedmutators/InvocationChaining.java (Fragment: robotchained)
 
A Warning
Back SMYC Forward
  • The Issue:
    • Documentation is especially important here!
  • A Quiz:
    • Some String methods (like toLowerCase()) return a String object. Why? Are String objects mutable?
    • Some StringBuilder methods (like append()) return a StringBuilder object. Why? Are StringBuilder objects mutable?
There's Always More to Learn
Back -