الأسبوع 12 · الوحدة ٢ الموضوعان الخامس والسادس: محاكاة بوابة OR بلغة VB.NET وبلغة PHP · 3 دروس
2
Tracing the OR code click by click
ICT Secondary 3 Term 1, Unit 2, Topics 5–6: pp. 48–64
GoalTrace the OR simulator with a table of clicks, and find the bug in a version that forgets the inner If.
New words
trace · to follow the code with given clicks and write down the state after eachtest case · a planned sequence of clicks together with the state you expectbug · a mistake in a program that makes it behave wronglyexpected state · the state that the rule says the program must show
Explanation
To trace the program, make a table with one row for each click: which switch was clicked, the text of A, the text of B and the lamp. The first row is the start state. For the OR simulator there is a quick check of every row: the lamp must be lit exactly when at least one text is On. In the trace below, the lamp is unlit only at step 4, where both texts are Off. A trace is also the best way to hunt a bug. Suppose the programmer forgets the inner If and writes ShowLamp(False) whenever A is switched Off. The mistake does not show on short tests, but with the clicks A, B, A the state is Off On, and the rule says that the lamp must be lit because B is still On, while the buggy code shows it unlit. A good set of test cases includes a click sequence that ends by switching a switch Off while the other is On.
Text of A
Text of B
The lamp must be
Off
Off
unlit
Off
On
lit
On
Off
lit
On
On
lit
Worked examples
Step
Click
A
B
Lamp
0
(start)
Off
Off
unlit
1
B
Off
On
lit
2
A
On
On
lit
3
A
Off
On
lit
4
B
Off
Off
unlit
5
A
On
Off
lit
6
B
On
On
lit
A trace of six clicks, starting from the start state. The lamp is unlit only after step 4.
Vb
1Private Sub SwitchA_Click(sender As Object, e As EventArgs) Handles SwitchA.Click
2 If SwitchA.Text = "Off" Then
3 SwitchA.Text = "On"4 ShowLamp(True)
5 Else
6 SwitchA.Text = "Off"7 ShowLamp(False)
8 End If
9End Sub
Output
Off On -> unlit
A bug hunt. In this version of SwitchA_Click the inner If was forgotten. The output line is the state after the clicks A, B, A. The lamp should be lit, because B is On.
Clicks
Expected state
(none)
Off, Off: unlit
A
On, Off: lit
A, A
Off, Off: unlit
B
Off, On: lit
A, B, A
Off, On: lit
A small test plan for the OR simulator. The last row catches the bug above.
Class activity
Trace the OR simulator for the clicks A, A, B, B, A starting from the start state. Write the table with the state after every click, then mark the steps at which the lamp is unlit.
Practice
1
After the clicks B and A from the start state, what do the texts and the lamp show?
On, On and the lamp lit.
2
In the OR simulator can the lamp be lit while both texts are Off?
No. The lamp is lit only when at least one text is On.
3
What is a test case?
A planned sequence of clicks together with the state you expect after it.
4
Why does the buggy click code fail on the clicks A, B, A?
Turning A Off unlights the lamp although B is still On.