<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@Reading_7_Objectives" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="VerticalStudentView" data-request-token="cec4e5c002f511efa5270afff417eba9">
<h2 class="hd hd-2 unit-title">Reading 7 Objectives</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_02386e5c5cbe">
<div class="xblock xblock-public_view xblock-public_view-video xmodule_display xmodule_VideoBlock" data-block-type="video" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_02386e5c5cbe" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Video"}
</script>
<h3 class="hd hd-2">Video</h3>
<div
id="video_video_02386e5c5cbe"
class="video closed"
data-metadata='{"transcriptLanguages": {"en": "English"}, "captionDataDir": null, "autoAdvance": false, "poster": null, "publishCompletionUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_02386e5c5cbe/handler/publish_completion", "transcriptLanguage": "en", "showCaptions": "true", "completionEnabled": false, "prioritizeHls": false, "sources": ["https://d2f1egay8yehza.cloudfront.net/MIT600512016-V004100_DTH.mp4", "https://d2f1egay8yehza.cloudfront.net/MIT600512016-V004100/MIT600512016-V004100.m3u8"], "transcriptAvailableTranslationsUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_02386e5c5cbe/handler/transcript/available_translations", "ytApiUrl": "https://www.youtube.com/iframe_api", "autohideHtml5": false, "start": 0.0, "generalSpeed": 1.0, "recordedYoutubeIsAvailable": true, "speed": null, "end": 0.0, "ytMetadataEndpoint": "", "savedVideoPosition": 0.0, "ytTestTimeout": 1500, "autoplay": false, "saveStateUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_02386e5c5cbe/handler/xmodule_handler/save_user_state", "saveStateEnabled": false, "transcriptTranslationUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_02386e5c5cbe/handler/transcript/translation/__lang__", "streams": "1.00:qM6SFX4C1Rs", "completionPercentage": 0.95, "duration": 24.06, "lmsRootURL": "https://openlearninglibrary.mit.edu"}'
data-bumper-metadata='null'
data-autoadvance-enabled="False"
data-poster='null'
tabindex="-1"
>
<div class="focus_grabber first"></div>
<div class="tc-wrapper">
<div class="video-wrapper">
<span tabindex="0" class="spinner" aria-hidden="false" aria-label="Loading video player"></span>
<span tabindex="-1" class="btn-play fa fa-youtube-play fa-2x is-hidden" aria-hidden="true" aria-label="Play video"></span>
<div class="video-player-pre"></div>
<div class="video-player">
<div id="video_02386e5c5cbe"></div>
<h4 class="hd hd-4 video-error is-hidden">No playable video sources found.</h4>
<h4 class="hd hd-4 video-hls-error is-hidden">
Your browser does not support this video format. Try using a different browser.
</h4>
</div>
<div class="video-player-post"></div>
<div class="closed-captions"></div>
<div class="video-controls is-hidden">
<div>
<div class="vcr"><div class="vidtime">0:00 / 0:00</div></div>
<div class="secondary-controls"></div>
</div>
</div>
</div>
</div>
<div class="focus_grabber last"></div>
<h3 class="hd hd-4 downloads-heading sr" id="video-download-transcripts_video_02386e5c5cbe">Downloads and transcripts</h3>
<div class="wrapper-downloads" role="region" aria-labelledby="video-download-transcripts_video_02386e5c5cbe">
<div class="wrapper-download-transcripts">
<h4 class="hd hd-5">Transcripts</h4>
<ul class="list-download-transcripts">
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_02386e5c5cbe/handler/transcript/download" data-value="srt">Download SubRip (.srt) file</a>
</li>
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_02386e5c5cbe/handler/transcript/download" data-value="txt">Download Text (.txt) file</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_3d3b925cd14c">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_3d3b925cd14c" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<h4>Software in 6.005</h4>
<table class="table table-striped no-markdown">
<tbody>
<tr>
<th width="33%">Safe from bugs</th>
<th>Easy to understand</th>
<th>Ready for change</th>
</tr>
<tr>
<td>
Correct today and correct in the unknown future
</td>
<td>
Communicating clearly with future programmers, including future you
</td>
<td>
Designed to accommodate change without rewriting
</td>
</tr>
</tbody>
</table>
<h4>Objectives for Today</h4>
<p>Today we’re going to talk more about the dangers of mutable data types, and the advantages of immutability.</p>
<p>After today’s reading, you should:</p>
<ul>
<li>Understand mutability and mutable objects</li>
<li>Identify aliasing and understand the dangers of mutability</li>
<li>Use immutability to improve correctness, clarity, & changeability</li>
</ul>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@Mutability" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="VerticalStudentView" data-request-token="cec4e5c002f511efa5270afff417eba9">
<h2 class="hd hd-2 unit-title">Mutability</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_78ffbac52509">
<div class="xblock xblock-public_view xblock-public_view-video xmodule_display xmodule_VideoBlock" data-block-type="video" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_78ffbac52509" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Video"}
</script>
<h3 class="hd hd-2">Video</h3>
<div
id="video_video_78ffbac52509"
class="video closed"
data-metadata='{"transcriptLanguages": {"en": "English"}, "captionDataDir": null, "autoAdvance": false, "poster": null, "publishCompletionUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_78ffbac52509/handler/publish_completion", "transcriptLanguage": "en", "showCaptions": "true", "completionEnabled": false, "prioritizeHls": false, "sources": ["https://d2f1egay8yehza.cloudfront.net/MIT600512016-V004200_DTH.mp4", "https://d2f1egay8yehza.cloudfront.net/MIT600512016-V004200/MIT600512016-V004200.m3u8"], "transcriptAvailableTranslationsUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_78ffbac52509/handler/transcript/available_translations", "ytApiUrl": "https://www.youtube.com/iframe_api", "autohideHtml5": false, "start": 0.0, "generalSpeed": 1.0, "recordedYoutubeIsAvailable": true, "speed": null, "end": 0.0, "ytMetadataEndpoint": "", "savedVideoPosition": 0.0, "ytTestTimeout": 1500, "autoplay": false, "saveStateUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_78ffbac52509/handler/xmodule_handler/save_user_state", "saveStateEnabled": false, "transcriptTranslationUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_78ffbac52509/handler/transcript/translation/__lang__", "streams": "1.00:mmqVXR76CCc", "completionPercentage": 0.95, "duration": 241.26, "lmsRootURL": "https://openlearninglibrary.mit.edu"}'
data-bumper-metadata='null'
data-autoadvance-enabled="False"
data-poster='null'
tabindex="-1"
>
<div class="focus_grabber first"></div>
<div class="tc-wrapper">
<div class="video-wrapper">
<span tabindex="0" class="spinner" aria-hidden="false" aria-label="Loading video player"></span>
<span tabindex="-1" class="btn-play fa fa-youtube-play fa-2x is-hidden" aria-hidden="true" aria-label="Play video"></span>
<div class="video-player-pre"></div>
<div class="video-player">
<div id="video_78ffbac52509"></div>
<h4 class="hd hd-4 video-error is-hidden">No playable video sources found.</h4>
<h4 class="hd hd-4 video-hls-error is-hidden">
Your browser does not support this video format. Try using a different browser.
</h4>
</div>
<div class="video-player-post"></div>
<div class="closed-captions"></div>
<div class="video-controls is-hidden">
<div>
<div class="vcr"><div class="vidtime">0:00 / 0:00</div></div>
<div class="secondary-controls"></div>
</div>
</div>
</div>
</div>
<div class="focus_grabber last"></div>
<h3 class="hd hd-4 downloads-heading sr" id="video-download-transcripts_video_78ffbac52509">Downloads and transcripts</h3>
<div class="wrapper-downloads" role="region" aria-labelledby="video-download-transcripts_video_78ffbac52509">
<div class="wrapper-download-transcripts">
<h4 class="hd hd-5">Transcripts</h4>
<ul class="list-download-transcripts">
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_78ffbac52509/handler/transcript/download" data-value="srt">Download SubRip (.srt) file</a>
</li>
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_78ffbac52509/handler/transcript/download" data-value="txt">Download Text (.txt) file</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_121b614a64e7">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_121b614a64e7" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<h2 id="mutability">Mutability</h2>
<div data-outline="mutability">
<p>Recall from <a href="/courses/course-v1:MITx+6.005.1x+3T2016/jump_to_id/vertical-mutating-values-vs-reassigning-variables#mutating_values_vs_reassigning_variables">when we discussed snapshot diagrams</a> that some objects are <em>immutable</em>: once created, they always represent the same value. Other objects are <em>mutable</em>: they have methods that change the value of the object.</p>
<p><a href="http://docs.oracle.com/javase/8/docs/api/?java/lang/String.html"><code>String</code></a> is an example of an immutable type. A <code>String</code> object always represents the same string.
<a href="http://docs.oracle.com/javase/8/docs/api/?java/lang/StringBuilder.html"><code>StringBuilder</code></a> is an example of a mutable type. It has methods to delete parts of the string, insert or replace characters, etc.</p>
<div class="panel panel-figure pull-right pull-margin"><img src="/assets/courseware/v1/2e2c4228d673d9fec24036674e5c999e/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/07-reassignment.png" alt="reassigning a variable" width="200"></div>
<p>Since <code>String</code> is immutable, once created, a <code>String</code> object always has the same value. To add something to the end of a String, you have to create a new String object:</p><pre><code class="language-java hljs">String s = <span class="hljs-string">"a"</span>;
s = s.concat(<span class="hljs-string">"b"</span>); <span class="hljs-comment">// s+="b" and s=s+"b" also mean the same thing</span></code></pre>
<div class="clearfix"></div>
<div class="panel panel-figure pull-right pull-margin"><img src="/assets/courseware/v1/c3bb51dde8aa4712756b9d2889a43a35/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/07-mutation.png" alt="mutating an object" width="200"></div>
<p>By contrast, <code>StringBuilder</code> objects are mutable. This class has methods that change the value of the object, rather than just returning new values:</p><pre><code class="language-java hljs">StringBuilder sb = <span class="hljs-keyword">new</span> StringBuilder(<span class="hljs-string">"a"</span>);
sb.append(<span class="hljs-string">"b"</span>);</code></pre>
<p><code>StringBuilder</code> has other methods as well, for deleting parts of the string, inserting in the middle, or changing individual characters.</p>
<div class="clearfix"></div>
<p>So what? In both cases, you end up with <code>s</code> and <code>sb</code> referring to the string of characters <code>"ab"</code>. The difference between mutability and immutability doesn't matter much when there's only one reference to the object. But there are big differences in how they behave when there are <em>other</em> references to the object. For example, when another variable <code>t</code> points to the same String object as <code>s</code>, and another variable <code>tb</code> points to the same StringBuilder as <code>sb</code>, then the differences between the immutable and mutable objects become more evident:</p>
<div class="panel panel-figure pull-right pull-margin"><img src="/assets/courseware/v1/0f683fa60c85eb588ffb98f24ce0c211/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/07-string-vs-stringbuilder.png" alt="different behavior of String and StringBuilder" width="500"></div><pre><code class="language-java hljs">String t = s;
t = t + <span class="hljs-string">"c"</span>;
StringBuilder tb = sb;
tb.append(<span class="hljs-string">"c"</span>);</code></pre>
<div class="clearfix"></div>
<p>This shows that changing <code>t</code> had no effect on <code>s</code>, but changing <code>tb</code> affected <code>sb</code> too -- possibly to the surprise of the programmer. That's the essence of the problem we're going to look at in this reading.</p>
<p>Since we have the immutable <code>String</code> class already, why do we even need the mutable <code>StringBuilder</code> in programming? A common use for it is to concatenate a large number of strings together. Consider this code:</p><pre><code class="language-java hljs">String s = <span class="hljs-string">""</span>;
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < n; ++i) {
s = s + i;
}</code></pre>
<p class="no-markdown">Using immutable strings, this makes a lot of temporary copies — the first number of the string (<code>"0"</code>) is actually copied <em>n</em> times in the course of building up the final string, the second number is copied <em>n-1</em> times, and so on. It actually costs <em>O(n<sup>2</sup>)</em> time just to do all that copying, even though we only concatenated <em>n</em> elements.</p>
<p><code>StringBuilder</code> is designed to minimize this copying. It uses a simple but clever internal data structure to avoid doing any copying at all until the very end when you ask for the final <code>String</code> with a <code>toString()</code> call:</p><pre><code class="language-java hljs">StringBuilder sb = <span class="hljs-keyword">new</span> StringBuilder();
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < n; ++i) {
sb.append(String.valueOf(i));
}
String s = sb.toString();</code></pre>
<p>Getting good performance is one reason why we use mutable objects. Another is convenient sharing: two parts of your program can communicate more conveniently by sharing a common mutable data structure.</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@vertical_Questions_e7f6070d1766" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="VerticalStudentView" data-request-token="cec4e5c002f511efa5270afff417eba9">
<h2 class="hd hd-2 unit-title">Questions</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<script src="/assets/courseware/v1/3e6443fb95285d2dc06e8ffc448b9bdf/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism.js"></script>
<script src="/assets/courseware/v1/2ba76f8bdfef4e2d45e31a3dc5208470/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/edx-script-v1.js"></script>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-follow-me">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-follow-me" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="True" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_07-follow-me" class="problems-wrapper" role="group"
aria-labelledby="07-follow-me-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-follow-me" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-follow-me/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="3"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="07-follow-me-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-follow-me-problem-progress" tabindex="-1">
follow me
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-follow-me-problem-progress"></div>
<div class="problem">
<div>
<img src="/assets/courseware/v1/42cad8e7200c7b4bdd48e9cce21b4dd9/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/07-snapshot-diagram.png" width="400"/>
<br/>
<p>Is it possible that a client with the variable <code>terrarium</code> could modify the <code>Turtle</code> in red?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_07-follow-me_2_1">
<fieldset aria-describedby="status_07-follow-me_2_1">
<div class="field">
<input type="radio" name="input_07-follow-me_2_1" id="input_07-follow-me_2_1_choice_0" class="field-input input-radio" value="choice_0"/><label id="07-follow-me_2_1-choice_0-label" for="input_07-follow-me_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_07-follow-me_2_1"> Yes, because all the references between "terrarium" and the "Turtle" are mutable
</label>
</div>
<div class="field">
<input type="radio" name="input_07-follow-me_2_1" id="input_07-follow-me_2_1_choice_1" class="field-input input-radio" value="choice_1"/><label id="07-follow-me_2_1-choice_1-label" for="input_07-follow-me_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_07-follow-me_2_1"> Yes, because of some reference between "terrarium" and the "Turtle" that is mutable
</label>
</div>
<div class="field">
<input type="radio" name="input_07-follow-me_2_1" id="input_07-follow-me_2_1_choice_2" class="field-input input-radio" value="choice_2"/><label id="07-follow-me_2_1-choice_2-label" for="input_07-follow-me_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_07-follow-me_2_1"> Yes, because the "Turtle" is mutable
</label>
</div>
<div class="field">
<input type="radio" name="input_07-follow-me_2_1" id="input_07-follow-me_2_1_choice_3" class="field-input input-radio" value="choice_3"/><label id="07-follow-me_2_1-choice_3-label" for="input_07-follow-me_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_07-follow-me_2_1"> No, because the "Turtle" is immutable
</label>
</div>
<div class="field">
<input type="radio" name="input_07-follow-me_2_1" id="input_07-follow-me_2_1_choice_4" class="field-input input-radio" value="choice_4"/><label id="07-follow-me_2_1-choice_4-label" for="input_07-follow-me_2_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_07-follow-me_2_1"> No, because of some reference between "terrarium" and the "Turtle" that is immutable
</label>
</div>
<div class="field">
<input type="radio" name="input_07-follow-me_2_1" id="input_07-follow-me_2_1_choice_5" class="field-input input-radio" value="choice_5"/><label id="07-follow-me_2_1-choice_5-label" for="input_07-follow-me_2_1_choice_5" class="response-label field-label label-inline" aria-describedby="status_07-follow-me_2_1"> No, because all the references between "terrarium" and the "Turtle" are immutable
</label>
</div>
<span id="answer_07-follow-me_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_07-follow-me_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_07-follow-me_solution_1"/>
</div><p>Is it possible that a client with the variable <code>george</code> could modify the <code>Gecko</code> in blue?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 2" role="group"><div class="choicegroup capa_inputtype" id="inputtype_07-follow-me_3_1">
<fieldset aria-describedby="status_07-follow-me_3_1">
<div class="field">
<input type="radio" name="input_07-follow-me_3_1" id="input_07-follow-me_3_1_choice_0" class="field-input input-radio" value="choice_0"/><label id="07-follow-me_3_1-choice_0-label" for="input_07-follow-me_3_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_07-follow-me_3_1"> Yes, because all the references between "george" and the "Gecko" are mutable
</label>
</div>
<div class="field">
<input type="radio" name="input_07-follow-me_3_1" id="input_07-follow-me_3_1_choice_1" class="field-input input-radio" value="choice_1"/><label id="07-follow-me_3_1-choice_1-label" for="input_07-follow-me_3_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_07-follow-me_3_1"> Yes, because of some reference between "george" and the "Gecko" that is mutable
</label>
</div>
<div class="field">
<input type="radio" name="input_07-follow-me_3_1" id="input_07-follow-me_3_1_choice_2" class="field-input input-radio" value="choice_2"/><label id="07-follow-me_3_1-choice_2-label" for="input_07-follow-me_3_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_07-follow-me_3_1"> Yes, because the "Gecko" is mutable
</label>
</div>
<div class="field">
<input type="radio" name="input_07-follow-me_3_1" id="input_07-follow-me_3_1_choice_3" class="field-input input-radio" value="choice_3"/><label id="07-follow-me_3_1-choice_3-label" for="input_07-follow-me_3_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_07-follow-me_3_1"> No, because the "Gecko" is immutable
</label>
</div>
<div class="field">
<input type="radio" name="input_07-follow-me_3_1" id="input_07-follow-me_3_1_choice_4" class="field-input input-radio" value="choice_4"/><label id="07-follow-me_3_1-choice_4-label" for="input_07-follow-me_3_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_07-follow-me_3_1"> No, because of some reference between "george" and the "Gecko" that is immutable
</label>
</div>
<div class="field">
<input type="radio" name="input_07-follow-me_3_1" id="input_07-follow-me_3_1_choice_5" class="field-input input-radio" value="choice_5"/><label id="07-follow-me_3_1-choice_5-label" for="input_07-follow-me_3_1_choice_5" class="response-label field-label label-inline" aria-describedby="status_07-follow-me_3_1"> No, because all the references between "george" and the "Gecko" are immutable
</label>
</div>
<span id="answer_07-follow-me_3_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_07-follow-me_3_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_07-follow-me_solution_2"/>
</div><p>Is it possible that a client with the variable <code>petStore</code> could do something such that a client with the variable <code>terrarium</code> could no longer access the <code>Gecko</code> in blue?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 3" role="group"><div class="choicegroup capa_inputtype" id="inputtype_07-follow-me_4_1">
<fieldset aria-describedby="status_07-follow-me_4_1">
<div class="field">
<input type="radio" name="input_07-follow-me_4_1" id="input_07-follow-me_4_1_choice_0" class="field-input input-radio" value="choice_0"/><label id="07-follow-me_4_1-choice_0-label" for="input_07-follow-me_4_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_07-follow-me_4_1"> Yes, because all the references between "petStore" and the "Gecko" are mutable
</label>
</div>
<div class="field">
<input type="radio" name="input_07-follow-me_4_1" id="input_07-follow-me_4_1_choice_1" class="field-input input-radio" value="choice_1"/><label id="07-follow-me_4_1-choice_1-label" for="input_07-follow-me_4_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_07-follow-me_4_1"> Yes, because of some reference between "petStore" and the "Gecko" that is mutable
</label>
</div>
<div class="field">
<input type="radio" name="input_07-follow-me_4_1" id="input_07-follow-me_4_1_choice_2" class="field-input input-radio" value="choice_2"/><label id="07-follow-me_4_1-choice_2-label" for="input_07-follow-me_4_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_07-follow-me_4_1"> Yes, because the "Gecko" is mutable
</label>
</div>
<div class="field">
<input type="radio" name="input_07-follow-me_4_1" id="input_07-follow-me_4_1_choice_3" class="field-input input-radio" value="choice_3"/><label id="07-follow-me_4_1-choice_3-label" for="input_07-follow-me_4_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_07-follow-me_4_1"> No, because the "Gecko" is immutable
</label>
</div>
<div class="field">
<input type="radio" name="input_07-follow-me_4_1" id="input_07-follow-me_4_1_choice_4" class="field-input input-radio" value="choice_4"/><label id="07-follow-me_4_1-choice_4-label" for="input_07-follow-me_4_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_07-follow-me_4_1"> No, because of some reference between "petStore" and the "Gecko" that is immutable
</label>
</div>
<div class="field">
<input type="radio" name="input_07-follow-me_4_1" id="input_07-follow-me_4_1_choice_5" class="field-input input-radio" value="choice_5"/><label id="07-follow-me_4_1-choice_5-label" for="input_07-follow-me_4_1_choice_5" class="response-label field-label label-inline" aria-describedby="status_07-follow-me_4_1"> No, because all the references between "petStore" and the "Gecko" are immutable
</label>
</div>
<span id="answer_07-follow-me_4_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_07-follow-me_4_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_07-follow-me_solution_3"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="follow me" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_07-follow-me" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_07-follow-me">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-follow-me-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-follow-me-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-follow-me-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@vertical-risks-of-mutation" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="VerticalStudentView" data-request-token="cec4e5c002f511efa5270afff417eba9">
<h2 class="hd hd-2 unit-title">Risks of Mutation</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_de4b54bb10ce">
<div class="xblock xblock-public_view xblock-public_view-video xmodule_display xmodule_VideoBlock" data-block-type="video" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_de4b54bb10ce" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Video"}
</script>
<h3 class="hd hd-2">Video</h3>
<div
id="video_video_de4b54bb10ce"
class="video closed"
data-metadata='{"transcriptLanguages": {"en": "English"}, "captionDataDir": null, "autoAdvance": false, "poster": null, "publishCompletionUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_de4b54bb10ce/handler/publish_completion", "transcriptLanguage": "en", "showCaptions": "true", "completionEnabled": false, "prioritizeHls": false, "sources": ["https://d2f1egay8yehza.cloudfront.net/MIT600512016-V004400_DTH.mp4", "https://d2f1egay8yehza.cloudfront.net/MIT600512016-V004400/MIT600512016-V004400.m3u8"], "transcriptAvailableTranslationsUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_de4b54bb10ce/handler/transcript/available_translations", "ytApiUrl": "https://www.youtube.com/iframe_api", "autohideHtml5": false, "start": 0.0, "generalSpeed": 1.0, "recordedYoutubeIsAvailable": true, "speed": null, "end": 0.0, "ytMetadataEndpoint": "", "savedVideoPosition": 0.0, "ytTestTimeout": 1500, "autoplay": false, "saveStateUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_de4b54bb10ce/handler/xmodule_handler/save_user_state", "saveStateEnabled": false, "transcriptTranslationUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_de4b54bb10ce/handler/transcript/translation/__lang__", "streams": "1.00:L6xl_z-cSlk", "completionPercentage": 0.95, "duration": 188.01, "lmsRootURL": "https://openlearninglibrary.mit.edu"}'
data-bumper-metadata='null'
data-autoadvance-enabled="False"
data-poster='null'
tabindex="-1"
>
<div class="focus_grabber first"></div>
<div class="tc-wrapper">
<div class="video-wrapper">
<span tabindex="0" class="spinner" aria-hidden="false" aria-label="Loading video player"></span>
<span tabindex="-1" class="btn-play fa fa-youtube-play fa-2x is-hidden" aria-hidden="true" aria-label="Play video"></span>
<div class="video-player-pre"></div>
<div class="video-player">
<div id="video_de4b54bb10ce"></div>
<h4 class="hd hd-4 video-error is-hidden">No playable video sources found.</h4>
<h4 class="hd hd-4 video-hls-error is-hidden">
Your browser does not support this video format. Try using a different browser.
</h4>
</div>
<div class="video-player-post"></div>
<div class="closed-captions"></div>
<div class="video-controls is-hidden">
<div>
<div class="vcr"><div class="vidtime">0:00 / 0:00</div></div>
<div class="secondary-controls"></div>
</div>
</div>
</div>
</div>
<div class="focus_grabber last"></div>
<h3 class="hd hd-4 downloads-heading sr" id="video-download-transcripts_video_de4b54bb10ce">Downloads and transcripts</h3>
<div class="wrapper-downloads" role="region" aria-labelledby="video-download-transcripts_video_de4b54bb10ce">
<div class="wrapper-download-transcripts">
<h4 class="hd hd-5">Transcripts</h4>
<ul class="list-download-transcripts">
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_de4b54bb10ce/handler/transcript/download" data-value="srt">Download SubRip (.srt) file</a>
</li>
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_de4b54bb10ce/handler/transcript/download" data-value="txt">Download Text (.txt) file</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_e540c506656c">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_e540c506656c" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<h2 id="risks_of_mutation">Risks of mutation</h2>
<div data-outline="risks_of_mutation">
<p>Mutable types seem much more powerful than immutable types. If you were shopping in the Datatype Supermarket and you had to choose between a boring immutable <code>String</code> and a super-powerful-do-anything mutable <code>StringBuilder</code>, why on earth would you choose the immutable one?
<code>StringBuilder</code> should be able to do everything that <code>String</code> can do, plus <code>set()</code> and <code>append()</code> and everything else.</p>
<p>The answer is that <strong>immutable types are safer from bugs, easier to understand, and more ready for change</strong>. Mutability makes it harder to understand what your program is doing and much harder to enforce contracts. Here are two examples that illustrate why.</p>
<h3 id="risky_example_1_passing_mutable_values">Risky example #1: passing mutable values</h3>
<div data-outline="risky_example_1_passing_mutable_values">
<p>Let's start with a simple method that sums the integers in a list:</p><pre><code class="language-java hljs"><span class="hljs-comment handout-javadoc-comment">/** <span class="hljs-doctag">@return</span> the sum of the numbers in the list */</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">sum</span><span class="hljs-params">(List<Integer> list)</span> </span>{
<span class="hljs-keyword">int</span> sum = <span class="hljs-number">0</span>;
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> x : list)
sum += x;
<span class="hljs-keyword">return</span> sum;
}</code></pre>
<p>Suppose we also need a method that sums the absolute values. Following good DRY practice (<a href="/courses/course-v1:MITx+6.005.1x+3T2016/jump_to_id/vertical-dont-repeat-yourself#dont_repeat_yourself">Don't Repeat Yourself</a>), the implementer writes a method that uses <code>sum()</code>:</p><pre><code class="language-java hljs"><span class="hljs-comment handout-javadoc-comment">/** <span class="hljs-doctag">@return</span> the sum of the absolute values of the numbers in the list */</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">sumOfAbsoluteValues</span><span class="hljs-params">(List<Integer> list)</span> </span>{
<span class="hljs-comment">// let's reuse sum() because DRY, so first we take absolute values</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < list.size(); ++i)
list.set(i, Math.abs(list.get(i)));
<span class="hljs-keyword">return</span> sum(list);
}</code></pre>
<p>Notice that this method does its job by <strong>mutating the list directly</strong>. It seemed sensible to the implementer because it's more efficient to reuse the existing list. If the list is millions of items long, then you're saving the time and memory of generating a new million-item list of absolute values. So the implementer has two very good reasons for this design: DRY and performance.</p>
<p>But the resulting behavior will be very surprising to anybody who uses it! For example:</p><pre><code class="language-java hljs"><span class="hljs-comment">// meanwhile, somewhere else in the code...</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
<span class="hljs-comment">// ...</span>
List<Integer> myData = Arrays.asList(-<span class="hljs-number">5</span>, -<span class="hljs-number">3</span>, -<span class="hljs-number">2</span>);
System.out.println(sumOfAbsoluteValues(myData));
System.out.println(sum(myData));
}</code></pre>
<p>What will this code print? Will it be 10 followed by -10? Or something else?</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@vertical_Questions_26d811e8a7e5" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="VerticalStudentView" data-request-token="cec4e5c002f511efa5270afff417eba9">
<h2 class="hd hd-2 unit-title">Questions</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<script src="/assets/courseware/v1/3e6443fb95285d2dc06e8ffc448b9bdf/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism.js"></script>
<script src="/assets/courseware/v1/2ba76f8bdfef4e2d45e31a3dc5208470/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/edx-script-v1.js"></script>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-risky-1">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-risky-1" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="True" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_07-risky-1" class="problems-wrapper" role="group"
aria-labelledby="07-risky-1-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-risky-1" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-risky-1/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="2"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="07-risky-1-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-risky-1-problem-progress" tabindex="-1">
risky #1
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-risky-1-problem-progress"></div>
<div class="problem">
<div>
<pre class="code">
/** @return the sum of the numbers in the list */
public static int sum(List&lt;Integer&gt; list) {
int sum = 0;
for (int x : list)
sum += x;
return sum;
}
</pre>
<pre class="code">
/** @return the sum of the absolute values of the numbers in the list */
public static int sumOfAbsoluteValues(List&lt;Integer&gt; list) {
// let's reuse sum(), because DRY, so first we take absolute values
for (int i = 0; i &lt; list.size(); ++i)
list.set(i, Math.abs(list.get(i)));
return sum(list);
}
</pre>
<pre class="code">
// meanwhile, somewhere else in the code...
public static void main(String[] args) {
// ...
List&lt;Integer&gt; myData = Arrays.asList(-5, -3, -2);
System.out.println(sumOfAbsoluteValues(myData));
System.out.println(sum(myData));
}
</pre>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div id="formulaequationinput_07-risky-1_2_1" class="inputtype formulaequationinput">
<div class="unanswered">
<label class="problem-group-label" for="input_07-risky-1_2_1" id="label_07-risky-1_2_1">What will this code print?</label>
<input type="text" name="input_07-risky-1_2_1" id="input_07-risky-1_2_1" data-input-id="07-risky-1_2_1" value="" aria-describedby="status_07-risky-1_2_1" size="20"/>
<span class="trailing_text" id="trailing_text_07-risky-1_2_1"/>
<span class="status unanswered" id="status_07-risky-1_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
<p id="answer_07-risky-1_2_1" class="answer"/>
<div id="input_07-risky-1_2_1_preview" class="equation">
\(\)
<img src="/static/images/spinner.bc34f953403f.gif" class="loading" alt="Loading"/>
</div>
</div>
<div class="script_placeholder" data-src="/static/js/capa/src/formula_equation_preview.b1967ab28c31.js"/>
</div></div>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 2" role="group"><div id="formulaequationinput_07-risky-1_3_1" class="inputtype formulaequationinput">
<div class="unanswered">
<input type="text" name="input_07-risky-1_3_1" id="input_07-risky-1_3_1" data-input-id="07-risky-1_3_1" value="" aria-describedby="status_07-risky-1_3_1" size="20"/>
<span class="trailing_text" id="trailing_text_07-risky-1_3_1"/>
<span class="status unanswered" id="status_07-risky-1_3_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
<p id="answer_07-risky-1_3_1" class="answer"/>
<div id="input_07-risky-1_3_1_preview" class="equation">
\(\)
<img src="/static/images/spinner.bc34f953403f.gif" class="loading" alt="Loading"/>
</div>
</div>
<div class="script_placeholder" data-src="/static/js/capa/src/formula_equation_preview.b1967ab28c31.js"/>
</div></div>
<div class="solution-span">
<span id="solution_07-risky-1_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="risky #1" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_07-risky-1" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_07-risky-1">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-risky-1-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-risky-1-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-risky-1-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@Risky_Example_2" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="VerticalStudentView" data-request-token="cec4e5c002f511efa5270afff417eba9">
<h2 class="hd hd-2 unit-title">Risky Example 2</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_401140cf6017">
<div class="xblock xblock-public_view xblock-public_view-video xmodule_display xmodule_VideoBlock" data-block-type="video" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_401140cf6017" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Video"}
</script>
<h3 class="hd hd-2">Video</h3>
<div
id="video_video_401140cf6017"
class="video closed"
data-metadata='{"transcriptLanguages": {"en": "English"}, "captionDataDir": null, "autoAdvance": false, "poster": null, "publishCompletionUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_401140cf6017/handler/publish_completion", "transcriptLanguage": "en", "showCaptions": "true", "completionEnabled": false, "prioritizeHls": false, "sources": ["https://d2f1egay8yehza.cloudfront.net/MIT600512016-V004300_DTH.mp4", "https://d2f1egay8yehza.cloudfront.net/MIT600512016-V004300/MIT600512016-V004300.m3u8"], "transcriptAvailableTranslationsUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_401140cf6017/handler/transcript/available_translations", "ytApiUrl": "https://www.youtube.com/iframe_api", "autohideHtml5": false, "start": 0.0, "generalSpeed": 1.0, "recordedYoutubeIsAvailable": true, "speed": null, "end": 0.0, "ytMetadataEndpoint": "", "savedVideoPosition": 0.0, "ytTestTimeout": 1500, "autoplay": false, "saveStateUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_401140cf6017/handler/xmodule_handler/save_user_state", "saveStateEnabled": false, "transcriptTranslationUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_401140cf6017/handler/transcript/translation/__lang__", "streams": "1.00:MpupqfBK2VA", "completionPercentage": 0.95, "duration": 274.65, "lmsRootURL": "https://openlearninglibrary.mit.edu"}'
data-bumper-metadata='null'
data-autoadvance-enabled="False"
data-poster='null'
tabindex="-1"
>
<div class="focus_grabber first"></div>
<div class="tc-wrapper">
<div class="video-wrapper">
<span tabindex="0" class="spinner" aria-hidden="false" aria-label="Loading video player"></span>
<span tabindex="-1" class="btn-play fa fa-youtube-play fa-2x is-hidden" aria-hidden="true" aria-label="Play video"></span>
<div class="video-player-pre"></div>
<div class="video-player">
<div id="video_401140cf6017"></div>
<h4 class="hd hd-4 video-error is-hidden">No playable video sources found.</h4>
<h4 class="hd hd-4 video-hls-error is-hidden">
Your browser does not support this video format. Try using a different browser.
</h4>
</div>
<div class="video-player-post"></div>
<div class="closed-captions"></div>
<div class="video-controls is-hidden">
<div>
<div class="vcr"><div class="vidtime">0:00 / 0:00</div></div>
<div class="secondary-controls"></div>
</div>
</div>
</div>
</div>
<div class="focus_grabber last"></div>
<h3 class="hd hd-4 downloads-heading sr" id="video-download-transcripts_video_401140cf6017">Downloads and transcripts</h3>
<div class="wrapper-downloads" role="region" aria-labelledby="video-download-transcripts_video_401140cf6017">
<div class="wrapper-download-transcripts">
<h4 class="hd hd-5">Transcripts</h4>
<ul class="list-download-transcripts">
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_401140cf6017/handler/transcript/download" data-value="srt">Download SubRip (.srt) file</a>
</li>
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_401140cf6017/handler/transcript/download" data-value="txt">Download Text (.txt) file</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_18f3677ff356">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_18f3677ff356" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<pre><code class="language-java hljs"><span class="hljs-comment handout-javadoc-comment">/** <span class="hljs-doctag">@return</span> the sum of the absolute values of the numbers in the list */</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">sumOfAbsoluteValues</span><span class="hljs-params">(List<Integer> list)</span> </span>{
<span class="hljs-comment">// let's reuse sum(), because DRY, so first we take absolute values</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < list.size(); ++i)
list.set(i, Math.abs(list.get(i)));
<span class="hljs-keyword">return</span> sum(list);
}
<span class="hljs-comment">// meanwhile, somewhere else in the code...</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
<span class="hljs-comment">// ...</span>
List<Integer> myData = Arrays.asList(-<span class="hljs-number">5</span>, -<span class="hljs-number">3</span>, -<span class="hljs-number">2</span>);
System.out.println(sumOfAbsoluteValues(myData));
System.out.println(sum(myData));
}</code></pre>
<p>Let's think about the key lessons of this example here:</p>
<ul>
<li>
<p><strong>Is it safe from bugs?</strong> In this example, it's easy to blame the implementer of <code>sumAbsolute()</code> for going beyond what its spec allowed. But really, <strong>passing mutable objects around is a latent bug</strong>. It's just waiting for some programmer to inadvertently mutate that list, often with very good intentions like reuse or performance, but resulting in a bug that may be very hard to track down. </p>
</li>
<li>
<p><strong>Is it easy to understand?</strong> When reading <code>main()</code>, what would you assume about <code>sum()</code> and <code>sumOfAbsoluteValues()</code>? Is it clearly visible to the reader that <code>myData</code> gets <em>changed</em> by one of them? </p>
</li>
</ul>
</div>
<h3 id="risky_example_2_returning_mutable_values">Risky example #2: returning mutable values</h3>
<div data-outline="risky_example_2_returning_mutable_values">
<p>We just saw an example where passing a mutable object to a function caused problems. What about returning a mutable object?</p>
<p>Let's consider <a href="http://docs.oracle.com/javase/8/docs/api/?java/util/Date.html"><code>Date</code></a>, one of the built-in Java classes.
<code>Date</code> happens to be a mutable type. Suppose we write a method that determines the first day of spring:</p><pre><code class="language-java hljs"><span class="hljs-comment handout-javadoc-comment">/** <span class="hljs-doctag">@return</span> the first day of spring this year */</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Date <span class="hljs-title">startOfSpring</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> askGroundhog();
}</code></pre>
<p>Here we're using the <a href="https://en.wikipedia.org/wiki/Groundhog_Day">Groundhog algorithm</a> for determining when spring starts.</p>
<p>Clients start using this method, for example to plan their big parties:</p><pre><code class="language-java hljs"><span class="hljs-comment">// somewhere else in the code...</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">partyPlanning</span><span class="hljs-params">()</span> </span>{
Date partyDate = startOfSpring();
<span class="hljs-comment">// ...</span>
}</code></pre>
<p>All the code works and people are happy. Now, independently, two things happen. First, the implementer of <code>startOfSpring()</code> realizes that the groundhog is starting to get annoyed from being constantly asked when spring will start. So the code is rewritten to ask the groundhog at most once and then cache the groundhog's answer for future calls:</p><pre><code class="language-java hljs"><span class="hljs-comment handout-javadoc-comment">/** <span class="hljs-doctag">@return</span> the first day of spring this year */</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Date <span class="hljs-title">startOfSpring</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">if</span> (groundhogAnswer == <span class="hljs-keyword">null</span>) groundhogAnswer = askGroundhog();
<span class="hljs-keyword">return</span> groundhogAnswer;
}
<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Date groundhogAnswer = <span class="hljs-keyword">null</span>;</code></pre>
<p>(Aside: note the use of a private static variable for the cached answer. Would you consider this a global variable or not?)</p>
<p>Second, one of the clients of <code>startOfSpring()</code> decides that the actual first day of spring is too cold for the party, so the party will be exactly a month later instead:</p><pre><code class="language-java hljs"><span class="hljs-comment">// somewhere else in the code...</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">partyPlanning</span><span class="hljs-params">()</span> </span>{
<span class="hljs-comment">// let's have a party one month after spring starts!</span>
Date partyDate = startOfSpring();
partyDate.setMonth(partyDate.getMonth() + <span class="hljs-number">1</span>);
<span class="hljs-comment">// ... uh-oh. what just happened?</span>
}</code></pre>
<p>(Aside: this code also has a latent bug in the way it adds a month. Why? What does it implicitly assume about when spring starts?)</p>
<p>What happens when these two decisions interact? Even worse, think about who will first discover this bug — will it be <code>startOfSpring()</code>? Will it be <code>partyPlanning()</code>? Or will it be some completely innocent third piece of code that also calls <code>startOfSpring()</code>?</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@vertical_Questions_71ff1f9963b6" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="VerticalStudentView" data-request-token="cec4e5c002f511efa5270afff417eba9">
<h2 class="hd hd-2 unit-title">Questions</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<script src="/assets/courseware/v1/3e6443fb95285d2dc06e8ffc448b9bdf/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism.js"></script>
<script src="/assets/courseware/v1/2ba76f8bdfef4e2d45e31a3dc5208470/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/edx-script-v1.js"></script>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-risky-2">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-risky-2" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="True" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_07-risky-2" class="problems-wrapper" role="group"
aria-labelledby="07-risky-2-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-risky-2" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-risky-2/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="07-risky-2-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-risky-2-problem-progress" tabindex="-1">
risky #2
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-risky-2-problem-progress"></div>
<div class="problem">
<div>
<pre class="code">
/** @return the first day of spring this year */
public static Date startOfSpring() {
if (groundhogAnswer == null) groundhogAnswer = askGroundhog();
return groundhogAnswer;
}
private static Date groundhogAnswer = null;
</pre>
<pre class="code">
// somewhere else in the code...
public static void partyPlanning() {
// let's have a party one month after spring starts!
Date partyDate = startOfSpring();
partyDate.setMonth(partyDate.getMonth() + 1);
// ... uh-oh. what just happened?
}
</pre>
<p>We don't know how <code>Date</code> stores the month, so we'll represent that with the abstract values <code>...march...</code> and <code>...april...</code> in an imagined <code>month</code> field of <code>Date</code>.</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_07-risky-2_2_1">
<fieldset aria-describedby="status_07-risky-2_2_1">
<legend id="07-risky-2_2_1-legend" class="response-fieldset-legend field-group-hd">Which of these snapshot diagrams shows the bug?</legend>
<div class="field">
<input type="radio" name="input_07-risky-2_2_1" id="input_07-risky-2_2_1_choice_0" class="field-input input-radio" value="choice_0"/><label id="07-risky-2_2_1-choice_0-label" for="input_07-risky-2_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_07-risky-2_2_1">
<img src="/assets/courseware/v1/e98cfda928cf6b8010540a7099fa98f4/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/07-risky2-1.png" width="334"/>
</label>
</div>
<div class="field">
<input type="radio" name="input_07-risky-2_2_1" id="input_07-risky-2_2_1_choice_1" class="field-input input-radio" value="choice_1"/><label id="07-risky-2_2_1-choice_1-label" for="input_07-risky-2_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_07-risky-2_2_1">
<img src="/assets/courseware/v1/21259c15a1f0f6c1264c30db2b48704c/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/07-risky2-2.png" width="400"/>
</label>
</div>
<div class="field">
<input type="radio" name="input_07-risky-2_2_1" id="input_07-risky-2_2_1_choice_2" class="field-input input-radio" value="choice_2"/><label id="07-risky-2_2_1-choice_2-label" for="input_07-risky-2_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_07-risky-2_2_1">
<img src="/assets/courseware/v1/36fdb0d1fdc3e9a4fd4272868bff9f3c/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/07-risky2-3.png" width="400"/>
</label>
</div>
<div class="field">
<input type="radio" name="input_07-risky-2_2_1" id="input_07-risky-2_2_1_choice_3" class="field-input input-radio" value="choice_3"/><label id="07-risky-2_2_1-choice_3-label" for="input_07-risky-2_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_07-risky-2_2_1">
<img src="/assets/courseware/v1/62d1b9e19a9e4f14eb41994c5d06a247/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/07-risky2-4.png" width="334"/>
</label>
</div>
<div class="field">
<input type="radio" name="input_07-risky-2_2_1" id="input_07-risky-2_2_1_choice_4" class="field-input input-radio" value="choice_4"/><label id="07-risky-2_2_1-choice_4-label" for="input_07-risky-2_2_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_07-risky-2_2_1">
<img src="/assets/courseware/v1/3d1e5a24aafb05a716f7f3fe48a5cd29/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/07-risky2-5.png" width="334"/>
</label>
</div>
<span id="answer_07-risky-2_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_07-risky-2_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_07-risky-2_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="risky #2" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_07-risky-2" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_07-risky-2">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-risky-2-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-risky-2-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-risky-2-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
<div class="vert vert-2" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-understanding-risky-example-2">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-understanding-risky-example-2" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="True" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_07-understanding-risky-example-2" class="problems-wrapper" role="group"
aria-labelledby="07-understanding-risky-example-2-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-understanding-risky-example-2" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-understanding-risky-example-2/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="07-understanding-risky-example-2-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-understanding-risky-example-2-problem-progress" tabindex="-1">
understanding risky example #2
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-understanding-risky-example-2-problem-progress"></div>
<div class="problem">
<div>
<p><code>partyPlanning</code> has unwittingly changed the start of spring because <code>partyDate</code> and <code>groundhogAnswer</code> happen to point to the same mutable <code>Date</code> object.</p>
<p>Worse, this bug will probably <em>not</em> be discovered in <code>partyPlanning()</code> or <code>startOfSpring()</code> right away. Instead, it will be some innocent piece of code that subsequently calls <code>startOfSpring()</code>, gets the wrong date back, and goes on to compute its own wrong answer.</p>
<strong>Globalization?</strong>
<p>Is one problem here that <code>groundhogAnswer</code> is a global variable?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_07-understanding-risky-example-2_2_1">
<fieldset aria-describedby="status_07-understanding-risky-example-2_2_1">
<div class="field">
<input type="radio" name="input_07-understanding-risky-example-2_2_1" id="input_07-understanding-risky-example-2_2_1_choice_0" class="field-input input-radio" value="choice_0"/><label id="07-understanding-risky-example-2_2_1-choice_0-label" for="input_07-understanding-risky-example-2_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_07-understanding-risky-example-2_2_1"> It's global, that's OK
</label>
</div>
<div class="field">
<input type="radio" name="input_07-understanding-risky-example-2_2_1" id="input_07-understanding-risky-example-2_2_1_choice_1" class="field-input input-radio" value="choice_1"/><label id="07-understanding-risky-example-2_2_1-choice_1-label" for="input_07-understanding-risky-example-2_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_07-understanding-risky-example-2_2_1"> It's global, that's terrible
</label>
</div>
<div class="field">
<input type="radio" name="input_07-understanding-risky-example-2_2_1" id="input_07-understanding-risky-example-2_2_1_choice_2" class="field-input input-radio" value="choice_2"/><label id="07-understanding-risky-example-2_2_1-choice_2-label" for="input_07-understanding-risky-example-2_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_07-understanding-risky-example-2_2_1"> It's not global
</label>
</div>
<span id="answer_07-understanding-risky-example-2_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_07-understanding-risky-example-2_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_07-understanding-risky-example-2_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="understanding risky example #2" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_07-understanding-risky-example-2" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_07-understanding-risky-example-2">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-understanding-risky-example-2-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-understanding-risky-example-2-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-understanding-risky-example-2-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
<div class="vert vert-3" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-arithmonthmatic">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-arithmonthmatic" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="True" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_07-arithmonthmatic" class="problems-wrapper" role="group"
aria-labelledby="07-arithmonthmatic-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-arithmonthmatic" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-arithmonthmatic/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="07-arithmonthmatic-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-arithmonthmatic-problem-progress" tabindex="-1">
arithmonthmatic
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-arithmonthmatic-problem-progress"></div>
<div class="problem">
<div>
<strong>A second bug</strong>
<p>The code has another potential bug in how it adds to the month.</p>
<p>Take a look at the Java API documentation for <code>Date.setMonth</code>.</p>
<p>For what result of <code>partyDate.getMonth()</code> could there be a problem?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="inputtype option-input ">
<select name="input_07-arithmonthmatic_2_1" id="input_07-arithmonthmatic_2_1" aria-describedby="status_07-arithmonthmatic_2_1">
<option value="option_07-arithmonthmatic_2_1_dummy_default">Select an option</option>
<option value="0"> 0</option>
<option value="1"> 1</option>
<option value="2"> 2</option>
<option value="3"> 3</option>
<option value="4"> 4</option>
<option value="5"> 5</option>
<option value="6"> 6</option>
<option value="7"> 7</option>
<option value="8"> 8</option>
<option value="9"> 9</option>
<option value="10"> 10</option>
<option value="11"> 11</option>
<option value="12"> 12</option>
</select>
<div class="indicator-container">
<span class="status unanswered" id="status_07-arithmonthmatic_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
<p class="answer" id="answer_07-arithmonthmatic_2_1"/>
</div></div>
<div class="solution-span">
<span id="solution_07-arithmonthmatic_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="arithmonthmatic" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_07-arithmonthmatic" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_07-arithmonthmatic">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-arithmonthmatic-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-arithmonthmatic-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-arithmonthmatic-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
<div class="vert vert-4" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-nosuchmonthexception">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-nosuchmonthexception" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="True" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_07-nosuchmonthexception" class="problems-wrapper" role="group"
aria-labelledby="07-nosuchmonthexception-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-nosuchmonthexception" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-nosuchmonthexception/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="07-nosuchmonthexception-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-nosuchmonthexception-problem-progress" tabindex="-1">
NoSuchMonthException
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-nosuchmonthexception-problem-progress"></div>
<div class="problem">
<div>
<p>The documentation for <code>Date.setMonth</code> says: <code>month - the month value between 0-11</code>.</p>
<p>Based on that statement and what you've read so far...</p>
<p>Which of the following <em>might</em> happen when this month-adding bug is triggered? Check all that apply.</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_07-nosuchmonthexception_2_1">
<fieldset aria-describedby="status_07-nosuchmonthexception_2_1">
<div class="field">
<input type="checkbox" name="input_07-nosuchmonthexception_2_1[]" id="input_07-nosuchmonthexception_2_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="07-nosuchmonthexception_2_1-choice_0-label" for="input_07-nosuchmonthexception_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_07-nosuchmonthexception_2_1"> The method call will do nothing
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-nosuchmonthexception_2_1[]" id="input_07-nosuchmonthexception_2_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="07-nosuchmonthexception_2_1-choice_1-label" for="input_07-nosuchmonthexception_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_07-nosuchmonthexception_2_1"> The method call will actually do the thing we wanted
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-nosuchmonthexception_2_1[]" id="input_07-nosuchmonthexception_2_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="07-nosuchmonthexception_2_1-choice_2-label" for="input_07-nosuchmonthexception_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_07-nosuchmonthexception_2_1"> The method call will cause the Date object to become invalid and report incorrect values
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-nosuchmonthexception_2_1[]" id="input_07-nosuchmonthexception_2_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="07-nosuchmonthexception_2_1-choice_3-label" for="input_07-nosuchmonthexception_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_07-nosuchmonthexception_2_1"> The method call will throw a checked exception
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-nosuchmonthexception_2_1[]" id="input_07-nosuchmonthexception_2_1_choice_4" class="field-input input-checkbox" value="choice_4"/><label id="07-nosuchmonthexception_2_1-choice_4-label" for="input_07-nosuchmonthexception_2_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_07-nosuchmonthexception_2_1"> The method call will throw an unchecked exception
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-nosuchmonthexception_2_1[]" id="input_07-nosuchmonthexception_2_1_choice_5" class="field-input input-checkbox" value="choice_5"/><label id="07-nosuchmonthexception_2_1-choice_5-label" for="input_07-nosuchmonthexception_2_1_choice_5" class="response-label field-label label-inline" aria-describedby="status_07-nosuchmonthexception_2_1"> The method call will set our computer clock to 9/9/99
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-nosuchmonthexception_2_1[]" id="input_07-nosuchmonthexception_2_1_choice_6" class="field-input input-checkbox" value="choice_6"/><label id="07-nosuchmonthexception_2_1-choice_6-label" for="input_07-nosuchmonthexception_2_1_choice_6" class="response-label field-label label-inline" aria-describedby="status_07-nosuchmonthexception_2_1"> The method call will cause other Date objects to become invalid
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-nosuchmonthexception_2_1[]" id="input_07-nosuchmonthexception_2_1_choice_7" class="field-input input-checkbox" value="choice_7"/><label id="07-nosuchmonthexception_2_1-choice_7-label" for="input_07-nosuchmonthexception_2_1_choice_7" class="response-label field-label label-inline" aria-describedby="status_07-nosuchmonthexception_2_1"> The method call will never return
</label>
</div>
<span id="answer_07-nosuchmonthexception_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_07-nosuchmonthexception_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_07-nosuchmonthexception_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="NoSuchMonthException" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_07-nosuchmonthexception" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_07-nosuchmonthexception">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-nosuchmonthexception-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-nosuchmonthexception-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-nosuchmonthexception-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
<div class="vert vert-5" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-suchterriblespecificationsexception">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-suchterriblespecificationsexception" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="True" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_07-suchterriblespecificationsexception" class="problems-wrapper" role="group"
aria-labelledby="07-suchterriblespecificationsexception-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-suchterriblespecificationsexception" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-suchterriblespecificationsexception/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="07-suchterriblespecificationsexception-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-suchterriblespecificationsexception-problem-progress" tabindex="-1">
SuchTerribleSpecificationsException
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-suchterriblespecificationsexception-problem-progress"></div>
<div class="problem">
<div>
<p>Elsewhere in the documentation for <code>Date</code>, it says: "arguments given to methods [...] need not fall within the indicated ranges; for example, a date may be specified as January 32 and is interpreted as meaning February 1".</p>
<p>What looks like a precondition... isn't!</p>
<p>Which of these is an argument against this feature of <code>Date</code>?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_07-suchterriblespecificationsexception_2_1">
<fieldset aria-describedby="status_07-suchterriblespecificationsexception_2_1">
<div class="field">
<input type="radio" name="input_07-suchterriblespecificationsexception_2_1" id="input_07-suchterriblespecificationsexception_2_1_choice_0" class="field-input input-radio" value="choice_0"/><label id="07-suchterriblespecificationsexception_2_1-choice_0-label" for="input_07-suchterriblespecificationsexception_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_07-suchterriblespecificationsexception_2_1"> Don't repeat yourself (DRY)
</label>
</div>
<div class="field">
<input type="radio" name="input_07-suchterriblespecificationsexception_2_1" id="input_07-suchterriblespecificationsexception_2_1_choice_1" class="field-input input-radio" value="choice_1"/><label id="07-suchterriblespecificationsexception_2_1-choice_1-label" for="input_07-suchterriblespecificationsexception_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_07-suchterriblespecificationsexception_2_1"> Fail fast
</label>
</div>
<div class="field">
<input type="radio" name="input_07-suchterriblespecificationsexception_2_1" id="input_07-suchterriblespecificationsexception_2_1_choice_2" class="field-input input-radio" value="choice_2"/><label id="07-suchterriblespecificationsexception_2_1-choice_2-label" for="input_07-suchterriblespecificationsexception_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_07-suchterriblespecificationsexception_2_1"> Groundhog algorithm
</label>
</div>
<div class="field">
<input type="radio" name="input_07-suchterriblespecificationsexception_2_1" id="input_07-suchterriblespecificationsexception_2_1_choice_3" class="field-input input-radio" value="choice_3"/><label id="07-suchterriblespecificationsexception_2_1-choice_3-label" for="input_07-suchterriblespecificationsexception_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_07-suchterriblespecificationsexception_2_1"> Exceptions for special results
</label>
</div>
<div class="field">
<input type="radio" name="input_07-suchterriblespecificationsexception_2_1" id="input_07-suchterriblespecificationsexception_2_1_choice_4" class="field-input input-radio" value="choice_4"/><label id="07-suchterriblespecificationsexception_2_1-choice_4-label" for="input_07-suchterriblespecificationsexception_2_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_07-suchterriblespecificationsexception_2_1"> Preconditions restrict the client
</label>
</div>
<span id="answer_07-suchterriblespecificationsexception_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_07-suchterriblespecificationsexception_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_07-suchterriblespecificationsexception_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="SuchTerribleSpecificationsException" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_07-suchterriblespecificationsexception" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_07-suchterriblespecificationsexception">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-suchterriblespecificationsexception-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-suchterriblespecificationsexception-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-suchterriblespecificationsexception-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@Aliasing_is_What_Makes_Mutable_Types_Risky" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="VerticalStudentView" data-request-token="cec4e5c002f511efa5270afff417eba9">
<h2 class="hd hd-2 unit-title">Aliasing is What Makes Mutable Types Risky</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_043b32f662e2">
<div class="xblock xblock-public_view xblock-public_view-video xmodule_display xmodule_VideoBlock" data-block-type="video" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_043b32f662e2" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Video"}
</script>
<h3 class="hd hd-2">Video</h3>
<div
id="video_video_043b32f662e2"
class="video closed"
data-metadata='{"transcriptLanguages": {"en": "English"}, "captionDataDir": null, "autoAdvance": false, "poster": null, "publishCompletionUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_043b32f662e2/handler/publish_completion", "transcriptLanguage": "en", "showCaptions": "true", "completionEnabled": false, "prioritizeHls": false, "sources": ["https://d2f1egay8yehza.cloudfront.net/MIT600512016-V004700_DTH.mp4", "https://d2f1egay8yehza.cloudfront.net/MIT600512016-V004700/MIT600512016-V004700.m3u8"], "transcriptAvailableTranslationsUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_043b32f662e2/handler/transcript/available_translations", "ytApiUrl": "https://www.youtube.com/iframe_api", "autohideHtml5": false, "start": 0.0, "generalSpeed": 1.0, "recordedYoutubeIsAvailable": true, "speed": null, "end": 0.0, "ytMetadataEndpoint": "", "savedVideoPosition": 0.0, "ytTestTimeout": 1500, "autoplay": false, "saveStateUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_043b32f662e2/handler/xmodule_handler/save_user_state", "saveStateEnabled": false, "transcriptTranslationUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_043b32f662e2/handler/transcript/translation/__lang__", "streams": "1.00:4tHknW01Rs0", "completionPercentage": 0.95, "duration": 293.71, "lmsRootURL": "https://openlearninglibrary.mit.edu"}'
data-bumper-metadata='null'
data-autoadvance-enabled="False"
data-poster='null'
tabindex="-1"
>
<div class="focus_grabber first"></div>
<div class="tc-wrapper">
<div class="video-wrapper">
<span tabindex="0" class="spinner" aria-hidden="false" aria-label="Loading video player"></span>
<span tabindex="-1" class="btn-play fa fa-youtube-play fa-2x is-hidden" aria-hidden="true" aria-label="Play video"></span>
<div class="video-player-pre"></div>
<div class="video-player">
<div id="video_043b32f662e2"></div>
<h4 class="hd hd-4 video-error is-hidden">No playable video sources found.</h4>
<h4 class="hd hd-4 video-hls-error is-hidden">
Your browser does not support this video format. Try using a different browser.
</h4>
</div>
<div class="video-player-post"></div>
<div class="closed-captions"></div>
<div class="video-controls is-hidden">
<div>
<div class="vcr"><div class="vidtime">0:00 / 0:00</div></div>
<div class="secondary-controls"></div>
</div>
</div>
</div>
</div>
<div class="focus_grabber last"></div>
<h3 class="hd hd-4 downloads-heading sr" id="video-download-transcripts_video_043b32f662e2">Downloads and transcripts</h3>
<div class="wrapper-downloads" role="region" aria-labelledby="video-download-transcripts_video_043b32f662e2">
<div class="wrapper-download-transcripts">
<h4 class="hd hd-5">Transcripts</h4>
<ul class="list-download-transcripts">
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_043b32f662e2/handler/transcript/download" data-value="srt">Download SubRip (.srt) file</a>
</li>
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_043b32f662e2/handler/transcript/download" data-value="txt">Download Text (.txt) file</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_72e5d2ce47a7">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_72e5d2ce47a7" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<p>The key lessons from this second example:</p>
<ul>
<li>
<p><strong>Is it safe from bugs?</strong> No -- again we had a latent bug that reared its ugly head.</p>
</li>
<li>
<p><strong>Is it ready for change?</strong> Obviously the mutation of the date object is a change, but that's not the kind of change we're talking about when we say “ready for change.” Instead, the question is whether the code of the program can be easily changed without rewriting a lot of it or introducing bugs. Here we had two apparently independent changes by different programmers that interacted to produce a bad bug.</p>
</li>
</ul>
<p>In both of these examples — the <code>List<Integer></code> example and the <code>Date</code> example — the problems would have been completely avoided if the list and the date had been immutable types. The bugs would have been impossible by design.</p>
<p>In fact, you should never use <code>Date</code>! Use one of the classes from <a href="http://docs.oracle.com/javase/8/docs/api/index.html?java/time/package-summary.html">package <code>java.time</code></a>: <a href="http://docs.oracle.com/javase/8/docs/api/?java/time/LocalDateTime.html"><code>LocalDateTime</code></a>, <a href="http://docs.oracle.com/javase/8/docs/api/?java/time/Instant.html"><code>Instant</code></a>, etc. All guarantee in their specifications that they are <em>immutable</em>.</p>
<p>This example also illustrates why using mutable objects can actually be <em>bad</em> for performance. The simplest solution to this bug, which avoids changing any of the specifications or method signatures, is for <code>startOfSpring()</code> to always return a <em>copy</em> of the groundhog's answer:</p><pre><code class="language-java hljs"> <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Date(groundhogAnswer.getTime());</code></pre>
<p>This pattern is <strong>defensive copying</strong>. We'll see much more of it when we talk about abstract data types. The defensive copy means <code>partyPlanning()</code> can freely stomp all over the returned date without affecting <code>startOfSpring()</code>'s cached date. But defensive copying forces <code>startOfSpring()</code> to do extra work and use extra space for <em>every client</em> — even if 99% of the clients never mutate the date it returns. We may end up with lots of copies of the first day of spring throughout memory. If we used an immutable type instead, then different parts of the program could safely share the same values in memory, so less copying and less memory space is required. Immutability can be more efficient than mutability, because immutable types never need to be defensively copied.</p>
</div>
</div>
<h2 id="aliasing_is_what_makes_mutable_types_risky">Aliasing is what makes mutable types risky</h2>
<div data-outline="aliasing_is_what_makes_mutable_types_risky">
<p>Actually, using mutable objects is just fine if you are using them entirely locally within a method and with only one reference to the object. What led to the problem in the two examples we just looked at was having multiple references, also called <strong>aliases</strong>, for the same mutable object.</p>
<p>Walking through the examples with a snapshot diagram will make this clear, but here's the outline:</p>
<ul>
<li>
<p>In the <code>List</code> example, the same list is pointed to by both <code>list</code> (in <code>sum</code> and <code>sumOfAbsoluteValues</code>) and <code>myData</code> (in <code>main</code>). One programmer (<code>sumOfAbsoluteValues</code>'s) thinks it's ok to modify the list; another programmer (<code>main</code>'s) wants the list to stay the same. Because of the aliases, <code>main</code>'s programmer loses. </p>
</li>
<li>
<p>In the <code>Date</code> example, there are two variable names that point to the <code>Date</code> object: <code>groundhogAnswer</code> and <code>partyDate</code>. These aliases are in completely different parts of the code under the control of different programmers who may have no idea what the other is doing.</p>
</li>
</ul>
<p>Draw snapshot diagrams on paper first, but your real goal should be to develop the snapshot diagram in your head, so you can visualize what's happening in the code.</p>
</div>
<h2 id="specifications_for_mutating_methods">Specifications for mutating methods</h2>
<div data-outline="specifications_for_mutating_methods">
<p>At this point it should be clear that when a method performs mutation, it is crucial to include that mutation in the method's spec, using <a href="/courses/course-v1:MITx+6.005.1x+3T2016/jump_to_id/vertical-what-a-specification-may-talk-about#specifications_for_mutating_methods">the structure we discussed in the previous reading</a>.</p>
<p>(Now we've seen that even when a particular method <em>doesn't</em> mutate an object, that object's mutability can still be a source of bugs.)</p>
<p>Here's an example of a mutating method:</p><pre class="no-markdown">static void sort(List<String> list)
<em>requires</em>: nothing
<em>effects</em>: puts list in sorted order, i.e. list[i] <= list[j]
for all 0 <= i < j < list.size()</pre>
<p>And an example of a method that does not mutate its argument:</p><pre class="no-markdown">static List<String> toLowerCase(List<String> list)
<em>requires</em>: nothing
<em>effects</em>: returns a new list t where t[i] = list[i].toLowerCase()</pre>
<p>If the <em>effects</em> do not explicitly say that an input can be mutated, then in 6.005 we assume mutation of the input is implicitly disallowed. Virtually all programmers would assume the same thing. Surprise mutations lead to terrible bugs.</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@vertical_Questions_8da07ccd89be" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="VerticalStudentView" data-request-token="cec4e5c002f511efa5270afff417eba9">
<h2 class="hd hd-2 unit-title">Questions</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<script src="/assets/courseware/v1/3e6443fb95285d2dc06e8ffc448b9bdf/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism.js"></script>
<script src="/assets/courseware/v1/2ba76f8bdfef4e2d45e31a3dc5208470/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/edx-script-v1.js"></script>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-secret-agent">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-secret-agent" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="True" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_07-secret-agent" class="problems-wrapper" role="group"
aria-labelledby="07-secret-agent-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-secret-agent" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-secret-agent/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="07-secret-agent-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-secret-agent-problem-progress" tabindex="-1">
secret agent
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-secret-agent-problem-progress"></div>
<div class="problem">
<div>
<p>Suppose we have a
<pre>List</pre> that's used in a number of places in our code. that's used in a number of places in our code. that's used in a number of places in our code. that's used in a number of places in our code.</p>
<p>Which of these specifications would be dangerous to use because of <em>mutation</em>? Check all that apply.</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_07-secret-agent_2_1">
<fieldset aria-describedby="status_07-secret-agent_2_1">
<div class="field">
<input type="checkbox" name="input_07-secret-agent_2_1[]" id="input_07-secret-agent_2_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="07-secret-agent_2_1-choice_0-label" for="input_07-secret-agent_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_07-secret-agent_2_1"> 1.
<pre>public static List&lt;String&gt; sort(List&lt; String&gt; list)
Requires: nothing
Effects: modifies list so its elements are sorted lexicographically, and returns list</pre>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-secret-agent_2_1[]" id="input_07-secret-agent_2_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="07-secret-agent_2_1-choice_1-label" for="input_07-secret-agent_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_07-secret-agent_2_1"> 2.
<pre>public static List&lt;String&gt; sort(List&lt; String&gt; list)
Requires: nothing
Effects: returns a copy of list with the elements sorted lexicographically</pre>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-secret-agent_2_1[]" id="input_07-secret-agent_2_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="07-secret-agent_2_1-choice_2-label" for="input_07-secret-agent_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_07-secret-agent_2_1"> 3.
<pre>public List&lt;String&gt; sort(List&lt; String&gt; list)
Requires: nothing
Effects: returns a new List with the elements from list, sorted lexicographically</pre>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-secret-agent_2_1[]" id="input_07-secret-agent_2_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="07-secret-agent_2_1-choice_3-label" for="input_07-secret-agent_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_07-secret-agent_2_1"> 4.
<pre>public List&lt;String&gt; sort(List&lt; String&gt; list)
Requires: nothing
Effects: returns a new List by removing all elements from list and sorting them lexicographically</pre>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-secret-agent_2_1[]" id="input_07-secret-agent_2_1_choice_4" class="field-input input-checkbox" value="choice_4"/><label id="07-secret-agent_2_1-choice_4-label" for="input_07-secret-agent_2_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_07-secret-agent_2_1"> 5.
<pre>public void sort(List&lt; String&gt; list)
Requires: nothing
Effects: modifies list so its elements are sorted lexicographically</pre>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-secret-agent_2_1[]" id="input_07-secret-agent_2_1_choice_5" class="field-input input-checkbox" value="choice_5"/><label id="07-secret-agent_2_1-choice_5-label" for="input_07-secret-agent_2_1_choice_5" class="response-label field-label label-inline" aria-describedby="status_07-secret-agent_2_1"> None of them
</label>
</div>
<span id="answer_07-secret-agent_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_07-secret-agent_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_07-secret-agent_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="secret agent" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_07-secret-agent" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_07-secret-agent">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-secret-agent-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-secret-agent-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-secret-agent-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
<div class="vert vert-2" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-agent-of-change">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-agent-of-change" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="True" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_07-agent-of-change" class="problems-wrapper" role="group"
aria-labelledby="07-agent-of-change-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-agent-of-change" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-agent-of-change/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="07-agent-of-change-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-agent-of-change-problem-progress" tabindex="-1">
agent of change
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-agent-of-change-problem-progress"></div>
<div class="problem">
<div>
<p>Which of those specifications cause <em>aliasing</em> when a client calls the method? Check all that apply.</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_07-agent-of-change_2_1">
<fieldset aria-describedby="status_07-agent-of-change_2_1">
<div class="field">
<input type="checkbox" name="input_07-agent-of-change_2_1[]" id="input_07-agent-of-change_2_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="07-agent-of-change_2_1-choice_0-label" for="input_07-agent-of-change_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_07-agent-of-change_2_1"> 1
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-agent-of-change_2_1[]" id="input_07-agent-of-change_2_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="07-agent-of-change_2_1-choice_1-label" for="input_07-agent-of-change_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_07-agent-of-change_2_1"> 2
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-agent-of-change_2_1[]" id="input_07-agent-of-change_2_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="07-agent-of-change_2_1-choice_2-label" for="input_07-agent-of-change_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_07-agent-of-change_2_1"> 3
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-agent-of-change_2_1[]" id="input_07-agent-of-change_2_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="07-agent-of-change_2_1-choice_3-label" for="input_07-agent-of-change_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_07-agent-of-change_2_1"> 4
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-agent-of-change_2_1[]" id="input_07-agent-of-change_2_1_choice_4" class="field-input input-checkbox" value="choice_4"/><label id="07-agent-of-change_2_1-choice_4-label" for="input_07-agent-of-change_2_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_07-agent-of-change_2_1"> 5
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-agent-of-change_2_1[]" id="input_07-agent-of-change_2_1_choice_5" class="field-input input-checkbox" value="choice_5"/><label id="07-agent-of-change_2_1-choice_5-label" for="input_07-agent-of-change_2_1_choice_5" class="response-label field-label label-inline" aria-describedby="status_07-agent-of-change_2_1"> None of them
</label>
</div>
<span id="answer_07-agent-of-change_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_07-agent-of-change_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_07-agent-of-change_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="agent of change" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_07-agent-of-change" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_07-agent-of-change">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-agent-of-change-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-agent-of-change-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-agent-of-change-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@Iterating_Over_Arrays_and_Lists" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="VerticalStudentView" data-request-token="cec4e5c002f511efa5270afff417eba9">
<h2 class="hd hd-2 unit-title">Iterating Over Arrays and Lists</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_1358c604deb9">
<div class="xblock xblock-public_view xblock-public_view-video xmodule_display xmodule_VideoBlock" data-block-type="video" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_1358c604deb9" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Video"}
</script>
<h3 class="hd hd-2">Video</h3>
<div
id="video_video_1358c604deb9"
class="video closed"
data-metadata='{"transcriptLanguages": {"en": "English"}, "captionDataDir": null, "autoAdvance": false, "poster": null, "publishCompletionUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_1358c604deb9/handler/publish_completion", "transcriptLanguage": "en", "showCaptions": "true", "completionEnabled": false, "prioritizeHls": false, "sources": ["https://d2f1egay8yehza.cloudfront.net/MIT600512016-V005500_DTH.mp4", "https://d2f1egay8yehza.cloudfront.net/MIT600512016-V005500/MIT600512016-V005500.m3u8"], "transcriptAvailableTranslationsUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_1358c604deb9/handler/transcript/available_translations", "ytApiUrl": "https://www.youtube.com/iframe_api", "autohideHtml5": false, "start": 0.0, "generalSpeed": 1.0, "recordedYoutubeIsAvailable": true, "speed": null, "end": 0.0, "ytMetadataEndpoint": "", "savedVideoPosition": 0.0, "ytTestTimeout": 1500, "autoplay": false, "saveStateUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_1358c604deb9/handler/xmodule_handler/save_user_state", "saveStateEnabled": false, "transcriptTranslationUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_1358c604deb9/handler/transcript/translation/__lang__", "streams": "1.00:EBn-Mz-lO2c", "completionPercentage": 0.95, "duration": 418.22, "lmsRootURL": "https://openlearninglibrary.mit.edu"}'
data-bumper-metadata='null'
data-autoadvance-enabled="False"
data-poster='null'
tabindex="-1"
>
<div class="focus_grabber first"></div>
<div class="tc-wrapper">
<div class="video-wrapper">
<span tabindex="0" class="spinner" aria-hidden="false" aria-label="Loading video player"></span>
<span tabindex="-1" class="btn-play fa fa-youtube-play fa-2x is-hidden" aria-hidden="true" aria-label="Play video"></span>
<div class="video-player-pre"></div>
<div class="video-player">
<div id="video_1358c604deb9"></div>
<h4 class="hd hd-4 video-error is-hidden">No playable video sources found.</h4>
<h4 class="hd hd-4 video-hls-error is-hidden">
Your browser does not support this video format. Try using a different browser.
</h4>
</div>
<div class="video-player-post"></div>
<div class="closed-captions"></div>
<div class="video-controls is-hidden">
<div>
<div class="vcr"><div class="vidtime">0:00 / 0:00</div></div>
<div class="secondary-controls"></div>
</div>
</div>
</div>
</div>
<div class="focus_grabber last"></div>
<h3 class="hd hd-4 downloads-heading sr" id="video-download-transcripts_video_1358c604deb9">Downloads and transcripts</h3>
<div class="wrapper-downloads" role="region" aria-labelledby="video-download-transcripts_video_1358c604deb9">
<div class="wrapper-download-transcripts">
<h4 class="hd hd-5">Transcripts</h4>
<ul class="list-download-transcripts">
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_1358c604deb9/handler/transcript/download" data-value="srt">Download SubRip (.srt) file</a>
</li>
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_1358c604deb9/handler/transcript/download" data-value="txt">Download Text (.txt) file</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_1d4eff685ab4">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_1d4eff685ab4" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<h2 id="iterating_over_arrays_and_lists">Iterating over arrays and lists</h2>
<div data-outline="iterating_over_arrays_and_lists">
<p>The next mutable object we're going to look at is an <strong>iterator</strong> — an object that steps through a collection of elements and returns the elements one by one. Iterators are used under the covers in Java when you're using a <code>for (... : ...)</code> loop to step through a <code>List</code> or array. This code:</p><pre class="no-markdown"><code class="java hljs">List<String> list = ...;
<strong class="text-danger"><span class="hljs-keyword">for</span> (String str : list) {</strong>
System.out.println(str);
<strong class="text-danger">}</strong>
</code></pre>
<p>is rewritten by the compiler into something like this:</p><pre class="no-markdown"><code class="java hljs">List<String> list = ...;
<strong class="text-danger">Iterator iter = list.iterator();</strong>
<strong class="text-danger"><span class="hljs-keyword">while</span> (iter.hasNext()) {</strong>
<strong class="text-danger">String str = iter.next();</strong>
System.out.println(str);
<strong class="text-danger">}</strong>
</code></pre>
<p>An iterator has two methods:</p>
<ul>
<li><code>next()</code> returns the next element in the collection.</li>
<li><code>hasNext()</code> tests whether the iterator has reached the end of the collection.</li>
</ul>
<p>Note that the <code>next()</code> method is a <strong>mutator</strong> method that not only returns an element but also advances the iterator so that the subsequent call to <code>next()</code> will return a different element.</p>
<p>You can also look at the <a href="http://docs.oracle.com/javase/8/docs/api/?java/util/Iterator.html">Java API definition of <code>Iterator</code></a>.</p>
<h3 id="myiterator"><code>MyIterator</code></h3>
<div data-outline="myiterator">
<p>To better understand how an iterator works, here's a simple implementation of an iterator for <code>ArrayList<String></code>:</p>
<div class="panel panel-figure pull-right pull-margin"><pre><code class="language-java hljs"><span class="hljs-comment handout-javadoc-comment">/**
* A MyIterator is a mutable object that iterates over
* the elements of an ArrayList<String>, from first to last.
* This is just an example to show how an iterator works.
* In practice, you should use the ArrayList's own iterator
* object, returned by its iterator() method.
*/</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyIterator</span> </span>{
<span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> ArrayList<String> list;
<span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> index;
<span class="hljs-comment">// list[index] is the next element that will be returned</span>
<span class="hljs-comment">// by next()</span>
<span class="hljs-comment">// index == list.size() means no more elements to return</span>
<span class="hljs-comment handout-javadoc-comment">/**
* Make an iterator.
* <span class="hljs-doctag">@param</span> list list to iterate over
*/</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">MyIterator</span><span class="hljs-params">(ArrayList<String> list)</span> </span>{
<span class="hljs-keyword">this</span>.list = list;
<span class="hljs-keyword">this</span>.index = <span class="hljs-number">0</span>;
}
<span class="hljs-comment handout-javadoc-comment">/**
* Test whether the iterator has more elements to return.
* <span class="hljs-doctag">@return</span> true if next() will return another element,
* false if all elements have been returned
*/</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">hasNext</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">return</span> index < list.size();
}
<span class="hljs-comment handout-javadoc-comment">/**
* Get the next element of the list.
* Requires: hasNext() returns true.
* Modifies: this iterator to advance it to the element
* following the returned element.
* <span class="hljs-doctag">@return</span> next element of the list
*/</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">next</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">final</span> String element = list.get(index);
++index;
<span class="hljs-keyword">return</span> element;
}
}</code></pre></div>
<p><code>MyIterator</code> makes use of a few Java language features that we haven't used much up to this point, so we'll explain them briefly here:</p>
<p><a href="http://docs.oracle.com/javase/tutorial/java/javaOO/variables.html"><strong>Instance variables</strong></a>, which are also called fields in Java. Instance variables differ from method parameters and local variables; the instance variables are stored in the object instance and persist for longer than a method call. What are the instance variables of <code>MyIterator</code>?</p>
<p>A <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html"><strong>constructor</strong></a>, which makes a new object instance and initializes its instance variables. Where is the constructor of <code>MyIterator</code>?</p>
<p>The <code>static</code> keyword is missing from <code>MyIterator</code>'s methods, which means they are <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html"><strong>instance methods</strong></a> that must be called on an instance of the object, e.g. <code>iter.next()</code>.</p>
<p>The <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html"><strong><code>this</code> keyword</strong></a> is used at one point to refer to the <strong>instance object</strong>, in particular to refer to an instance variable (<code>this.list</code>). This was done to disambiguate two different variables named <code>list</code> (an instance variable and a constructor parameter). Most of <code>MyIterator</code>'s code refers to instance variables without an explicit <code>this</code>, but this is just a convenient shorthand that Java supports — e.g., <code>index</code> actually means <code>this.index</code>.</p>
<p><strong><code>private</code></strong> is used for the object's internal state and internal helper methods, while <code>public</code> indicates methods and constructors that are intended for clients of the class (<a href="http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html">access control</a>).</p>
<p><strong><code>final</code></strong> is used to indicate which of the object's instance variables can be reassigned and which can't.
<code>index</code> is allowed to change (<code>next()</code> updates it as it steps through the list), but <code>list</code> cannot (the iterator has to keep pointing at the same list for its entire life — if you want to iterate through another list, you're expected to create another iterator object).</p><span class="clearfix"></span>
<div class="panel panel-figure pull-right pull-margin">
<div class="panel-body"><img src="/assets/courseware/v1/89314d550707a6e2fef6b1aecc1de154/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/07-iterator.png" width="400"></div>
</div>
<p>Here's a snapshot diagram showing a typical state for a <code>MyIterator</code> object in action:</p>
<p>Note that we draw the arrow from <code>list</code> with a double line to indicate that it's <em>final</em>. That means the arrow can't change once it's drawn. But the <code>ArrayList</code> object it points to is mutable — elements can be changed within it — and declaring <code>list</code> as final has no effect on that.</p>
<p>Why do iterators exist? There are many kinds of collection data structures (linked lists, maps, hash tables) with different kinds of internal representations. The iterator concept allows a single uniform way to access them all, so that client code is simpler and the collection implementation can change without changing the client code that iterates over it. Most modern languages (including Python, C#, and Ruby) use the notion of an iterator. It's an effective <strong>design pattern</strong> (a well-tested solution to a common design problem). We'll see many other design patterns as we move through the course.</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@vertical_Questions_6cc70ba2e4e1" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="VerticalStudentView" data-request-token="cec4e5c002f511efa5270afff417eba9">
<h2 class="hd hd-2 unit-title">Questions</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<script src="/assets/courseware/v1/3e6443fb95285d2dc06e8ffc448b9bdf/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism.js"></script>
<script src="/assets/courseware/v1/2ba76f8bdfef4e2d45e31a3dc5208470/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/edx-script-v1.js"></script>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-myiterator-next-signature">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-myiterator-next-signature" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="True" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_07-myiterator-next-signature" class="problems-wrapper" role="group"
aria-labelledby="07-myiterator-next-signature-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-myiterator-next-signature" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-myiterator-next-signature/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="2"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="07-myiterator-next-signature-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-myiterator-next-signature-problem-progress" tabindex="-1">
MyIterator.next signature
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-myiterator-next-signature-problem-progress"></div>
<div class="problem">
<div>
<p>This example is one of the first we&#8217;ve seen that uses <em>instance methods</em>. Instance methods operate on an instance of a class, take an implicit <code>this</code> parameter (like the explicit <code>self</code> parameter in Python), and can access instance fields.</p>
<p>Let&#8217;s examine <code>MyIterator</code>&#8217;s <code>next</code> method:</p>
<pre class="code">
public class MyIterator {
private final ArrayList&lt;String&gt; list;
private int index;
...
/**
* Get the next element of the list.
* Requires: hasNext() returns true.
* Modifies: this iterator to advance it to the element
* following the returned element.
* @return next element of the list
*/
public String next() {
final String element = list.get(index);
++index;
return element;
}
}
</pre>
<p>Thinking about <code>next</code> as an operation as defined in <a href="/courses/course-v1:MITx+6.005.1x+3T2016/jump_to_id/vertical-types#types">Static Checking: Types</a>...</p>
<p>What are the types of the input(s) to next? Check all that apply.</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_07-myiterator-next-signature_2_1">
<fieldset aria-describedby="status_07-myiterator-next-signature_2_1">
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-signature_2_1[]" id="input_07-myiterator-next-signature_2_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="07-myiterator-next-signature_2_1-choice_0-label" for="input_07-myiterator-next-signature_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-signature_2_1"> <code>void</code> (there are no inputs)
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-signature_2_1[]" id="input_07-myiterator-next-signature_2_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="07-myiterator-next-signature_2_1-choice_1-label" for="input_07-myiterator-next-signature_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-signature_2_1">
<code>ArrayList</code>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-signature_2_1[]" id="input_07-myiterator-next-signature_2_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="07-myiterator-next-signature_2_1-choice_2-label" for="input_07-myiterator-next-signature_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-signature_2_1">
<code>MyIterator</code>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-signature_2_1[]" id="input_07-myiterator-next-signature_2_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="07-myiterator-next-signature_2_1-choice_3-label" for="input_07-myiterator-next-signature_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-signature_2_1">
<code>String</code>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-signature_2_1[]" id="input_07-myiterator-next-signature_2_1_choice_4" class="field-input input-checkbox" value="choice_4"/><label id="07-myiterator-next-signature_2_1-choice_4-label" for="input_07-myiterator-next-signature_2_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-signature_2_1">
<code>boolean</code>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-signature_2_1[]" id="input_07-myiterator-next-signature_2_1_choice_5" class="field-input input-checkbox" value="choice_5"/><label id="07-myiterator-next-signature_2_1-choice_5-label" for="input_07-myiterator-next-signature_2_1_choice_5" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-signature_2_1">
<code>int</code>
</label>
</div>
<span id="answer_07-myiterator-next-signature_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_07-myiterator-next-signature_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<p>What are the types of the output(s) to next? Check all that apply.</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 2" role="group"><div class="choicegroup capa_inputtype" id="inputtype_07-myiterator-next-signature_3_1">
<fieldset aria-describedby="status_07-myiterator-next-signature_3_1">
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-signature_3_1[]" id="input_07-myiterator-next-signature_3_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="07-myiterator-next-signature_3_1-choice_0-label" for="input_07-myiterator-next-signature_3_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-signature_3_1"> <code>void</code> (there are no inputs)
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-signature_3_1[]" id="input_07-myiterator-next-signature_3_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="07-myiterator-next-signature_3_1-choice_1-label" for="input_07-myiterator-next-signature_3_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-signature_3_1">
<code>ArrayList</code>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-signature_3_1[]" id="input_07-myiterator-next-signature_3_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="07-myiterator-next-signature_3_1-choice_2-label" for="input_07-myiterator-next-signature_3_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-signature_3_1">
<code>MyIterator</code>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-signature_3_1[]" id="input_07-myiterator-next-signature_3_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="07-myiterator-next-signature_3_1-choice_3-label" for="input_07-myiterator-next-signature_3_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-signature_3_1">
<code>String</code>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-signature_3_1[]" id="input_07-myiterator-next-signature_3_1_choice_4" class="field-input input-checkbox" value="choice_4"/><label id="07-myiterator-next-signature_3_1-choice_4-label" for="input_07-myiterator-next-signature_3_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-signature_3_1">
<code>boolean</code>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-signature_3_1[]" id="input_07-myiterator-next-signature_3_1_choice_5" class="field-input input-checkbox" value="choice_5"/><label id="07-myiterator-next-signature_3_1-choice_5-label" for="input_07-myiterator-next-signature_3_1_choice_5" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-signature_3_1">
<code>int</code>
</label>
</div>
<span id="answer_07-myiterator-next-signature_3_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_07-myiterator-next-signature_3_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_07-myiterator-next-signature_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="MyIterator.next signature" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_07-myiterator-next-signature" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_07-myiterator-next-signature">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-myiterator-next-signature-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-myiterator-next-signature-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-myiterator-next-signature-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
<div class="vert vert-2" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-myiterator-next-precondition">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-myiterator-next-precondition" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="True" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_07-myiterator-next-precondition" class="problems-wrapper" role="group"
aria-labelledby="07-myiterator-next-precondition-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-myiterator-next-precondition" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-myiterator-next-precondition/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="2"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="07-myiterator-next-precondition-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-myiterator-next-precondition-problem-progress" tabindex="-1">
MyIterator.next precondition
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-myiterator-next-precondition-problem-progress"></div>
<div class="problem">
<div>
<p><code>next</code> has the precondition <code>requires: hasNext() returns true</code>.</p>
<p>Which input(s) to <code>next</code> are constrained by the precondition? Check all that apply.</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_07-myiterator-next-precondition_2_1">
<fieldset aria-describedby="status_07-myiterator-next-precondition_2_1">
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-precondition_2_1[]" id="input_07-myiterator-next-precondition_2_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="07-myiterator-next-precondition_2_1-choice_0-label" for="input_07-myiterator-next-precondition_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-precondition_2_1">
<em>none of them</em>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-precondition_2_1[]" id="input_07-myiterator-next-precondition_2_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="07-myiterator-next-precondition_2_1-choice_1-label" for="input_07-myiterator-next-precondition_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-precondition_2_1">
<code>this</code>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-precondition_2_1[]" id="input_07-myiterator-next-precondition_2_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="07-myiterator-next-precondition_2_1-choice_2-label" for="input_07-myiterator-next-precondition_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-precondition_2_1">
<code>hasNext</code>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-precondition_2_1[]" id="input_07-myiterator-next-precondition_2_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="07-myiterator-next-precondition_2_1-choice_3-label" for="input_07-myiterator-next-precondition_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-precondition_2_1">
<code>elem</code>
</label>
</div>
<span id="answer_07-myiterator-next-precondition_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_07-myiterator-next-precondition_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<p>When the precondition isn&#8217;t satisfied, the implementation is free to do anything. So:</p>
<p>What does this particular implementation do when the precondition is not satisfied?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 2" role="group"><div class="choicegroup capa_inputtype" id="inputtype_07-myiterator-next-precondition_3_1">
<fieldset aria-describedby="status_07-myiterator-next-precondition_3_1">
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-precondition_3_1[]" id="input_07-myiterator-next-precondition_3_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="07-myiterator-next-precondition_3_1-choice_0-label" for="input_07-myiterator-next-precondition_3_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-precondition_3_1"> return <code>null</code>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-precondition_3_1[]" id="input_07-myiterator-next-precondition_3_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="07-myiterator-next-precondition_3_1-choice_1-label" for="input_07-myiterator-next-precondition_3_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-precondition_3_1"> return some other element of the list
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-precondition_3_1[]" id="input_07-myiterator-next-precondition_3_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="07-myiterator-next-precondition_3_1-choice_2-label" for="input_07-myiterator-next-precondition_3_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-precondition_3_1"> throw a checked exception
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-precondition_3_1[]" id="input_07-myiterator-next-precondition_3_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="07-myiterator-next-precondition_3_1-choice_3-label" for="input_07-myiterator-next-precondition_3_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-precondition_3_1"> throw an unchecked exception
</label>
</div>
<span id="answer_07-myiterator-next-precondition_3_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_07-myiterator-next-precondition_3_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_07-myiterator-next-precondition_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="MyIterator.next precondition" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_07-myiterator-next-precondition" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_07-myiterator-next-precondition">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-myiterator-next-precondition-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-myiterator-next-precondition-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-myiterator-next-precondition-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
<div class="vert vert-3" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-myiterator-next-postcondition">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-myiterator-next-postcondition" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="True" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_07-myiterator-next-postcondition" class="problems-wrapper" role="group"
aria-labelledby="07-myiterator-next-postcondition-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-myiterator-next-postcondition" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-myiterator-next-postcondition/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="2"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="07-myiterator-next-postcondition-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-myiterator-next-postcondition-problem-progress" tabindex="-1">
MyIterator.next postcondition
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-myiterator-next-postcondition-problem-progress"></div>
<div class="problem">
<div>
<p>Part of the postcondition of <code>next</code> is: <code>@return next element of the list.</code></p>
<p>Which output(s) from <code>next</code> are constrained by that postcondition? Check all that apply.</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_07-myiterator-next-postcondition_2_1">
<fieldset aria-describedby="status_07-myiterator-next-postcondition_2_1">
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-postcondition_2_1[]" id="input_07-myiterator-next-postcondition_2_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="07-myiterator-next-postcondition_2_1-choice_0-label" for="input_07-myiterator-next-postcondition_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-postcondition_2_1">
<em>none of them</em>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-postcondition_2_1[]" id="input_07-myiterator-next-postcondition_2_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="07-myiterator-next-postcondition_2_1-choice_1-label" for="input_07-myiterator-next-postcondition_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-postcondition_2_1">
<code>this</code>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-postcondition_2_1[]" id="input_07-myiterator-next-postcondition_2_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="07-myiterator-next-postcondition_2_1-choice_2-label" for="input_07-myiterator-next-postcondition_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-postcondition_2_1">
<code>hasNext</code>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-postcondition_2_1[]" id="input_07-myiterator-next-postcondition_2_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="07-myiterator-next-postcondition_2_1-choice_3-label" for="input_07-myiterator-next-postcondition_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-postcondition_2_1"> the return value
</label>
</div>
<span id="answer_07-myiterator-next-postcondition_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_07-myiterator-next-postcondition_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<p>Another part of the postcondition of <code>next</code> is <code>modifies: this iterator to advance it to the element following the returned element.</code></p>
<p>What is (are) constrained by that postcondition? Check all that apply.</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 2" role="group"><div class="choicegroup capa_inputtype" id="inputtype_07-myiterator-next-postcondition_3_1">
<fieldset aria-describedby="status_07-myiterator-next-postcondition_3_1">
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-postcondition_3_1[]" id="input_07-myiterator-next-postcondition_3_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="07-myiterator-next-postcondition_3_1-choice_0-label" for="input_07-myiterator-next-postcondition_3_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-postcondition_3_1">
<em>nothing</em>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-postcondition_3_1[]" id="input_07-myiterator-next-postcondition_3_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="07-myiterator-next-postcondition_3_1-choice_1-label" for="input_07-myiterator-next-postcondition_3_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-postcondition_3_1">
<code>this</code>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-postcondition_3_1[]" id="input_07-myiterator-next-postcondition_3_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="07-myiterator-next-postcondition_3_1-choice_2-label" for="input_07-myiterator-next-postcondition_3_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-postcondition_3_1">
<code>hasNext</code>
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-myiterator-next-postcondition_3_1[]" id="input_07-myiterator-next-postcondition_3_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="07-myiterator-next-postcondition_3_1-choice_3-label" for="input_07-myiterator-next-postcondition_3_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_07-myiterator-next-postcondition_3_1"> the return value
</label>
</div>
<span id="answer_07-myiterator-next-postcondition_3_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_07-myiterator-next-postcondition_3_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_07-myiterator-next-postcondition_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="MyIterator.next postcondition" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_07-myiterator-next-postcondition" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_07-myiterator-next-postcondition">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-myiterator-next-postcondition-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-myiterator-next-postcondition-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-myiterator-next-postcondition-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@Mutation_Undermines_an_Iterator" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="VerticalStudentView" data-request-token="cec4e5c002f511efa5270afff417eba9">
<h2 class="hd hd-2 unit-title">Mutation Undermines an Iterator</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_01fe5fc26b50">
<div class="xblock xblock-public_view xblock-public_view-video xmodule_display xmodule_VideoBlock" data-block-type="video" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_01fe5fc26b50" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Video"}
</script>
<h3 class="hd hd-2">Video</h3>
<div
id="video_video_01fe5fc26b50"
class="video closed"
data-metadata='{"transcriptLanguages": {"en": "English"}, "captionDataDir": null, "autoAdvance": false, "poster": null, "publishCompletionUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_01fe5fc26b50/handler/publish_completion", "transcriptLanguage": "en", "showCaptions": "true", "completionEnabled": false, "prioritizeHls": false, "sources": ["https://d2f1egay8yehza.cloudfront.net/MIT600512016-V005400_DTH.mp4", "https://d2f1egay8yehza.cloudfront.net/MIT600512016-V005400/MIT600512016-V005400.m3u8"], "transcriptAvailableTranslationsUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_01fe5fc26b50/handler/transcript/available_translations", "ytApiUrl": "https://www.youtube.com/iframe_api", "autohideHtml5": false, "start": 0.0, "generalSpeed": 1.0, "recordedYoutubeIsAvailable": true, "speed": null, "end": 0.0, "ytMetadataEndpoint": "", "savedVideoPosition": 0.0, "ytTestTimeout": 1500, "autoplay": false, "saveStateUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_01fe5fc26b50/handler/xmodule_handler/save_user_state", "saveStateEnabled": false, "transcriptTranslationUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_01fe5fc26b50/handler/transcript/translation/__lang__", "streams": "1.00:m9TSB-7lwvs", "completionPercentage": 0.95, "duration": 94.58, "lmsRootURL": "https://openlearninglibrary.mit.edu"}'
data-bumper-metadata='null'
data-autoadvance-enabled="False"
data-poster='null'
tabindex="-1"
>
<div class="focus_grabber first"></div>
<div class="tc-wrapper">
<div class="video-wrapper">
<span tabindex="0" class="spinner" aria-hidden="false" aria-label="Loading video player"></span>
<span tabindex="-1" class="btn-play fa fa-youtube-play fa-2x is-hidden" aria-hidden="true" aria-label="Play video"></span>
<div class="video-player-pre"></div>
<div class="video-player">
<div id="video_01fe5fc26b50"></div>
<h4 class="hd hd-4 video-error is-hidden">No playable video sources found.</h4>
<h4 class="hd hd-4 video-hls-error is-hidden">
Your browser does not support this video format. Try using a different browser.
</h4>
</div>
<div class="video-player-post"></div>
<div class="closed-captions"></div>
<div class="video-controls is-hidden">
<div>
<div class="vcr"><div class="vidtime">0:00 / 0:00</div></div>
<div class="secondary-controls"></div>
</div>
</div>
</div>
</div>
<div class="focus_grabber last"></div>
<h3 class="hd hd-4 downloads-heading sr" id="video-download-transcripts_video_01fe5fc26b50">Downloads and transcripts</h3>
<div class="wrapper-downloads" role="region" aria-labelledby="video-download-transcripts_video_01fe5fc26b50">
<div class="wrapper-download-transcripts">
<h4 class="hd hd-5">Transcripts</h4>
<ul class="list-download-transcripts">
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_01fe5fc26b50/handler/transcript/download" data-value="srt">Download SubRip (.srt) file</a>
</li>
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_01fe5fc26b50/handler/transcript/download" data-value="txt">Download Text (.txt) file</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_1fd538678164">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_1fd538678164" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<h2 id="mutation_undermines_an_iterator">Mutation undermines an iterator</h2>
<div data-outline="mutation_undermines_an_iterator">
<p>Let's try using our iterator for a simple job. Suppose we have a list of MIT subjects represented as strings, like <code>["6.005", "8.03", "9.00"]</code>. We want a method <code>dropCourse6</code> that will delete the Course 6 subjects from the list, leaving the other subjects behind. Following good practices, we first write the spec:</p><pre><code class="language-java hljs"><span class="hljs-comment handout-javadoc-comment">/**
* Drop all subjects that are from Course 6.
* Modifies subjects list by removing subjects that start with "6."
*
* <span class="hljs-doctag">@param</span> subjects list of MIT subject numbers
*/</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">dropCourse6</span><span class="hljs-params">(ArrayList<String> subjects)</span></span></code></pre>
<p>Note that <code>dropCourse6</code> has a clause in its contract that warns the client that its list argument will be mutated.</p>
<p>Next, following test-first programming, we devise a testing strategy that partitions the input space and choose test cases to cover that partition:</p><pre><code class="hljs java">// Testing strategy:
// subjects.size: <span class="hljs-operator">0, <span class="hljs-number">1</span>, <span class="hljs-keyword">n</span>
// <span class="hljs-keyword">contents</span>: <span class="hljs-keyword">no</span> <span class="hljs-number">6.</span>xx, one <span class="hljs-number">6.</span>xx, all <span class="hljs-number">6.</span>xx
// <span class="hljs-keyword">position</span>: <span class="hljs-number">6.</span>xx <span class="hljs-keyword">at</span> <span class="hljs-keyword">start</span>, <span class="hljs-number">6.</span>xx <span class="hljs-keyword">in</span> middle, <span class="hljs-number">6.</span>xx <span class="hljs-keyword">at</span> <span class="hljs-keyword">end</span>
// <span class="hljs-keyword">Test</span> cases:
// [] => []
// [<span class="hljs-string">"8.03"</span>] => [<span class="hljs-string">"8.03"</span>]
// [<span class="hljs-string">"14.03"</span>, <span class="hljs-string">"9.00"</span>, <span class="hljs-string">"21L.005"</span>] => [<span class="hljs-string">"14.03"</span>, <span class="hljs-string">"9.00"</span>, <span class="hljs-string">"21L.005"</span>]
// [<span class="hljs-string">"2.001"</span>, <span class="hljs-string">"6.01"</span>, <span class="hljs-string">"18.03"</span>] => [<span class="hljs-string">"2.001"</span>, <span class="hljs-string">"18.03"</span>]
// [<span class="hljs-string">"6.045"</span>, <span class="hljs-string">"6.005"</span>, <span class="hljs-string">"6.813"</span>] => []
</span></code></pre>
<p>Finally, we implement it:</p><pre><code class="language-java hljs"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">dropCourse6</span><span class="hljs-params">(ArrayList<String> subjects)</span> </span>{
MyIterator iter = <span class="hljs-keyword">new</span> MyIterator(subjects);
<span class="hljs-keyword">while</span> (iter.hasNext()) {
String subject = iter.next();
<span class="hljs-keyword">if</span> (subject.startsWith(<span class="hljs-string">"6."</span>)) {
subjects.remove(subject);
}
}
}</code></pre>
<p>Now we run our test cases, and they work! … almost. The last test case fails:</p><pre><code class="hljs bash">// dropCourse6([<span class="hljs-string">"6.045"</span>, <span class="hljs-string">"6.005"</span>, <span class="hljs-string">"6.813"</span>])
// expected [], actual [<span class="hljs-string">"6.005"</span>]
</code></pre>
<p>We got the wrong answer: <code>dropCourse6</code> left a course behind in the list! Why? Trace through what happens. It will help to use a snapshot diagram showing the <code>MyIterator</code> object and the <code>ArrayList</code> object and update the diagram while you work through the code.</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@vertical_Questions_af904cd6450d" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="VerticalStudentView" data-request-token="cec4e5c002f511efa5270afff417eba9">
<h2 class="hd hd-2 unit-title">Questions</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<script src="/assets/courseware/v1/3e6443fb95285d2dc06e8ffc448b9bdf/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism.js"></script>
<script src="/assets/courseware/v1/2ba76f8bdfef4e2d45e31a3dc5208470/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/edx-script-v1.js"></script>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-undroppable">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-undroppable" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="True" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_07-undroppable" class="problems-wrapper" role="group"
aria-labelledby="07-undroppable-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-undroppable" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-undroppable/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="07-undroppable-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-undroppable-problem-progress" tabindex="-1">
undroppable
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-undroppable-problem-progress"></div>
<div class="problem">
<div>
<pre class="code">
public static void dropCourse6(ArrayList&lt;String&gt; subjects) {
MyIterator iter = new MyIterator(subjects);
while (iter.hasNext()) {
String subject = iter.next();
if (subject.startsWith("6.")) {
subjects.remove(subject);
}
}
}
</pre>
<pre class="code">
// dropCourse6(["6.045", "6.005", "6.813"])
// expected [], actual ["6.005"]
</pre>
<p>Before you go on to the next problem, draw your own snapshot diagram to illustrate the bug.</p>
<center>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<em>(feel free to use this space and a magic marker)</em>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
</center>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_07-undroppable_2_1">
<fieldset aria-describedby="status_07-undroppable_2_1">
<legend id="07-undroppable_2_1-legend" class="response-fieldset-legend field-group-hd">Did you draw it?</legend>
<div class="field">
<input type="radio" name="input_07-undroppable_2_1" id="input_07-undroppable_2_1_choice_0" class="field-input input-radio" value="choice_0"/><label id="07-undroppable_2_1-choice_0-label" for="input_07-undroppable_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_07-undroppable_2_1"> Yes
</label>
</div>
<span id="answer_07-undroppable_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_07-undroppable_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_07-undroppable_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="undroppable" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_07-undroppable" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_07-undroppable">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-undroppable-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-undroppable-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-undroppable-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
<div class="vert vert-2" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-drop-skip-and-roll">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-drop-skip-and-roll" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="True" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_07-drop-skip-and-roll" class="problems-wrapper" role="group"
aria-labelledby="07-drop-skip-and-roll-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-drop-skip-and-roll" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-drop-skip-and-roll/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="07-drop-skip-and-roll-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-drop-skip-and-roll-problem-progress" tabindex="-1">
drop, skip, and roll
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-drop-skip-and-roll-problem-progress"></div>
<div class="problem">
<div>
<p>Which of these snapshot diagrams illustrates the same underlying bug from the previous exercise?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_07-drop-skip-and-roll_2_1">
<fieldset aria-describedby="status_07-drop-skip-and-roll_2_1">
<div class="field">
<input type="radio" name="input_07-drop-skip-and-roll_2_1" id="input_07-drop-skip-and-roll_2_1_choice_0" class="field-input input-radio" value="choice_0"/><label id="07-drop-skip-and-roll_2_1-choice_0-label" for="input_07-drop-skip-and-roll_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_07-drop-skip-and-roll_2_1">
<img src="/assets/courseware/v1/cc4fc2555868368d598542bc62c00777/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/07-iterator1.png" width="400"/>
</label>
</div>
<div class="field">
<input type="radio" name="input_07-drop-skip-and-roll_2_1" id="input_07-drop-skip-and-roll_2_1_choice_1" class="field-input input-radio" value="choice_1"/><label id="07-drop-skip-and-roll_2_1-choice_1-label" for="input_07-drop-skip-and-roll_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_07-drop-skip-and-roll_2_1">
<img src="/assets/courseware/v1/d3176046907c1b0aa0a5612e2838d428/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/07-iterator2.png" width="400"/>
</label>
</div>
<div class="field">
<input type="radio" name="input_07-drop-skip-and-roll_2_1" id="input_07-drop-skip-and-roll_2_1_choice_2" class="field-input input-radio" value="choice_2"/><label id="07-drop-skip-and-roll_2_1-choice_2-label" for="input_07-drop-skip-and-roll_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_07-drop-skip-and-roll_2_1">
<img src="/assets/courseware/v1/82318eb71026009ce6115768bd45807c/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/07-iterator3.png" width="400"/>
</label>
</div>
<div class="field">
<input type="radio" name="input_07-drop-skip-and-roll_2_1" id="input_07-drop-skip-and-roll_2_1_choice_3" class="field-input input-radio" value="choice_3"/><label id="07-drop-skip-and-roll_2_1-choice_3-label" for="input_07-drop-skip-and-roll_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_07-drop-skip-and-roll_2_1">
<img src="/assets/courseware/v1/8b2199ee6b76d1a4ab1d53947b991628/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/07-iterator4.png" width="400"/>
</label>
</div>
<div class="field">
<input type="radio" name="input_07-drop-skip-and-roll_2_1" id="input_07-drop-skip-and-roll_2_1_choice_4" class="field-input input-radio" value="choice_4"/><label id="07-drop-skip-and-roll_2_1-choice_4-label" for="input_07-drop-skip-and-roll_2_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_07-drop-skip-and-roll_2_1">
<img src="/assets/courseware/v1/adff7476a13b5ff7c0e7bb3539e990e9/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/07-iterator5.png" width="400"/>
</label>
</div>
<span id="answer_07-drop-skip-and-roll_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_07-drop-skip-and-roll_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_07-drop-skip-and-roll_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="drop, skip, and roll" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_07-drop-skip-and-roll" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_07-drop-skip-and-roll">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-drop-skip-and-roll-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-drop-skip-and-roll-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-drop-skip-and-roll-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@vertical-mutation-and-contracts" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="VerticalStudentView" data-request-token="cec4e5c002f511efa5270afff417eba9">
<h2 class="hd hd-2 unit-title">Mutation and Contracts</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_fb6d2347f154">
<div class="xblock xblock-public_view xblock-public_view-video xmodule_display xmodule_VideoBlock" data-block-type="video" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_fb6d2347f154" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Video"}
</script>
<h3 class="hd hd-2">Video</h3>
<div
id="video_video_fb6d2347f154"
class="video closed"
data-metadata='{"transcriptLanguages": {"en": "English"}, "captionDataDir": null, "autoAdvance": false, "poster": null, "publishCompletionUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_fb6d2347f154/handler/publish_completion", "transcriptLanguage": "en", "showCaptions": "true", "completionEnabled": false, "prioritizeHls": false, "sources": ["https://d2f1egay8yehza.cloudfront.net/MIT600512016-V005200_DTH.mp4", "https://d2f1egay8yehza.cloudfront.net/MIT600512016-V005200/MIT600512016-V005200.m3u8"], "transcriptAvailableTranslationsUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_fb6d2347f154/handler/transcript/available_translations", "ytApiUrl": "https://www.youtube.com/iframe_api", "autohideHtml5": false, "start": 0.0, "generalSpeed": 1.0, "recordedYoutubeIsAvailable": true, "speed": null, "end": 0.0, "ytMetadataEndpoint": "", "savedVideoPosition": 0.0, "ytTestTimeout": 1500, "autoplay": false, "saveStateUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_fb6d2347f154/handler/xmodule_handler/save_user_state", "saveStateEnabled": false, "transcriptTranslationUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_fb6d2347f154/handler/transcript/translation/__lang__", "streams": "1.00:MhRm1JAHlu4", "completionPercentage": 0.95, "duration": 689.59, "lmsRootURL": "https://openlearninglibrary.mit.edu"}'
data-bumper-metadata='null'
data-autoadvance-enabled="False"
data-poster='null'
tabindex="-1"
>
<div class="focus_grabber first"></div>
<div class="tc-wrapper">
<div class="video-wrapper">
<span tabindex="0" class="spinner" aria-hidden="false" aria-label="Loading video player"></span>
<span tabindex="-1" class="btn-play fa fa-youtube-play fa-2x is-hidden" aria-hidden="true" aria-label="Play video"></span>
<div class="video-player-pre"></div>
<div class="video-player">
<div id="video_fb6d2347f154"></div>
<h4 class="hd hd-4 video-error is-hidden">No playable video sources found.</h4>
<h4 class="hd hd-4 video-hls-error is-hidden">
Your browser does not support this video format. Try using a different browser.
</h4>
</div>
<div class="video-player-post"></div>
<div class="closed-captions"></div>
<div class="video-controls is-hidden">
<div>
<div class="vcr"><div class="vidtime">0:00 / 0:00</div></div>
<div class="secondary-controls"></div>
</div>
</div>
</div>
</div>
<div class="focus_grabber last"></div>
<h3 class="hd hd-4 downloads-heading sr" id="video-download-transcripts_video_fb6d2347f154">Downloads and transcripts</h3>
<div class="wrapper-downloads" role="region" aria-labelledby="video-download-transcripts_video_fb6d2347f154">
<div class="wrapper-download-transcripts">
<h4 class="hd hd-5">Transcripts</h4>
<ul class="list-download-transcripts">
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_fb6d2347f154/handler/transcript/download" data-value="srt">Download SubRip (.srt) file</a>
</li>
<li class="transcript-option">
<a class="btn btn-link" href="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_fb6d2347f154/handler/transcript/download" data-value="txt">Download Text (.txt) file</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fe7d28f77d1b">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fe7d28f77d1b" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<p>So we've seen that <code>MyIterator</code> can be broken by mutating the underlying list of strings while you're iterating over it. But this isn't just a bug in our <code>MyIterator</code>. The built-in iterator in <code>ArrayList</code> suffers from the same problem and so does the <code>for</code> loop that's syntactic sugar for it. The problem just has a different symptom. If you used this code instead:</p><pre><code class="language-java hljs"><span class="hljs-keyword">for</span> (String subject : subjects) {
<span class="hljs-keyword">if</span> (subject.startsWith(<span class="hljs-string">"6."</span>)) {
subjects.remove(subject);
}
}</code></pre>
<p>then you'll get a <a href="http://docs.oracle.com/javase/8/docs/api/?java/util/ConcurrentModificationException.html"><code>ConcurrentModificationException</code></a>. The built-in iterator detects that you're changing the list under its feet and cries foul. (How do you think it does that?)</p>
<p>How can you fix this problem? One way is to use the <code>remove()</code> method of <code>Iterator</code> so that the iterator adjusts its index appropriately:</p><pre class="no-markdown"><code class="java hljs">Iterator iter = subjects.iterator();
<span class="hljs-keyword">while</span> (iter.hasNext()) {
String subject = iter.next();
<span class="hljs-keyword">if</span> (subject.startsWith(<span class="hljs-string">"6."</span>)) {
<strong class="text-danger">iter.remove();</strong>
}
}
</code></pre>
<p>This is actually more efficient as well, it turns out, because <code>iter.remove()</code> already knows where the element it should remove is, while <code>subjects.remove()</code> had to search for it again.</p>
<p>But this doesn't fix the whole problem. What if there are other <code>Iterator</code>s currently active over the same list? They won't all be informed!</p>
<h2 id="mutation_and_contracts">Mutation and contracts</h2>
<div data-outline="mutation_and_contracts">
<h3 id="mutable_objects_can_make_simple_contracts_very_complex">Mutable objects can make simple contracts very complex</h3>
<div data-outline="mutable_objects_can_make_simple_contracts_very_complex">
<p>This is a fundamental issue with mutable data structures. Multiple references to the same mutable object (also called <strong>aliases</strong> for the object) may mean that multiple places in your program — possibly widely separated — are relying on that object to remain consistent.</p>
<p>To put it in terms of specifications, contracts can't be enforced in just one place anymore, e.g. between the client of a class and the implementer of a class. Contracts involving mutable objects now depend on the good behavior of everyone who has a reference to the mutable object.</p>
<p>As a symptom of this non-local contract phenomenon, consider the Java collections classes, which are normally documented with very clear contracts on the client and implementer of a class. Try to find where it documents the crucial requirement on the client that we've just discovered — that you can't modify a collection while you're iterating over it. Who takes responsibility for it?
<a href="http://docs.oracle.com/javase/8/docs/api/?java/util/Iterator.html"><code>Iterator</code></a>?
<a href="http://docs.oracle.com/javase/8/docs/api/?java/util/List.html"><code>List</code></a>?
<a href="http://docs.oracle.com/javase/8/docs/api/?java/util/Collection.html"><code>Collection</code></a>? Can you find it?</p>
<p>The need to reason about global properties like this make it much harder to understand, and be confident in the correctness of, programs with mutable data structures. We still have to do it — for performance and convenience — but we pay a big cost in bug safety for doing so. </p>
</div>
<h3 id="mutable_objects_reduce_changeability">Mutable objects reduce changeability</h3>
<div data-outline="mutable_objects_reduce_changeability">
<p>Mutable objects make the contract between a client and an implementer more complicated and reduce the freedom of the client and implementer to change. In other words, using <em>objects</em> that are allowed to change makes the <em>code</em> harder to change. Here's an example to illustrate the point.</p>
<p>The crux of our example will be the specification for this method, which looks up a username in MIT's database and returns the user's 9-digit identifier:</p>
<div class="pull-margin"><pre><code class="language-java hljs"><span class="hljs-comment handout-javadoc-comment">/**
* <span class="hljs-doctag">@param</span> username username of person to look up
* <span class="hljs-doctag">@return</span> the 9-digit MIT identifier for username.
* <span class="hljs-doctag">@throws</span> NoSuchUserException if nobody with username is in MIT's database
*/</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">char</span>[] getMitId(String username) <span class="hljs-keyword">throws</span> NoSuchUserException {
<span class="hljs-comment">// ... look up username in MIT's database and return the 9-digit ID</span>
}</code></pre></div>
<p>A reasonable specification. Now suppose we have a client using this method to print out a user's identifier:</p><pre><code class="language-java hljs"><span class="hljs-keyword">char</span>[] id = getMitId(<span class="hljs-string">"bitdiddle"</span>);
System.out.println(id);</code></pre>
<p><strong>Now both the client and the implementor separately decide to make a change.</strong> The client is worried about the user's privacy and decides to obscure the first 5 digits of the id:</p><pre><code class="language-java hljs"><span class="hljs-keyword">char</span>[] id = getMitId(<span class="hljs-string">"bitdiddle"</span>);
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < <span class="hljs-number">5</span>; ++i) {
id[i] = <span class="hljs-string">'*'</span>;
}
System.out.println(id);</code></pre>
<p>The implementer is worried about the speed and load on the database, so the implementer introduces a cache that remembers usernames that have been looked up:</p>
<div class="pull-margin"><pre><code class="language-java hljs"><span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Map<String, <span class="hljs-keyword">char</span>[]> cache = <span class="hljs-keyword">new</span> HashMap<String, <span class="hljs-keyword">char</span>[]>();
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">char</span>[] getMitId(String username) <span class="hljs-keyword">throws</span> NoSuchUserException {
<span class="hljs-comment">// see if it's in the cache already</span>
<span class="hljs-keyword">if</span> (cache.containsKey(username)) {
<span class="hljs-keyword">return</span> cache.get(username);
}
<span class="hljs-comment">// ... look up username in MIT's database ...</span>
<span class="hljs-comment">// store it in the cache for future lookups</span>
cache.put(username, id);
<span class="hljs-keyword">return</span> id;
}</code></pre></div>
<p>These two changes have created a subtle bug. When the client looks up <code>"bitdiddle"</code> and gets back a char array, now both the client and the implementer's cache are pointing to the <em>same</em> char array. The array is aliased. That means that the client's obscuring code is actually overwriting the identifier in the cache, so future calls to <code>getMidId("bitdiddle")</code> will not return the full 9-digit number, like “928432033”, but instead the obscured version “*****2033”.</p>
<p><strong>Sharing a mutable object complicates a contract</strong>. If this contract failure went to software engineering court, it would be contentious. Who's to blame here? Was the client obliged not to modify the object it got back? Was the implementer obliged not to hold on to the object that it returned?</p>
<p>Here's one way we could have clarified the spec:</p><pre class="pull-margin"><p>public static char[] getMitId(String username) throws NoSuchUserException
<em>requires</em>: nothing
<em>effects</em>: returns an array containing the 9-digit MIT identifier of username,
or throws NoSuchUserException if nobody with username is in MIT's
database. <span class="yellow-highlight">Caller may never modify the returned array.</span></p></pre>
<p><strong>This is a bad way to do it</strong>. The problem with this approach is that it means the contract has to be in force for the entire rest of the program. It's a lifetime contract! The other contracts we wrote were much narrower in scope; you could think about the precondition just before the call was made, and the postcondition just after, and you didn't have to reason about what would happen for the rest of time. </p>
<p>Here's a spec with a similar problem:</p><pre class="pull-margin"><p>public static char[] getMitId(String username) throws NoSuchUserException
<em>requires</em>: nothing
<em>effects</em>: returns <span class="yellow-highlight">a new array</span> containing the 9-digit MIT identifier of username,
or throws NoSuchUserException if nobody with username is in MIT's
database.</p></pre>
<p><strong>This doesn't entirely fix the problem either</strong>. This spec at least says that the array has to be fresh. But does it keep the implementer from holding an alias to that new array? Does it keep the implementer from changing that array or reusing it in the future for something else?</p>
<p>Here's a much better spec:</p><pre class="pull-margin"><p>public static <span class="yellow-highlight">String</span> getMitId(String username) throws NoSuchUserException
<em>requires</em>: nothing
<em>effects</em>: returns the 9-digit MIT identifier of username, or throws
NoSuchUserException if nobody with username is in MIT's database.</p></pre>
<p>The immutable String return value provides a <em>guarantee</em> that the client and the implementer will never step on each other the way they could with char arrays. It doesn't depend on a programmer reading the spec comment carefully. String is <em>immutable</em>. Not only that, but this approach (unlike the previous one) gives the implementer the freedom to introduce a cache — a performance improvement.</p>
</div>
</div>
<h2 id="useful_immutable_types">Useful immutable types</h2>
<div data-outline="useful_immutable_types">
<p>Since immutable types avoid so many pitfalls, let's enumerate some commonly-used immutable types in the Java API:</p>
<ul>
<li>
<p>The primitive types and primitive wrappers are all immutable. If you need to compute with large numbers, <a href="http://docs.oracle.com/javase/8/docs/api/?java/math/BigInteger.html"><code>BigInteger</code></a> and <a href="http://docs.oracle.com/javase/8/docs/api/?java/math/BigDecimal.html"><code>BigDecimal</code></a> are immutable.</p>
</li>
<li>
<p>Don't use mutable <code>Date</code>s but instead use the appropriate immutable type from <a href="http://docs.oracle.com/javase/8/docs/api/index.html?java/time/package-summary.html"><code>java.time</code></a> based on the granularity of timekeeping you need.</p>
</li>
<li>
<p>The usual implementations of Java's collections types — <code>List</code>, <code>Set</code>, <code>Map</code> — are all mutable: <code>ArrayList</code>, <code>HashMap</code>, etc. The <a href="http://docs.oracle.com/javase/8/docs/api/?java/util/Collections.html"><code>Collections</code></a> utility class has methods for obtaining <em>unmodifiable views</em> of these mutable collections:</p>
<ul>
<li><code><a href="https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#unmodifiableList-java.util.List-">Collections.unmodifiableList</a></code></li>
<li><code><a href="https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#unmodifiableSet-java.util.Set-">Collections.unmodifiableSet</a></code></li>
<li><code><a href="https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#unmodifiableMap-java.util.Map--">Collections.unmodifiableMap</a></code></li>
</ul>
<p>You can think of the unmodifiable view as a wrapper around the underlying list/set/map. A client who has a reference to the wrapper and tries to perform mutations — <code>add</code>, <code>remove</code>, <code>put</code>, etc. — will trigger an <a href="http://docs.oracle.com/javase/8/docs/api/?java/lang/UnsupportedOperationException.html"><code>UnsupportedOperationException</code></a>.</p>
<p>Before we pass a mutable collection to another part of our program, we can wrap it in an unmodifiable wrapper. We should be careful at that point to forget our reference to the mutable collection, lest we accidentally mutate it. (One way to do that is to let it go out of scope.) Just as a mutable object behind a <code>final</code> reference can be mutated, the mutable collection inside an unmodifiable wrapper can still be modified by someone with a reference to it, defeating the wrapper.</p>
</li>
<li>
<p><code>Collections</code> also provides methods for obtaining immutable empty collections: <code><a href="https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#emptyList--">Collections.emptyList</a></code>, etc. Nothing's worse than discovering your <em>definitely very empty</em> list is suddenly <em>definitely not empty</em>!</p>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@vertical_Questions_74150df5d6b3" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="VerticalStudentView" data-request-token="cec4e5c002f511efa5270afff417eba9">
<h2 class="hd hd-2 unit-title">Questions</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<script src="/assets/courseware/v1/3e6443fb95285d2dc06e8ffc448b9bdf/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism.js"></script>
<script src="/assets/courseware/v1/2ba76f8bdfef4e2d45e31a3dc5208470/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/edx-script-v1.js"></script>
</div>
</div>
<div class="vert vert-1" data-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-immutability-never-lies">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-block-type="problem" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-immutability-never-lies" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="True" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_07-immutability-never-lies" class="problems-wrapper" role="group"
aria-labelledby="07-immutability-never-lies-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-immutability-never-lies" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-immutability-never-lies/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="1"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="07-immutability-never-lies-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-immutability-never-lies-problem-progress" tabindex="-1">
immutability never lies
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@07-immutability-never-lies-problem-progress"></div>
<div class="problem">
<div>
<p>Which of the following are correct? Check all that apply.</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div class="choicegroup capa_inputtype" id="inputtype_07-immutability-never-lies_2_1">
<fieldset aria-describedby="status_07-immutability-never-lies_2_1">
<div class="field">
<input type="checkbox" name="input_07-immutability-never-lies_2_1[]" id="input_07-immutability-never-lies_2_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="07-immutability-never-lies_2_1-choice_0-label" for="input_07-immutability-never-lies_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_07-immutability-never-lies_2_1"> 1. A class is immutable if all of its fields are final
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-immutability-never-lies_2_1[]" id="input_07-immutability-never-lies_2_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="07-immutability-never-lies_2_1-choice_1-label" for="input_07-immutability-never-lies_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_07-immutability-never-lies_2_1"> 2. A class is immutable if instances of it always represent the same value
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-immutability-never-lies_2_1[]" id="input_07-immutability-never-lies_2_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="07-immutability-never-lies_2_1-choice_2-label" for="input_07-immutability-never-lies_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_07-immutability-never-lies_2_1"> 3. Instances of an immutable class can be safely shared
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-immutability-never-lies_2_1[]" id="input_07-immutability-never-lies_2_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="07-immutability-never-lies_2_1-choice_3-label" for="input_07-immutability-never-lies_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_07-immutability-never-lies_2_1"> 4. Objects can be made immutable using defensive copying
</label>
</div>
<div class="field">
<input type="checkbox" name="input_07-immutability-never-lies_2_1[]" id="input_07-immutability-never-lies_2_1_choice_4" class="field-input input-checkbox" value="choice_4"/><label id="07-immutability-never-lies_2_1-choice_4-label" for="input_07-immutability-never-lies_2_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_07-immutability-never-lies_2_1"> 5. Immutability allows us to reason about global properties instead of local ones
</label>
</div>
<span id="answer_07-immutability-never-lies_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_07-immutability-never-lies_2_1" data-tooltip="Not yet answered.">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_07-immutability-never-lies_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="immutability never lies" />
<div class="submit-attempt-container">
<button type="button" class="submit btn-brand" data-submitting="Submitting" data-value="Submit" data-should-enable-submit-button="True" aria-describedby="submission_feedback_07-immutability-never-lies" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_07-immutability-never-lies">
<span class="sr">Some problems have options such as save, reset, hints, or show answer. These options follow the Submit button.</span>
</div>
</div>
<div class="problem-action-buttons-wrapper">
</div>
</div>
<div class="notification warning notification-gentle-alert
is-hidden"
tabindex="-1">
<span class="icon fa fa-exclamation-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-immutability-never-lies-problem-title">
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification warning notification-save
is-hidden"
tabindex="-1">
<span class="icon fa fa-save" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-immutability-never-lies-problem-title">None
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
<div class="notification general notification-show-answer
is-hidden"
tabindex="-1">
<span class="icon fa fa-info-circle" aria-hidden="true"></span>
<span class="notification-message" aria-describedby="07-immutability-never-lies-problem-title">Answers are displayed within the problem
</span>
<div class="notification-btn-wrapper">
<button type="button" class="btn btn-default btn-small notification-btn review-btn sr">Review</button>
</div>
</div>
</div>
"
data-graded="True">
<p class="loading-spinner">
<i class="fa fa-spinner fa-pulse fa-2x fa-fw"></i>
<span class="sr">Loading…</span>
</p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-block-type="vertical" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@Reading_7_Summary" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="VerticalStudentView" data-request-token="cec4e5c002f511efa5270afff417eba9">
<h2 class="hd hd-2 unit-title">Reading 7 Summary</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_8cc335ba66f3">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-block-type="html" data-runtime-class="LmsRuntime" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_8cc335ba66f3" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-has-score="False" data-graded="True" data-runtime-version="1" data-init="XBlockToXModuleShim" data-request-token="cec4e5c002f511efa5270afff417eba9">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "HTMLModule"}
</script>
<link href="/assets/courseware/v1/9fab367942e94f98d32835b3ef4df11d/asset-v1:MITx+6.005.1x+3T2016+type@asset+block/prism-edx-v1.css" rel="stylesheet" type="text/css" />
<h2 id="summary">Summary</h2>
<div data-outline="summary">
<p>In this reading, we saw that mutability is useful for performance and convenience, but it also creates risks of bugs by requiring the code that uses the objects to be well-behaved on a global level, greatly complicating the reasoning and testing we have to do to be confident in its correctness.</p>
<p>Make sure you understand the difference between an immutable <em>object</em> (like a <code>String</code>) and an immutable <em>reference</em> (like a <code>final</code> variable). Snapshot diagrams can help with this understanding. Objects are values, represented by circles in a snapshot diagram and an immutable one has a double border indicating that it never changes its value. A reference is a pointer to an object, represented by an arrow in the snapshot diagram and an immutable reference is an arrow with a double line, indicating that the arrow can't be moved to point to a different object.</p>
<p>The key design principle here is <strong>immutability</strong>: using immutable objects and immutable references as much as possible. Let's review how immutability helps with the main goals of this course:</p>
<ul>
<li>
<p><strong>Safe from bugs</strong>. Immutable objects aren't susceptible to bugs caused by aliasing. Immutable references always point to the same object.</p>
</li>
<li>
<p><strong>Easy to understand</strong>. Because an immutable object or reference always means the same thing, it's simpler for a reader of the code to reason about — they don't have to trace through all the code to find all the places where the object or reference might be changed because it can't be changed.</p>
</li>
<li>
<p><strong>Ready for change</strong>. If an object or reference can't be changed at runtime, then code that depends on that object or reference won't have to be revised when the program changes.</p>
</li>
</ul>
</div>
<div class="license">This reading was collaboratively authored with contributions from: Saman Amarasinghe, Adam Chlipala, Srini Devadas, Michael Ernst, Max Goldman, John Guttag, Daniel Jackson, Rob Miller, Martin Rinard, and Armando Solar-Lezama. This work is licensed under <a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/">CC BY-SA 4.0</a>.</div>
</div>
</div>
</div>
</div>