Docsity

Aliasing and Immutability: Understanding Accessors, Mutators, and Defensive Copies in Java, Study notes of Engineering

Toggle sidebar
bg1
1
Computer Science and Engineering College of Engineering The Ohio State University
Aliasing and Immutability
Lecture 8
Computer Science and Engineering The Ohio State University
Vocabulary: Accessors & Mutators
Accessor:
A method that reads, but never changes, the
(abstract) state of an object
Concrete representation may change, so long as
change is not visible to client
eg Lazy initialization
Examples: getter methods toString
Examples: getter methods
,
toString
Formally: restores “this”
Mutator method:
A method that may change the (abstract) state of
an object
Examples: setter methods
Formally: updates “this”
Constructors not considered mutators
Computer Science and Engineering The Ohio State University
A Fixed Epoch Interface
// Interface cover story goes here
// Mathematical modeling …
// constructor
// requires start date < end date
// initializes start and end dates
// operations have specifications based on the model
// exercises …
public interface FixedEpoch {
public Date getStart();
public Date getEnd();
}
Computer Science and Engineering The Ohio State University
A Broken Time Period Class
public class Period implements FixedEpoch {
private Date start;
private Date end;
public Period(Date start, Date end) {
this.start = start;
t
hi
s.e
n
d
=
e
n
d;
t s.e d e d;
}
public Date getStart() {
return start;
}
public Date getEnd() {
return end;
}
}
Computer Science and Engineering The Ohio State University
Problem: Aliasing
Assignment in constructor creates an alias
Client and component both have references to the
same Date object
Class invariant can be undermined via alias
Date t1 = new Date(300);
Date t2 = new Date (500);
Period p = new Period (t1, t2);
t2.setTime(100); //modifies p’s rep
Solution: “defensive copying”
Constructor creates a copy of the arguments
Copy is used to initialize the private fields
Metaphor: ownership
Computer Science and Engineering The Ohio State University
A Better Period Class
public class Period implements FixedEpoch {
private Date start;
private Date end;
public Period(Date start, Date end) {
this.start = new Date(start.getTime());
t
hi
s.e
n
d
=
ne
w D
ate
(e
n
d.get
Tim
e());
t s.e d
e ate
(e d.get e());
}
public Date getStart() {
return start;
}
public Date getEnd() {
return end;
}
}
pf3
pf4

Partial preview of the text

Download Aliasing and Immutability: Understanding Accessors, Mutators, and Defensive Copies in Java and more Study notes Engineering in PDF only on Docsity!

Computer Science and Engineering „ College of Engineering „ The Ohio State University

Aliasing and Immutability

Lecture 8

Computer Science and Engineering „ The Ohio State University

Vocabulary: Accessors & Mutators

† Accessor:

„ A method that reads, but never changes, the (abstract) state of an object † Concrete representation may change, so long as change is not visible to client † eg Lazy initialization „„ Examples: getter methodsExamples: getter methods, toString toString „ Formally: restores “this”

† Mutator method:

„ A method that may change the (abstract) state of an object „ Examples: setter methods „ Formally: updates “this” „ Constructors not considered mutators

Computer Science and Engineering „ The Ohio State University

A Fixed Epoch Interface

// Interface cover story goes here // Mathematical modeling … // constructor // requires start date < end date // initializes start and end dates // operations have specifications based on the model // exercises …

public interface FixedEpoch { public Date getStart(); public Date getEnd(); }

Computer Science and Engineering „ The Ohio State University

A Broken Time Period Class

public class Period implements FixedEpoch { private Date start; private Date end;

public Period(Date start, Date end) { this.start = start; this.end =t s.e d end;e d; }

public Date getStart() { return start; }

public Date getEnd() { return end; } }

Computer Science and Engineering „ The Ohio State University

Problem: Aliasing

† Assignment in constructor creates an alias

„ Client and component both have references to the same Date object

† Class invariant can be undermined via alias

Date t1 = new Date(300); Date t2 = new Date (500); Period p = new Period (t1, t2); t2.setTime(100); // modifies p’s rep

† Solution: “defensive copying”

„ Constructor creates a copy of the arguments „ Copy is used to initialize the private fields „ Metaphor: ownership

Computer Science and Engineering „ The Ohio State University

A Better Period Class

public class Period implements FixedEpoch { private Date start; private Date end;

public Period(Date start, Date end) { this.start = new Date(start.getTime()); this.end =t s.e d new Date(end.getTime());e ate(e d.get e()); }

public Date getStart() { return start; }

public Date getEnd() { return end; } }

Computer Science and Engineering „ The Ohio State University

Problem 2: Aliasing (Again)

† Return value in accessor creates an alias

„ Client can still obtain a reference to the class’s internal representation (the private fields) „ aka “privacy leak”, but really just an alias problem

† Class invariant can be undermined via alias

Date t1 = new Date(300); Date t2 = new Date (500); Period p = new Period (t1, t2); p.getEnd().setTime(100); // modifies p’s rep

† Solution: “defensive copying”

„ Accessors create a copy of internal fields „ Copy is returned to the client

Computer Science and Engineering „ The Ohio State University

A Better+2 Period Class

public class Period implements FixedEpoch { private Date start; private Date end;

public Period(Date start, Date end) { this.start = new Date(start.getTime()); this.end =t s.e d new Date(end.getTime());e ate(e d.get e()); }

public Date getStart() { return new Date(start.getTime()); }

public Date getEnd() { return new Date(end.getTime()); } }

Computer Science and Engineering „ The Ohio State University

Good Practice: Defensive Copies

† Always make defensive copies when

needed

„ Problem: Aliases undermine the privacy of a field „ Solution: Prevent aliases to fields

†† Typical examplesTypical examples

„ Parameters in constructors and mutators „ Return value from any method

† Note: There are some types of fields for

which aliasing is never a concern!

„ Fields that are primitive (eg int, float) „ Fields that are enumerations (eg Suit, Colors) „ Fields that are… (next slide)

Computer Science and Engineering „ The Ohio State University

Immutability

† An immutable object is one whose (abstract)

value can never change

„ Constructor allows initialization to different values „ No mutator methods

† Why would we want such a thing?y ou d a u a g

† Because aliasing an immutable is safe!

„ Having multiple references to the same immutable is indistinguishable from having multiple references to different immutables that have the same value „ Defensive copies of immutables are not required!

Computer Science and Engineering „ The Ohio State University

How to Write an Immutable Interf.

† Do not provide mutators

„ Check alters clause of all methods

Computer Science and Engineering „ The Ohio State University

How to Write an Immutable Class

† Implement an (immutable) interface

„ Result: no mutators „ You do that anyway, right?

† Make all fields private

„ You do that anyway, right?

†† Ensure exclusive access to anyEnsure exclusive access to any mutablemutable

objects referred to by fields

„ Rule: If the class has fields that refer to mutable objects

  1. Make defensive copies of parameters in constructors and mutators
  2. Make defensive copies for return values from methods „ Defensive copies not needed for fields that are primitive, enumerations, or refer to immutable objects

Computer Science and Engineering „ The Ohio State University

Summary

† Defensive copying

„ Copy constructor arguments (reference types) „ Return only copies of fields (reference types)

† Immutable interfaces and classes

„ Each instance represents a distinct valueEach instance represents a distinct value „ No mutators: no methods alter “this” † Methods can return a new instance „ Defensive copying of mutable fields

† Examples of immutables

„ String „ Wrapper classes (Integer, Long, Float…)

† Auto-boxing / auto-unboxing