1/14/24, 8:01 AM SWE 619 Quiz Number 5
SWE 619 Quiz Number 5
September 27, 2023
Name: Group:
Consider the following (supposedly) immutable class:
public final class IWantToBeImmutable { // Line A
private final List<String> list; // Line B
private final String string; // Line C
public IWantToBeImmutable(String string, List<String> list) {
this.list = list; // Line D
this.string = string; // Line E
}
public List<String> getList() {
return new ArrayList<String> (list); // Line F
}
public String getString() { return string; } // Line G
}
1. Mark whether each line of code is a problem w.r.t. the immutability of class
IWantToBeImmutable.
Line A: ____ Yes ____ No
Line B: ____ Yes ____ No
Line C: ____ Yes ____ No
Line D: ____ Yes ____ No
Line E: ____ Yes ____ No
Line F: ____ Yes ____ No
Line G: ____ Yes ____ No
Answer: Line D is a problem for immutability. Other lines are not.
2. Write pseudo-code that compromises the immutability of the IWantToBeImmutable class.
Answer: We need an attack on the List object, since it is the only mutable component the
client can get access to.
https://cdn-uploads.piazza.com/paste/gxxicyrgsbf2x6/b17cc5f80a25dfb8722c74344207d63fd031539e0c8c642d020a5e075b0a99a6/quiz05.html 1/2
1/14/24, 8:01 AM SWE 619 Quiz Number 5
Here is a mutability attack enabled through the fault on line D:
List<String> list = //... supppose list is [cat, dog]
IWantToBeImmutable im = new IWantToBeImmutable("bat", list);
list.add("elephant"); // now I've changed the internal state of im
// from
// <bat, [cat, dog]>
// to
// <bat, [cat, dog, elephant]>
https://cdn-uploads.piazza.com/paste/gxxicyrgsbf2x6/b17cc5f80a25dfb8722c74344207d63fd031539e0c8c642d020a5e075b0a99a6/quiz05.html 2/2