<div class="xblock xblock-public_view xblock-public_view-vertical" data-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@Reading_6_Objectives" data-block-type="vertical" data-graded="True" data-has-score="False" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="VerticalStudentView">
<h2 class="hd hd-2 unit-title">Reading 6 Objectives</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_aa0a0d1d9290">
<div class="xblock xblock-public_view xblock-public_view-video xmodule_display xmodule_VideoBlock" data-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_aa0a0d1d9290" data-block-type="video" data-graded="True" data-has-score="False" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="XBlockToXModuleShim">
<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_aa0a0d1d9290"
class="video closed"
data-metadata='{"transcriptLanguages": {"en": "English"}, "lmsRootURL": "https://openlearninglibrary.mit.edu", "captionDataDir": null, "ytTestTimeout": 1500, "saveStateEnabled": false, "start": 0.0, "autoAdvance": false, "ytApiUrl": "https://www.youtube.com/iframe_api", "ytMetadataEndpoint": "", "recordedYoutubeIsAvailable": true, "speed": null, "generalSpeed": 1.0, "streams": "1.00:TbHE7jCuWv8", "completionEnabled": false, "end": 0.0, "transcriptTranslationUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_aa0a0d1d9290/handler/transcript/translation/__lang__", "prioritizeHls": false, "duration": 35.26, "publishCompletionUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_aa0a0d1d9290/handler/publish_completion", "completionPercentage": 0.95, "transcriptAvailableTranslationsUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_aa0a0d1d9290/handler/transcript/available_translations", "showCaptions": "true", "saveStateUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_aa0a0d1d9290/handler/xmodule_handler/save_user_state", "poster": null, "autoplay": false, "transcriptLanguage": "en", "autohideHtml5": false, "savedVideoPosition": 0.0, "sources": ["https://d2f1egay8yehza.cloudfront.net/MIT600512016-V003700_DTH.mp4", "https://d2f1egay8yehza.cloudfront.net/MIT600512016-V003700/MIT600512016-V003700.m3u8"]}'
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_aa0a0d1d9290"></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_aa0a0d1d9290">Downloads and transcripts</h3>
<div class="wrapper-downloads" role="region" aria-labelledby="video-download-transcripts_video_aa0a0d1d9290">
<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_aa0a0d1d9290/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_aa0a0d1d9290/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_a3d89824ceeb">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_a3d89824ceeb" data-block-type="html" data-graded="True" data-has-score="False" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="XBlockToXModuleShim">
<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>
Communicates 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>The topic of today's reading is debugging — or rather, how to avoid debugging entirely or keep it easy when you have to do it.</p>
<p>We're going to talk about two general ways to avoid painful debugging:</p>
<ul>
<li><strong>Make bugs impossible</strong> by design. We'll review some techniques that we've already talked about: static checking, dynamic checking, and immutability.</li>
<li><strong>Localize bugs</strong> to a small part of the program, so that finding the bug becomes easier. We'll see some new ideas for this: assertions, incremental development, and scope minimization.</li>
</ul>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@First_Defense_Make_Bugs_Impossible" data-block-type="vertical" data-graded="True" data-has-score="False" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="VerticalStudentView">
<h2 class="hd hd-2 unit-title">First Defense: Make Bugs Impossible</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_623e62f63084">
<div class="xblock xblock-public_view xblock-public_view-video xmodule_display xmodule_VideoBlock" data-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_623e62f63084" data-block-type="video" data-graded="True" data-has-score="False" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="XBlockToXModuleShim">
<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_623e62f63084"
class="video closed"
data-metadata='{"transcriptLanguages": {"en": "English"}, "lmsRootURL": "https://openlearninglibrary.mit.edu", "captionDataDir": null, "ytTestTimeout": 1500, "saveStateEnabled": false, "start": 0.0, "autoAdvance": false, "ytApiUrl": "https://www.youtube.com/iframe_api", "ytMetadataEndpoint": "", "recordedYoutubeIsAvailable": true, "speed": null, "generalSpeed": 1.0, "streams": "1.00:REuTUdAnASo", "completionEnabled": false, "end": 0.0, "transcriptTranslationUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_623e62f63084/handler/transcript/translation/__lang__", "prioritizeHls": false, "duration": 166.98, "publishCompletionUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_623e62f63084/handler/publish_completion", "completionPercentage": 0.95, "transcriptAvailableTranslationsUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_623e62f63084/handler/transcript/available_translations", "showCaptions": "true", "saveStateUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_623e62f63084/handler/xmodule_handler/save_user_state", "poster": null, "autoplay": false, "transcriptLanguage": "en", "autohideHtml5": false, "savedVideoPosition": 0.0, "sources": ["https://d2f1egay8yehza.cloudfront.net/MIT600512016-V003900_DTH.mp4", "https://d2f1egay8yehza.cloudfront.net/MIT600512016-V003900/MIT600512016-V003900.m3u8"]}'
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_623e62f63084"></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_623e62f63084">Downloads and transcripts</h3>
<div class="wrapper-downloads" role="region" aria-labelledby="video-download-transcripts_video_623e62f63084">
<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_623e62f63084/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_623e62f63084/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_1207c8177380">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_1207c8177380" data-block-type="html" data-graded="True" data-has-score="False" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="XBlockToXModuleShim">
<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="first_defense_make_bugs_impossible">First Defense: Make Bugs Impossible</h2>
<div data-outline="first_defense_make_bugs_impossible">
<p>The best defense against bugs is to make them impossible by design.</p>
<p><strong>Static checking</strong> is one way that <a href="/courses/course-v1:MITx+6.005.1x+3T2016/jump_to_id/vertical-static-typing#static_checking_dynamic_checking_no_checking">we've already talked about</a>. For example, Java prevents you from inadvertently passing an <code>int</code> value to a function expecting a <code>String</code> parameter, and it won't even allow your code to compile. Static checking eliminates many bugs by catching them at compile time.</p>
<p>We also saw some examples of <strong>dynamic checking</strong> in earlier readings. For example, Java makes array overflow bugs impossible by catching them dynamically. If you try to use an index outside the bounds of an array or a List, then Java automatically produces an error at runtime. Older languages like C and C++ silently allow the bad access, which leads to bugs and <a href="http://en.wikipedia.org/wiki/Buffer_overflow">security vulnerabilities</a>.</p>
<p><strong>Immutability</strong> (immunity from change) is another design principle that prevents bugs. An <em>immutable type</em> is a type whose values can never change once they have been created.</p>
<p><code>String</code> is an immutable type. There are no methods that you can call on a String that will change the sequence of characters that it represents. Strings can be passed around and shared without fear that they will be modified by other code.</p>
<p>Java also gives us <em>immutable references</em>: variables declared with the keyword <code>final</code>, which can be assigned once but never reassigned. It's good practice to use <code>final</code> for declaring the parameters of a method and as many local variables as possible. Like the type of the variable, these declarations are important documentation, useful to the reader of the code and statically checked by the compiler. </p>
<p>Consider this example:</p><pre><code class="language-java hljs"><span class="hljs-keyword">final</span> <span class="hljs-keyword">char</span>[] vowels = <span class="hljs-keyword">new</span> <span class="hljs-keyword">char</span>[] { <span class="hljs-string">'a'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'i'</span>, <span class="hljs-string">'o'</span>, <span class="hljs-string">'u'</span> };</code></pre>
<p>The <code>vowels</code> variable is declared final, but is it really unchanging? Which of the following statements will be illegal (caught statically by the compiler) and which will be allowed?</p><pre><code class="language-java hljs">vowels = <span class="hljs-keyword">new</span> <span class="hljs-keyword">char</span>[] { <span class="hljs-string">'x'</span>, <span class="hljs-string">'y'</span>, <span class="hljs-string">'z'</span> };
vowels[<span class="hljs-number">0</span>] = <span class="hljs-string">'z'</span>;</code></pre>
<p>You'll find the answers in the next exercise. Be careful about what <code>final</code> means! It only makes the <em>reference</em> immutable, not necessarily the <em>object</em> that the reference points to. </p>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@vertical_Questions_864e19c4bedd" data-block-type="vertical" data-graded="True" data-has-score="False" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="VerticalStudentView">
<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-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a" data-block-type="html" data-graded="True" data-has-score="False" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="XBlockToXModuleShim">
<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@06-final-references-immutable-objects">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@06-final-references-immutable-objects" data-block-type="problem" data-graded="True" data-has-score="True" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="XBlockToXModuleShim">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_06-final-references-immutable-objects" class="problems-wrapper" role="group"
aria-labelledby="06-final-references-immutable-objects-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@06-final-references-immutable-objects" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@06-final-references-immutable-objects/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="06-final-references-immutable-objects-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@06-final-references-immutable-objects-problem-progress" tabindex="-1">
final references, immutable objects
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@06-final-references-immutable-objects-problem-progress"></div>
<div class="problem">
<div>
<p>Consider the following code, executed in order:</p>
<pre class="code">
char vowel0 = 'a';
final char vowel1 = vowel0;
String vowel2 = vowel1 + "eiou";
final String vowel3 = vowel2;
char[] vowel4 = new char[] { vowel0, 'e', 'i', 'o', 'u' };
final char[] vowel5 = vowel4;
</pre>
<p>Which of the following statements are legal Java (i.e. produce no compiler error if placed after the code above)? 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_06-final-references-immutable-objects_2_1">
<fieldset aria-describedby="status_06-final-references-immutable-objects_2_1">
<div class="field">
<input type="checkbox" name="input_06-final-references-immutable-objects_2_1[]" id="input_06-final-references-immutable-objects_2_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="06-final-references-immutable-objects_2_1-choice_0-label" for="input_06-final-references-immutable-objects_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_06-final-references-immutable-objects_2_1"> vowel0 = vowel1
</label>
</div>
<div class="field">
<input type="checkbox" name="input_06-final-references-immutable-objects_2_1[]" id="input_06-final-references-immutable-objects_2_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="06-final-references-immutable-objects_2_1-choice_1-label" for="input_06-final-references-immutable-objects_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_06-final-references-immutable-objects_2_1"> vowel1 = vowel0
</label>
</div>
<div class="field">
<input type="checkbox" name="input_06-final-references-immutable-objects_2_1[]" id="input_06-final-references-immutable-objects_2_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="06-final-references-immutable-objects_2_1-choice_2-label" for="input_06-final-references-immutable-objects_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_06-final-references-immutable-objects_2_1"> vowel2 = vowel3
</label>
</div>
<div class="field">
<input type="checkbox" name="input_06-final-references-immutable-objects_2_1[]" id="input_06-final-references-immutable-objects_2_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="06-final-references-immutable-objects_2_1-choice_3-label" for="input_06-final-references-immutable-objects_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_06-final-references-immutable-objects_2_1"> vowel3 = vowel2
</label>
</div>
<div class="field">
<input type="checkbox" name="input_06-final-references-immutable-objects_2_1[]" id="input_06-final-references-immutable-objects_2_1_choice_4" class="field-input input-checkbox" value="choice_4"/><label id="06-final-references-immutable-objects_2_1-choice_4-label" for="input_06-final-references-immutable-objects_2_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_06-final-references-immutable-objects_2_1"> vowel2[0] = 'x'
</label>
</div>
<div class="field">
<input type="checkbox" name="input_06-final-references-immutable-objects_2_1[]" id="input_06-final-references-immutable-objects_2_1_choice_5" class="field-input input-checkbox" value="choice_5"/><label id="06-final-references-immutable-objects_2_1-choice_5-label" for="input_06-final-references-immutable-objects_2_1_choice_5" class="response-label field-label label-inline" aria-describedby="status_06-final-references-immutable-objects_2_1"> vowel3[0] = 'x'
</label>
</div>
<div class="field">
<input type="checkbox" name="input_06-final-references-immutable-objects_2_1[]" id="input_06-final-references-immutable-objects_2_1_choice_6" class="field-input input-checkbox" value="choice_6"/><label id="06-final-references-immutable-objects_2_1-choice_6-label" for="input_06-final-references-immutable-objects_2_1_choice_6" class="response-label field-label label-inline" aria-describedby="status_06-final-references-immutable-objects_2_1"> vowel4 = vowel5
</label>
</div>
<div class="field">
<input type="checkbox" name="input_06-final-references-immutable-objects_2_1[]" id="input_06-final-references-immutable-objects_2_1_choice_7" class="field-input input-checkbox" value="choice_7"/><label id="06-final-references-immutable-objects_2_1-choice_7-label" for="input_06-final-references-immutable-objects_2_1_choice_7" class="response-label field-label label-inline" aria-describedby="status_06-final-references-immutable-objects_2_1"> vowel5 = vowel4
</label>
</div>
<div class="field">
<input type="checkbox" name="input_06-final-references-immutable-objects_2_1[]" id="input_06-final-references-immutable-objects_2_1_choice_8" class="field-input input-checkbox" value="choice_8"/><label id="06-final-references-immutable-objects_2_1-choice_8-label" for="input_06-final-references-immutable-objects_2_1_choice_8" class="response-label field-label label-inline" aria-describedby="status_06-final-references-immutable-objects_2_1"> vowel4[0] = 'x'
</label>
</div>
<div class="field">
<input type="checkbox" name="input_06-final-references-immutable-objects_2_1[]" id="input_06-final-references-immutable-objects_2_1_choice_9" class="field-input input-checkbox" value="choice_9"/><label id="06-final-references-immutable-objects_2_1-choice_9-label" for="input_06-final-references-immutable-objects_2_1_choice_9" class="response-label field-label label-inline" aria-describedby="status_06-final-references-immutable-objects_2_1"> vowel5[0] = 'x'
</label>
</div>
<span id="answer_06-final-references-immutable-objects_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_06-final-references-immutable-objects_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_06-final-references-immutable-objects_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="final references, immutable objects" />
<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_06-final-references-immutable-objects" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_06-final-references-immutable-objects">
<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="06-final-references-immutable-objects-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="06-final-references-immutable-objects-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="06-final-references-immutable-objects-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-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@Second_Defense_Localize_Bugs" data-block-type="vertical" data-graded="True" data-has-score="False" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="VerticalStudentView">
<h2 class="hd hd-2 unit-title">Second Defense: Localize Bugs</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_01bcab88a271">
<div class="xblock xblock-public_view xblock-public_view-video xmodule_display xmodule_VideoBlock" data-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_01bcab88a271" data-block-type="video" data-graded="True" data-has-score="False" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="XBlockToXModuleShim">
<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_01bcab88a271"
class="video closed"
data-metadata='{"transcriptLanguages": {"en": "English"}, "lmsRootURL": "https://openlearninglibrary.mit.edu", "captionDataDir": null, "ytTestTimeout": 1500, "saveStateEnabled": false, "start": 0.0, "autoAdvance": false, "ytApiUrl": "https://www.youtube.com/iframe_api", "ytMetadataEndpoint": "", "recordedYoutubeIsAvailable": true, "speed": null, "generalSpeed": 1.0, "streams": "1.00:4MSuGBvFB9U", "completionEnabled": false, "end": 0.0, "transcriptTranslationUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_01bcab88a271/handler/transcript/translation/__lang__", "prioritizeHls": false, "duration": 609.92, "publishCompletionUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_01bcab88a271/handler/publish_completion", "completionPercentage": 0.95, "transcriptAvailableTranslationsUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_01bcab88a271/handler/transcript/available_translations", "showCaptions": "true", "saveStateUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_01bcab88a271/handler/xmodule_handler/save_user_state", "poster": null, "autoplay": false, "transcriptLanguage": "en", "autohideHtml5": false, "savedVideoPosition": 0.0, "sources": ["https://d2f1egay8yehza.cloudfront.net/MIT600512016-V004000_DTH.mp4", "https://d2f1egay8yehza.cloudfront.net/MIT600512016-V004000/MIT600512016-V004000.m3u8"]}'
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_01bcab88a271"></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_01bcab88a271">Downloads and transcripts</h3>
<div class="wrapper-downloads" role="region" aria-labelledby="video-download-transcripts_video_01bcab88a271">
<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_01bcab88a271/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_01bcab88a271/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_3a496c8130de">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_3a496c8130de" data-block-type="html" data-graded="True" data-has-score="False" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="XBlockToXModuleShim">
<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="second_defense_localize_bugs">Second Defense: Localize Bugs</h2>
<div data-outline="second_defense_localize_bugs">
<p>If we can't prevent bugs, we can try to localize them to a small part of the program so that we don't have to look too hard to find the cause of a bug. When localized to a single method or small module, bugs may be found simply by studying the program text.</p>
<p>We already talked about <a href="/courses/course-v1:MITx+6.005.1x+3T2016/jump_to_id/vertical-fail-fast#fail_fast"><strong>fail fast</strong></a>: the earlier a problem is observed (the closer to its cause), the easier it is to fix. In this section, we'll talk about a particular technique for failing fast, called assertions.</p>
<p>Let's begin with a simple example:</p><pre><code class="language-java hljs"><span class="hljs-comment handout-javadoc-comment">/**
* <span class="hljs-doctag">@param</span> x requires x >= 0
* <span class="hljs-doctag">@return</span> approximation to square root of x
*/</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">sqrt</span><span class="hljs-params">(<span class="hljs-keyword">double</span> x)</span> </span>{ ... }</code></pre>
<p>Now suppose somebody calls <code>sqrt</code> with a negative argument. What's the best behavior for <code>sqrt</code>? Since the caller has failed to satisfy the requirement that <code>x</code> should be nonnegative, <code>sqrt</code> is no longer bound by the terms of its contract, so it is technically free to do whatever it wants: return an arbitrary value, enter an infinite loop, or even melt down the CPU. Since the bad call indicates a bug in the caller, however, the most useful behavior would point out the bug as early as possible. We do this by inserting a runtime assertion that tests the precondition. Here is one way we might write the assertion:</p><pre><code class="language-java hljs"><span class="hljs-comment handout-javadoc-comment">/**
* <span class="hljs-doctag">@param</span> x requires x >= 0
* <span class="hljs-doctag">@return</span> approximation to square root of x
*/</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">sqrt</span><span class="hljs-params">(<span class="hljs-keyword">double</span> x)</span> </span>{
<span class="hljs-keyword">if</span> (! (x >= <span class="hljs-number">0</span>)) <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> AssertionError();
...
}</code></pre>
<p>When the precondition is not satisfied, this code terminates the program by throwing an <code>AssertionError</code> exception. The effects of the caller's bug are prevented from propagating.</p>
<p>Checking preconditions is an example of <strong>defensive programming</strong>. Real programs are rarely bug-free. Defensive programming offers a way to mitigate the effects of bugs even if you don't know where they are.</p>
</div>
<h2 id="assertions">Assertions</h2>
<div data-outline="assertions">
<p>It is common practice to define a procedure for these kinds of defensive checks, usually called <code>assert</code>:</p><pre><code class="language-java hljs"><span class="hljs-keyword">assert</span> (x >= <span class="hljs-number">0</span>);</code></pre>
<p>This approach abstracts away from what exactly happens when the assertion fails. The failed assert might exit, might record an event in a log file, or might even email a report to a maintainer.</p>
<p>Assertions have the added benefit of documenting an assumption about the state of the program at that point. To somebody reading your code, <code>assert (x >= 0)</code> says “at this point, it should always be true that x >= 0.” Unlike a comment, however, an assertion is executable code that enforces the assumption at runtime.</p>
<p>In Java, runtime assertions are a built-in feature of the language. The simplest form of the assert statement takes a boolean expression, exactly as shown above, and throws an <code>AssertionError</code> if the boolean expression evaluates to false:</p><pre><code class="language-java hljs"><span class="hljs-keyword">assert</span> x >= <span class="hljs-number">0</span>;</code></pre>
<p>An assert statement may also include a description expression, which is usually a string, but may also be a primitive type or a reference to an object. The description is printed in an error message when the assertion fails, so that it can be used to provide additional details to the programmer about the cause of the failure. The description follows the asserted expression, separated by a colon. For example:</p><pre><code class="language-java hljs"><span class="hljs-keyword">assert</span> (x >= <span class="hljs-number">0</span>) : <span class="hljs-string">"x is "</span> + x;</code></pre>
<p>If x == -1, then this assertion fails with the error message</p>
<blockquote>
<p><code>x is -1</code></p>
</blockquote>
<p>along with a stack trace that tells you where the assert statement was found in your code and the sequence of calls that brought the program to that point. This information is often enough to get started in finding the bug.</p>
<div style="color:darkred">
<p>A serious problem with Java assertions is that assertions are <em>off by default</em>.</p>
</div>
<p>If you just run your program as usual, none of your assertions will be checked! Java's designers did this because checking assertions can sometimes be costly to performance. For example, a procedure that searches an array using binary search has a requirement that the array be sorted. Asserting this requirement requires scanning through the entire array, however, turning an operation that should run in logarithmic time into one that takes linear time. You should be willing (eager!) to pay this cost during testing, since it makes debugging much easier, but not after the program is released to users. For most applications, however, assertions are <em>not</em> expensive compared to the rest of the code and the benefit they provide in bug-checking is worth that small cost in peformance.</p>
<p>So you have to enable assertions explicity by passing <code>-ea</code> (which stands for <em>enable assertions</em>) to the Java virtual machine. In Eclipse, you enable assertions by going to Run → Run Configurations → Arguments, and putting -ea in the VM arguments box. It's best, in fact, to enable them by default by going to Preferences → Java → Installed JREs → Edit → Default VM Arguments. </p>
<p>It's always a good idea to have assertions turned on when you're running JUnit tests. You can ensure that assertions are enabled using the following test case: </p><pre><code class="language-java hljs"><span class="hljs-annotation">@Test</span>(expected=AssertionError.class)
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testAssertionsEnabled</span><span class="hljs-params">()</span> </span>{
<span class="hljs-keyword">assert</span> <span class="hljs-keyword">false</span>;
}</code></pre>
<p>If assertions are turned on as desired, then <code>assert false</code> throws an <code>AssertionError</code>. The annotation <code>(expected=AssertionError.class)</code> on the test expects and requires this error to be thrown, so the test passes. If assertions are turned off, however, then the body of the test will do nothing, failing to throw the expected exception, and JUnit will mark the test as failing.</p>
<p>Note that the Java <code>assert</code> statement is a different mechanism than the JUnit methods <code>assertTrue()</code>, <code>assertEquals()</code>, etc. They all assert a predicate about your code, but are designed for use in different contexts. The <code>assert</code> statement should be used in implementation code for defensive checks inside the implementation. JUnit <code>assert...()</code> methods should be used in JUnit tests to check the result of a test. The <code>assert</code> statements don't run without <code>-ea</code>, but the JUnit <code>assert...()</code> methods always run.</p>
</div>
<h2 id="what_to_assert">What to Assert</h2>
<div data-outline="what_to_assert">
<p>Here are some things you should assert:</p>
<p><strong>Method argument requirements</strong>, like we saw for <code>sqrt</code>.</p>
<p><strong>Method return value requirements.</strong> This kind of assertion is sometimes called a <em>self check</em>. For example, the sqrt method might square its result to check whether it is reasonably close to x:</p><pre><code class="language-java hljs"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">sqrt</span><span class="hljs-params">(<span class="hljs-keyword">double</span> x)</span> </span>{
<span class="hljs-keyword">assert</span> x >= <span class="hljs-number">0</span>;
<span class="hljs-keyword">double</span> r;
... <span class="hljs-comment">// compute result r</span>
<span class="hljs-keyword">assert</span> Math.abs(r*r - x) < .<span class="hljs-number">0001</span>;
<span class="hljs-keyword">return</span> r;
}</code></pre>
<p><strong>Covering all cases.</strong> If a conditional statement or switch does not cover all the possible cases, it is good practice to use an assertion to block the illegal cases:</p><pre><code class="language-java hljs"><span class="hljs-keyword">switch</span> (vowel) {
<span class="hljs-keyword">case</span> <span class="hljs-string">'a'</span>:
<span class="hljs-keyword">case</span> <span class="hljs-string">'e'</span>:
<span class="hljs-keyword">case</span> <span class="hljs-string">'i'</span>:
<span class="hljs-keyword">case</span> <span class="hljs-string">'o'</span>:
<span class="hljs-keyword">case</span> <span class="hljs-string">'u'</span>: <span class="hljs-keyword">return</span> <span class="hljs-string">"A"</span>;
<span class="hljs-keyword">default</span>: Assert.fail();
}</code></pre>
<p>The assertion in the default clause has the effect of asserting that <code>vowel</code> must be one of the five vowel letters.</p>
<p>When should you write runtime assertions? As you write the code, not after the fact. When you're writing the code, you have the invariants in mind. If you postpone writing assertions, you're less likely to do it, and you're liable to omit some important invariants.</p>
</div>
<h2 id="what_not_to_assert">What Not to Assert</h2>
<div data-outline="what_not_to_assert">
<p>Runtime assertions are not free. They can clutter the code, so they must be used judiciously. Avoid trivial assertions, just as you would avoid uninformative comments. For example:</p><pre><code class="language-java hljs"><span class="hljs-comment">// don't do this:</span>
x = y + <span class="hljs-number">1</span>;
<span class="hljs-keyword">assert</span> x == y+<span class="hljs-number">1</span>;</code></pre>
<p>This assertion doesn't find bugs in your code. It finds bugs in the compiler or Java virtual machine, which are components that you should trust until you have good reason to doubt them. If an assertion is obvious from its local context, leave it out.</p>
<p>Never use assertions to test conditions that are external to your program, such as the existence of files, the availability of the network, or the correctness of input typed by a human user. Assertions test the internal state of your program to ensure that it is within the bounds of its specification. When an assertion fails, it indicates that the program has run off the rails, in some sense, into a state in which it was not designed to function properly. Assertion failures therefore indicate bugs. External failures are not bugs and there is no change you can make to your program in advance that will prevent them from happening. External failures should be handled using exceptions instead.</p>
<p>Many assertion mechanisms are designed so that assertions are executed only during testing and debugging and turned off when the program is released to users. Java's assert statement behaves this way. Since assertions may be disabled, the correctness of your program should never depend on whether or not the assertion expressions are executed. In particular, asserted expressions should not have <em>side-effects</em>. For example, if you want to assert that an element removed from a list was actually found in the list, don't write it like this:</p><pre><code class="language-java hljs"><span class="hljs-comment">// don't do this:</span>
<span class="hljs-keyword">assert</span> list.remove(x);</code></pre>
<p>If assertions are disabled, the entire expression is skipped, and <code>x</code> is never removed from the list. Write it like this instead:</p><pre><code class="language-java hljs"><span class="hljs-keyword">boolean</span> found = list.remove(x);
<span class="hljs-keyword">assert</span> found;</code></pre>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@vertical_Questions_2cccc8b9667f" data-block-type="vertical" data-graded="True" data-has-score="False" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="VerticalStudentView">
<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-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a" data-block-type="html" data-graded="True" data-has-score="False" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="XBlockToXModuleShim">
<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@06-assertions">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@06-assertions" data-block-type="problem" data-graded="True" data-has-score="True" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="XBlockToXModuleShim">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_06-assertions" class="problems-wrapper" role="group"
aria-labelledby="06-assertions-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@06-assertions" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@06-assertions/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="06-assertions-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@06-assertions-problem-progress" tabindex="-1">
assertions
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@06-assertions-problem-progress"></div>
<div class="problem">
<div>
<p>Consider this (incomplete) function:</p>
<pre class="code">
/**
* Solves quadratic equation ax^2 + bx + c = 0.
*
* @param a quadratic coefficient, requires a != 0
* @param b linear coefficient
* @param c constant term
* @return a list of the real roots of the equation
*/
public static List&lt;Double&gt; quadraticRoots(final int a, final int b, final int c) {
List&lt;Double&gt; roots = new ArrayList&lt;Double&gt;();
// A
... // compute roots
// B
return roots;
}
</pre>
<p>What statements would be reasonable to write at position A? Check all that apply.</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 1" role="group"><div id="inputtype_06-assertions_2_1" class="choicegroup capa_inputtype">
<fieldset aria-describedby="status_06-assertions_2_1">
<div class="field">
<input id="input_06-assertions_2_1_choice_0" type="checkbox" name="input_06-assertions_2_1[]" class="field-input input-checkbox" value="choice_0"/><label id="06-assertions_2_1-choice_0-label" for="input_06-assertions_2_1_choice_0" aria-describedby="status_06-assertions_2_1" class="response-label field-label label-inline"> assert a != 0;
</label>
</div>
<div class="field">
<input id="input_06-assertions_2_1_choice_1" type="checkbox" name="input_06-assertions_2_1[]" class="field-input input-checkbox" value="choice_1"/><label id="06-assertions_2_1-choice_1-label" for="input_06-assertions_2_1_choice_1" aria-describedby="status_06-assertions_2_1" class="response-label field-label label-inline"> assert b != 0;
</label>
</div>
<div class="field">
<input id="input_06-assertions_2_1_choice_2" type="checkbox" name="input_06-assertions_2_1[]" class="field-input input-checkbox" value="choice_2"/><label id="06-assertions_2_1-choice_2-label" for="input_06-assertions_2_1_choice_2" aria-describedby="status_06-assertions_2_1" class="response-label field-label label-inline"> assert c != 0;
</label>
</div>
<div class="field">
<input id="input_06-assertions_2_1_choice_3" type="checkbox" name="input_06-assertions_2_1[]" class="field-input input-checkbox" value="choice_3"/><label id="06-assertions_2_1-choice_3-label" for="input_06-assertions_2_1_choice_3" aria-describedby="status_06-assertions_2_1" class="response-label field-label label-inline"> assert roots.size() &gt;= 0;
</label>
</div>
<div class="field">
<input id="input_06-assertions_2_1_choice_4" type="checkbox" name="input_06-assertions_2_1[]" class="field-input input-checkbox" value="choice_4"/><label id="06-assertions_2_1-choice_4-label" for="input_06-assertions_2_1_choice_4" aria-describedby="status_06-assertions_2_1" class="response-label field-label label-inline"> assert roots.size() &lt;= 2;
</label>
</div>
<div class="field">
<input id="input_06-assertions_2_1_choice_5" type="checkbox" name="input_06-assertions_2_1[]" class="field-input input-checkbox" value="choice_5"/><label id="06-assertions_2_1-choice_5-label" for="input_06-assertions_2_1_choice_5" aria-describedby="status_06-assertions_2_1" class="response-label field-label label-inline"> roots.forEach( (x) -&gt; { assert Math.abs(a*x*x + b*x + c) &lt; 0.0001; } );
</label>
</div>
<span id="answer_06-assertions_2_1"/>
</fieldset>
<div class="indicator-container">
<span id="status_06-assertions_2_1" data-tooltip="Not yet answered." class="status unanswered">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<p>What statements would be reasonable to write at position B? Check all that apply.</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 2" role="group"><div id="inputtype_06-assertions_3_1" class="choicegroup capa_inputtype">
<fieldset aria-describedby="status_06-assertions_3_1">
<div class="field">
<input id="input_06-assertions_3_1_choice_0" type="checkbox" name="input_06-assertions_3_1[]" class="field-input input-checkbox" value="choice_0"/><label id="06-assertions_3_1-choice_0-label" for="input_06-assertions_3_1_choice_0" aria-describedby="status_06-assertions_3_1" class="response-label field-label label-inline"> assert a != 0;
</label>
</div>
<div class="field">
<input id="input_06-assertions_3_1_choice_1" type="checkbox" name="input_06-assertions_3_1[]" class="field-input input-checkbox" value="choice_1"/><label id="06-assertions_3_1-choice_1-label" for="input_06-assertions_3_1_choice_1" aria-describedby="status_06-assertions_3_1" class="response-label field-label label-inline"> assert b != 0;
</label>
</div>
<div class="field">
<input id="input_06-assertions_3_1_choice_2" type="checkbox" name="input_06-assertions_3_1[]" class="field-input input-checkbox" value="choice_2"/><label id="06-assertions_3_1-choice_2-label" for="input_06-assertions_3_1_choice_2" aria-describedby="status_06-assertions_3_1" class="response-label field-label label-inline"> assert c != 0;
</label>
</div>
<div class="field">
<input id="input_06-assertions_3_1_choice_3" type="checkbox" name="input_06-assertions_3_1[]" class="field-input input-checkbox" value="choice_3"/><label id="06-assertions_3_1-choice_3-label" for="input_06-assertions_3_1_choice_3" aria-describedby="status_06-assertions_3_1" class="response-label field-label label-inline"> assert roots.size() &gt;= 0;
</label>
</div>
<div class="field">
<input id="input_06-assertions_3_1_choice_4" type="checkbox" name="input_06-assertions_3_1[]" class="field-input input-checkbox" value="choice_4"/><label id="06-assertions_3_1-choice_4-label" for="input_06-assertions_3_1_choice_4" aria-describedby="status_06-assertions_3_1" class="response-label field-label label-inline"> assert roots.size() &lt;= 2;
</label>
</div>
<div class="field">
<input id="input_06-assertions_3_1_choice_5" type="checkbox" name="input_06-assertions_3_1[]" class="field-input input-checkbox" value="choice_5"/><label id="06-assertions_3_1-choice_5-label" for="input_06-assertions_3_1_choice_5" aria-describedby="status_06-assertions_3_1" class="response-label field-label label-inline"> roots.forEach( (x) -&gt; { assert Math.abs(a*x*x + b*x + c) &lt; 0.0001; } );
</label>
</div>
<span id="answer_06-assertions_3_1"/>
</fieldset>
<div class="indicator-container">
<span id="status_06-assertions_3_1" data-tooltip="Not yet answered." class="status unanswered">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<p>Note: roots.forEach() applies a lambda expression to each element of the roots list. Its rough equivalent in Python is:</p>
<pre class="code">
map(lambda x: assert abs(a*x*x + b*x + c) &lt; 0.0001, roots)
</pre>
<p>or:</p>
<pre class="code">
for x in roots:
assert abs(a*x*x + b*x + c) &lt; 0.0001
</pre>
<div class="solution-span">
<span id="solution_06-assertions_solution_1"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="assertions" />
<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_06-assertions" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_06-assertions">
<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="06-assertions-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="06-assertions-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="06-assertions-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-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@Incremental_Development_Modularity_Encapsulation" data-block-type="vertical" data-graded="True" data-has-score="False" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="VerticalStudentView">
<h2 class="hd hd-2 unit-title">Incremental Development, Modularity & Encapsulation</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_189de5ba3a93">
<div class="xblock xblock-public_view xblock-public_view-video xmodule_display xmodule_VideoBlock" data-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@video+block@video_189de5ba3a93" data-block-type="video" data-graded="True" data-has-score="False" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="XBlockToXModuleShim">
<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_189de5ba3a93"
class="video closed"
data-metadata='{"transcriptLanguages": {"en": "English"}, "lmsRootURL": "https://openlearninglibrary.mit.edu", "captionDataDir": null, "ytTestTimeout": 1500, "saveStateEnabled": false, "start": 0.0, "autoAdvance": false, "ytApiUrl": "https://www.youtube.com/iframe_api", "ytMetadataEndpoint": "", "recordedYoutubeIsAvailable": true, "speed": null, "generalSpeed": 1.0, "streams": "1.00:mVp-4nTXzbk", "completionEnabled": false, "end": 0.0, "transcriptTranslationUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_189de5ba3a93/handler/transcript/translation/__lang__", "prioritizeHls": false, "duration": 465.03, "publishCompletionUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_189de5ba3a93/handler/publish_completion", "completionPercentage": 0.95, "transcriptAvailableTranslationsUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_189de5ba3a93/handler/transcript/available_translations", "showCaptions": "true", "saveStateUrl": "/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@video+block@video_189de5ba3a93/handler/xmodule_handler/save_user_state", "poster": null, "autoplay": false, "transcriptLanguage": "en", "autohideHtml5": false, "savedVideoPosition": 0.0, "sources": ["https://d2f1egay8yehza.cloudfront.net/MIT600512016-V003800_DTH.mp4", "https://d2f1egay8yehza.cloudfront.net/MIT600512016-V003800/MIT600512016-V003800.m3u8"]}'
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_189de5ba3a93"></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_189de5ba3a93">Downloads and transcripts</h3>
<div class="wrapper-downloads" role="region" aria-labelledby="video-download-transcripts_video_189de5ba3a93">
<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_189de5ba3a93/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_189de5ba3a93/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_3809471b2fe0">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_3809471b2fe0" data-block-type="html" data-graded="True" data-has-score="False" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="XBlockToXModuleShim">
<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="incremental_development">Incremental Development</h2>
<div data-outline="incremental_development">
<p>A great way to localize bugs to a tiny part of the program is incremental development. Build only a bit of your program at a time and test that bit thoroughly before you move on. That way, when you discover a bug, it's more likely to be in the part that you just wrote, rather than anywhere in a huge pile of code.</p>
<p>Our class on testing talked about two techniques that help with incremental development:</p>
<ul>
<li><a href="/courses/course-v1:MITx+6.005.1x+3T2016/jump_to_id/vertical-unit-testing-and-stubs#unit_testing_and_stubs">Unit testing</a>: when you test a module in isolation, you can be confident that any bug you find is in that unit — or maybe in the test cases themselves.</li>
<li><a href="/courses/course-v1:MITx+6.005.1x+3T2016/jump_to_id/vertical-automated-testing-and-regression-testing#automated_testing_and_regression_testing">Regression testing</a>: when you're adding a new feature to a big system, run the regression test suite as often as possible. If a test fails, the bug is probably in the code you just changed.</li>
</ul>
</div>
<h2 id="modularity_encapsulation">Modularity & Encapsulation</h2>
<div data-outline="modularity_encapsulation">
<p>You can also localize bugs by better software design.</p>
<p><strong>Modularity</strong> means dividing up a system into components, or modules, each of which can be designed, implemented, tested, reasoned about, and reused separately from the rest of the system. The opposite of a modular system is a monolithic system — big and with all of its pieces tangled up and dependent on each other.</p>
<p>A program consisting of a single, very long main() function is monolithic — harder to understand and harder to isolate bugs in. By contrast, a program broken up into small functions and classes is more modular.</p>
<p><strong>Encapsulation</strong> means building walls around a module (a hard shell or capsule) so that the module is responsible for its own internal behavior and bugs in other parts of the system can't damage its integrity.</p>
<p>One kind of encapsulation is <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html">access control</a>: using <code>public</code> and <code>private</code> to control the visibility and accessibility of your variables and methods. A public variable or method can be accessed by any code (assuming the class containing that variable or method is also public). A private variable or method can only be accessed by code in the same class. Keeping things private as much as possible, especially for variables, provides encapsulation, since it limits the code that could inadvertently cause bugs.</p>
<p>Another kind of encapsulation comes from <strong>variable scope</strong>. The <em>scope</em> of a variable is the portion of the program text over which that variable is defined, in the sense that expressions and statements can refer to the variable. A method parameter's scope is the body of the method. A local variable's scope (in Java) extends from its declaration to the closing curly brace of the block around the declaration. Keeping variable scopes as small as possible makes it much easier to reason about where a bug might be in the program. For example, suppose you have a loop like this:</p><pre><code class="language-java hljs"><span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i < <span class="hljs-number">100</span>; ++i) {
...
doSomeThings();
...
}</code></pre>
<p>…and you've discovered that this loop keeps running forever — <code>i</code> never reaches 100. Somewhere, somebody is changing <code>i</code>. But where? If <code>i</code> is declared as a global variable like this:</p><pre><code class="language-java hljs"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> i;
...
<span class="hljs-keyword">for</span> (i =<span class="hljs-number">0</span>; i < <span class="hljs-number">100</span>; ++i) {
...
doSomeThings();
...
}</code></pre>
<p>…then its scope is the entire program. It might be changed anywhere in your program: by <code>doSomeThings()</code>, by some other method that <code>doSomeThings()</code> calls, or by a concurrent thread running some completely different code. But if <code>i</code> is instead declared as a local variable with a narrow scope, like this:</p><pre><code class="language-java hljs"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < <span class="hljs-number">100</span>; ++i) {
...
doSomeThings();
...
}</code></pre>
<p>…then the only place where <code>i</code> can be changed is within the for statement — in fact, only in the … parts that we've omitted. You don't even have to consider <code>doSomeThings()</code> because <code>doSomeThings()</code> doesn't have access to this local variable.</p>
</div>
<h2 id="minimizing_variable_scope">Minimizing Variable Scope</h2>
<div data-outline="minimizing_variable_scope">
<p>Minimizing the scope of variables is a powerful practice for bug localization. Here are a few rules that are good for Java:</p>
<ul>
<li><strong>Always declare a loop variable in the for-loop initializer.</strong> Don't declare it before the loop:
<pre><code class="language-java hljs"><span class="hljs-keyword">int</span> i; <span class="hljs-comment">// don't do this</span>
<span class="hljs-keyword">for</span> (i = <span class="hljs-number">0</span>; i < <span class="hljs-number">100</span>; ++i) {</code></pre>
<p>This makes the scope of the variable the entire rest of the outer curly-brace block containing this code.</p>
<p>Do this instead:</p><pre><code class="language-java hljs"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < <span class="hljs-number">100</span>; ++i) {</code></pre>
<p>which makes the scope of <code>i</code> limited just to the for loop.</p></li>
<li>
<p><strong>Declare a variable only when you first need it and in the innermost curly-brace block that you can.</strong> Variable scopes in Java are curly-brace blocks, so put your variable declaration in the innermost one that contains all the expressions that need to use the variable. Don't declare all your variables at the start of the function — it makes their scopes unnecessarily large. But note that in languages without static type declarations, like Python and Javascript, the scope of a variable is normally the entire function anyway, so you can't restrict the scope of a variable with curly braces, alas.</p>
</li>
<li>
<p><strong>Avoid global variables.</strong> Using global variables is very bad idea, especially as programs get large. Global variables are often unwisely used as a shortcut to provide a parameter to several parts of your program, but that's a terrible idea. It's better to just pass the parameter into the code that needs it, rather than putting it in global space where it can inadvertently reassigned.</p>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<div class="xblock xblock-public_view xblock-public_view-vertical" data-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@vertical_Questions_aaa12cb514cc" data-block-type="vertical" data-graded="True" data-has-score="False" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="VerticalStudentView">
<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-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_fff67ba8819a" data-block-type="html" data-graded="True" data-has-score="False" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="XBlockToXModuleShim">
<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@06-variable-scope">
<div class="xblock xblock-public_view xblock-public_view-problem xmodule_display xmodule_ProblemBlock" data-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@06-variable-scope" data-block-type="problem" data-graded="True" data-has-score="True" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="XBlockToXModuleShim">
<script type="json/xblock-args" class="xblock-json-init-args">
{"xmodule-type": "Problem"}
</script>
<div id="problem_06-variable-scope" class="problems-wrapper" role="group"
aria-labelledby="06-variable-scope-problem-title"
data-problem-id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@06-variable-scope" data-url="/courses/course-v1:MITx+6.005.1x+3T2016/xblock/block-v1:MITx+6.005.1x+3T2016+type@problem+block@06-variable-scope/handler/xmodule_handler"
data-problem-score="0"
data-problem-total-possible="4"
data-attempts-used="0"
data-content="
<h3 class="hd hd-3 problem-header" id="06-variable-scope-problem-title" aria-describedby="block-v1:MITx+6.005.1x+3T2016+type@problem+block@06-variable-scope-problem-progress" tabindex="-1">
variable scope
</h3>
<div class="problem-progress" id="block-v1:MITx+6.005.1x+3T2016+type@problem+block@06-variable-scope-problem-progress"></div>
<div class="problem">
<div>
<p>Consider the following code (which is missing some variable declarations):</p>
<pre class="code">
1 class Apartment {
2 Apartment(String newAddress) {
3 this.address = newAddress;
4 this.roommates = new HashSet&lt;Person&gt;();
5 }
6
7 String getAddress() {
8 return address;
9 }
10
11 void addRoommate(Person newRoommate) {
12 roommates.add(newRoommate);
13 if (roommates.size() &gt; MAXIMUM_OCCUPANCY) {
14 roommates.remove(newRoommate);
15 throw new TooManyPeopleException();
16 }
17 }
18
19 int getMaximumOccupancy() {
20 return MAXIMUM_OCCUPANCY;
21 }
22 }
</pre>
<p>Which of these lines are within the scope of the <code>newRoommate</code> variable? 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_06-variable-scope_2_1">
<fieldset aria-describedby="status_06-variable-scope_2_1">
<div class="field">
<input type="checkbox" name="input_06-variable-scope_2_1[]" id="input_06-variable-scope_2_1_choice_0" class="field-input input-checkbox" value="choice_0"/><label id="06-variable-scope_2_1-choice_0-label" for="input_06-variable-scope_2_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_06-variable-scope_2_1"> line 3
</label>
</div>
<div class="field">
<input type="checkbox" name="input_06-variable-scope_2_1[]" id="input_06-variable-scope_2_1_choice_1" class="field-input input-checkbox" value="choice_1"/><label id="06-variable-scope_2_1-choice_1-label" for="input_06-variable-scope_2_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_06-variable-scope_2_1"> line 8
</label>
</div>
<div class="field">
<input type="checkbox" name="input_06-variable-scope_2_1[]" id="input_06-variable-scope_2_1_choice_2" class="field-input input-checkbox" value="choice_2"/><label id="06-variable-scope_2_1-choice_2-label" for="input_06-variable-scope_2_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_06-variable-scope_2_1"> line 12
</label>
</div>
<div class="field">
<input type="checkbox" name="input_06-variable-scope_2_1[]" id="input_06-variable-scope_2_1_choice_3" class="field-input input-checkbox" value="choice_3"/><label id="06-variable-scope_2_1-choice_3-label" for="input_06-variable-scope_2_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_06-variable-scope_2_1"> line 15
</label>
</div>
<div class="field">
<input type="checkbox" name="input_06-variable-scope_2_1[]" id="input_06-variable-scope_2_1_choice_4" class="field-input input-checkbox" value="choice_4"/><label id="06-variable-scope_2_1-choice_4-label" for="input_06-variable-scope_2_1_choice_4" class="response-label field-label label-inline" aria-describedby="status_06-variable-scope_2_1"> line 20
</label>
</div>
<span id="answer_06-variable-scope_2_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_06-variable-scope_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_06-variable-scope_solution_1"/>
</div><p>What is the appropriate scope for the (currently undeclared) <code>address</code> variable?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 2" role="group"><div class="choicegroup capa_inputtype" id="inputtype_06-variable-scope_3_1">
<fieldset aria-describedby="status_06-variable-scope_3_1">
<div class="field">
<input type="radio" name="input_06-variable-scope_3_1" id="input_06-variable-scope_3_1_choice_0" class="field-input input-radio" value="choice_0"/><label id="06-variable-scope_3_1-choice_0-label" for="input_06-variable-scope_3_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_06-variable-scope_3_1"> lines 2-21
</label>
</div>
<div class="field">
<input type="radio" name="input_06-variable-scope_3_1" id="input_06-variable-scope_3_1_choice_1" class="field-input input-radio" value="choice_1"/><label id="06-variable-scope_3_1-choice_1-label" for="input_06-variable-scope_3_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_06-variable-scope_3_1"> lines 3-4
</label>
</div>
<div class="field">
<input type="radio" name="input_06-variable-scope_3_1" id="input_06-variable-scope_3_1_choice_2" class="field-input input-radio" value="choice_2"/><label id="06-variable-scope_3_1-choice_2-label" for="input_06-variable-scope_3_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_06-variable-scope_3_1"> line 8
</label>
</div>
<div class="field">
<input type="radio" name="input_06-variable-scope_3_1" id="input_06-variable-scope_3_1_choice_3" class="field-input input-radio" value="choice_3"/><label id="06-variable-scope_3_1-choice_3-label" for="input_06-variable-scope_3_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_06-variable-scope_3_1"> lines 12-16
</label>
</div>
<span id="answer_06-variable-scope_3_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_06-variable-scope_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_06-variable-scope_solution_2"/>
</div><p>Out of the choices below, what is the best declaration for the <code>roommates</code> variable?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 3" role="group"><div id="inputtype_06-variable-scope_4_1" class="choicegroup capa_inputtype">
<fieldset aria-describedby="status_06-variable-scope_4_1">
<div class="field">
<input id="input_06-variable-scope_4_1_choice_0" type="radio" name="input_06-variable-scope_4_1" class="field-input input-radio" value="choice_0"/><label id="06-variable-scope_4_1-choice_0-label" for="input_06-variable-scope_4_1_choice_0" aria-describedby="status_06-variable-scope_4_1" class="response-label field-label label-inline"> List<person> roommates;
</person></label>
</div>
<div class="field">
<input id="input_06-variable-scope_4_1_choice_1" type="radio" name="input_06-variable-scope_4_1" class="field-input input-radio" value="choice_1"/><label id="06-variable-scope_4_1-choice_1-label" for="input_06-variable-scope_4_1_choice_1" aria-describedby="status_06-variable-scope_4_1" class="response-label field-label label-inline"> Set<person> roommates;
</person></label>
</div>
<div class="field">
<input id="input_06-variable-scope_4_1_choice_2" type="radio" name="input_06-variable-scope_4_1" class="field-input input-radio" value="choice_2"/><label id="06-variable-scope_4_1-choice_2-label" for="input_06-variable-scope_4_1_choice_2" aria-describedby="status_06-variable-scope_4_1" class="response-label field-label label-inline"> final Set<person> roommates;
</person></label>
</div>
<div class="field">
<input id="input_06-variable-scope_4_1_choice_3" type="radio" name="input_06-variable-scope_4_1" class="field-input input-radio" value="choice_3"/><label id="06-variable-scope_4_1-choice_3-label" for="input_06-variable-scope_4_1_choice_3" aria-describedby="status_06-variable-scope_4_1" class="response-label field-label label-inline"> HashSet<person> roommates;
</person></label>
</div>
<span id="answer_06-variable-scope_4_1"/>
</fieldset>
<div class="indicator-container">
<span id="status_06-variable-scope_4_1" data-tooltip="Not yet answered." class="status unanswered">
<span class="sr">unanswered</span><span class="status-icon" aria-hidden="true"/>
</span>
</div>
</div></div>
<div class="solution-span">
<span id="solution_06-variable-scope_solution_3"/>
</div><p>Out of the choices below, what is the best declaration for the <code>MAXIMUM_OCCUPANCY</code> variable?</p>
<div class="wrapper-problem-response" tabindex="-1" aria-label="Question 4" role="group"><div class="choicegroup capa_inputtype" id="inputtype_06-variable-scope_5_1">
<fieldset aria-describedby="status_06-variable-scope_5_1">
<div class="field">
<input type="radio" name="input_06-variable-scope_5_1" id="input_06-variable-scope_5_1_choice_0" class="field-input input-radio" value="choice_0"/><label id="06-variable-scope_5_1-choice_0-label" for="input_06-variable-scope_5_1_choice_0" class="response-label field-label label-inline" aria-describedby="status_06-variable-scope_5_1"> int MAXIMUM_OCCUPANCY = 8;
</label>
</div>
<div class="field">
<input type="radio" name="input_06-variable-scope_5_1" id="input_06-variable-scope_5_1_choice_1" class="field-input input-radio" value="choice_1"/><label id="06-variable-scope_5_1-choice_1-label" for="input_06-variable-scope_5_1_choice_1" class="response-label field-label label-inline" aria-describedby="status_06-variable-scope_5_1"> final int MAXIMUM_OCCUPANCY = 8;
</label>
</div>
<div class="field">
<input type="radio" name="input_06-variable-scope_5_1" id="input_06-variable-scope_5_1_choice_2" class="field-input input-radio" value="choice_2"/><label id="06-variable-scope_5_1-choice_2-label" for="input_06-variable-scope_5_1_choice_2" class="response-label field-label label-inline" aria-describedby="status_06-variable-scope_5_1"> static int MAXIMUM_OCCUPANCY = 8;
</label>
</div>
<div class="field">
<input type="radio" name="input_06-variable-scope_5_1" id="input_06-variable-scope_5_1_choice_3" class="field-input input-radio" value="choice_3"/><label id="06-variable-scope_5_1-choice_3-label" for="input_06-variable-scope_5_1_choice_3" class="response-label field-label label-inline" aria-describedby="status_06-variable-scope_5_1"> static final int MAXIMUM_OCCUPANCY = 8;
</label>
</div>
<span id="answer_06-variable-scope_5_1"/>
</fieldset>
<div class="indicator-container">
<span class="status unanswered" id="status_06-variable-scope_5_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_06-variable-scope_solution_4"/>
</div></div>
<div class="action">
<input type="hidden" name="problem_id" value="variable scope" />
<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_06-variable-scope" >
<span class="submit-label">Submit</span>
</button>
<div class="submission-feedback" id="submission_feedback_06-variable-scope">
<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="06-variable-scope-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="06-variable-scope-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="06-variable-scope-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-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@vertical+block@Reading_6_Summary" data-block-type="vertical" data-graded="True" data-has-score="False" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="VerticalStudentView">
<h2 class="hd hd-2 unit-title">Reading 6 Summary</h2>
<div class="vert-mod">
<div class="vert vert-0" data-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_301e357ab310">
<div class="xblock xblock-public_view xblock-public_view-html xmodule_display xmodule_HtmlBlock" data-runtime-version="1" data-usage-id="block-v1:MITx+6.005.1x+3T2016+type@html+block@html_301e357ab310" data-block-type="html" data-graded="True" data-has-score="False" data-course-id="course-v1:MITx+6.005.1x+3T2016" data-runtime-class="LmsRuntime" data-request-token="8ca32b5c4c3811ef89500e6e8f39bb05" data-init="XBlockToXModuleShim">
<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" />
<h3 id="summary">Summary</h3>
<div data-outline="summary">
<p>In this reading, we looked at some ways to minimize the cost of debugging.</p>
<p><strong>Avoid debugging.</strong> Make bugs impossible with techniques like:</p>
<ul><li>static typing</li>
<li>automatic dynamic checking</li>
<li>immutable types and references</li>
</ul>
<p><strong>Keep bugs confined.</strong> Make the search for buggy code easier with techniques like:</p>
<ul>
<li>failing fast</li>
<li>incremental development and unit testing</li>
<li>scope minimization</li>
</ul>
<p>Thinking about our three main measures of code quality:</p>
<ul>
<li><strong>Safe from bugs.</strong> We're trying to prevent them and get rid of them.</li>
<li><strong>Easy to understand.</strong> Techniques like static typing, final declarations, and assertions are additional documentation of the assumptions in your code. Variable scope minimization makes it easier for a reader to understand how the variable is used because there's less code to look at.</li>
<li><strong>Ready for change.</strong> Assertions and static typing document the assumptions in an automatically-checkable way so that when a future programmer changes the code, accidental violations of those assumptions are detected.</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>