SECTION 12 / 15

Side effects: returning a number can change a deck

2 min read
On this page 3 headings

A procedure may return the right sum and still change the data arrangement. That extra change is called a side effect. To use the procedure safely, the caller must know what happens to its input.

Moving cards top-to-top reverses their order. Transferring them back one at a time restores the original order.
Moving cards top-to-top reverses their order. Transferring them back one at a time restores the original order.

Pass the data too

SumMarks(Gender,Field) assumes a particular deck already exists. To reuse it for another class, also pass the dataset: SumMarks(Deck,Gender,Field). State whether the procedure may consume, reorder or edit that deck.

REAL COURSE DATA · FOLLOW THE PROCEDURE

Watch a procedure change a deck

Read the current record, check the explanation, and watch the variables. Use Back to revisit any step.

Ready

CURRENT RECORD

Ready to begin

No records have been processed. Start with Next step.

What we remember

Processed
0

Start at the first step. Watch the current row and the values we remember.

All cards returned is not the same as original order

Start with top-to-bottom IDs 0,1,2. Move each top card onto the top of SeenDeck: the new top-to-bottom order is 2,1,0. Renaming SeenDeck as Deck gives every card back, but in reverse order. A second top-to-top transfer reverses it again and restores 0,1,2.

For a sum, order does not change the answer: 68+62 equals 62+68. However, leaving the original deck empty breaks a later call unless the interface explicitly says it consumes the deck. In the lab, compare “Move cards back one at a time” with “Rename the seen pile”. Both retain the marks sum 2,171, but only the former restores sequence.

Not every procedure needs a useful return value

UpdateMarks(CardNo,Field,NewValue) may be called as a statement because its purpose is to change a record. If a mark changes, keep the stored Total consistent too. Sorting also intentionally changes order; for such a procedure the change is its goal, not an unwanted surprise.

Try it yourself

Can a correct sum hide an unwanted side effect?

Show explained answer

Yes. The sum can be correct while the input deck is emptied or reordered.

Try it yourself

What order results from moving 0,1,2 top-to-top into a new pile?

Show explained answer

2,1,0, read top-to-bottom.

Try it yourself

Does renaming a reversed pile restore sequence?

Show explained answer

No. It returns the cards but preserves the reversed sequence.

Try it yourself

Why pass Deck as an argument?

Show explained answer

So the same procedure can work on different datasets rather than one hidden fixed pile.

Try it yourself

Is reordering always a bug?

Show explained answer

No. Sorting intentionally reorders data. Whether a change is acceptable depends on the contract.

YOUR STUDY PROGRESS

Finished this section? Save your progress.

Back to top ↑