Sonoma State University
Department of Computer Science
CS-370: Software Design and Development
Exercise 20: Refactoring code to improve readability and reliability

Objective:

To refactor a code section to make it more easily readable and understandable.

The exercise:

The following code shows one way to swap the values in two integers a and b. The caret (^) operator takes the exclusive or (XOR) of the two values. The comments to the right explain how this method works.

// Swap a and b. Let A and B be the original values.
b = a ^ b; // b = A ^ B
a = a ^ b; // a = A ^ (A ^ B) = (A ^ A) ^ B = B
b = a ^ b; // b = B ^ (A ^ B) = (B ^ B) ^ A = A

This is a clever piece of code. It lets you swap two values without needing to waste memory for a temporary variable.

Questions:

  1. What assumptions did you make about variable a and variable b datatype declarations (above)?
  2. Why is the code (above) not a good programming practice?
  3. Write an improved version.

Uploading your solution:

  • This is an individual exercise, not a team exercise.
  • Please upload your answer in either PDF (Acrobat), Word (doc/docx), or as a text file.