Lab 8: Refactoring
Contents
Instructions
In this lab, we will gain more experience with
Now, refactoring is not necessarily an intuitive process. So, while this lab will be focused on the program below, you can see how the three phases might be done on an example program here.
Phase 1: Reducing repeated code
For this phase, copy and paste the program above into a new file called lab8-phase1.cpp. The point of this phase is to find code that is repeated verbatim throughout the program and replace it with a function. Repeated code might only be one line, or it could be a set of many lines. For example, see the functions created for phase 1 in the example program.
Find as many pieces of identically repeated code in the blackjack program. For each, create a new function for that code and replace the code in main with an invocation of the function you created.
Phase 2: Modularizing code
Copy your code from phase 1 and paste it in a new file called
lab8-phase2.cpp. This phase focuses on breaking your code into
conceptual modules, where each module gets its own function. This will
involve taking the code in main and then creating a hierarchy of logical
steps. Each level of the hierarchy should be at a similar level of abstraction,
with the levels closer to main being more abstract (e.g., runGame()
in the example),
and the levels further
away being less abstract (e.g., promptPlayerForDoorChoice()
in
the example).
In your lab8-phase2.cpp file, make a logical hierarchy of steps for the blackjack program and make a function for each logical component. Then reorganize the program to use those functions. Note that, just like in the example, main should have only one invocation and the return statement.
Phase 3: Increasing reusability
Copy your code from phase 2 and paste it in a new file called lab8-phase3.cpp. In this phase, you will create functions for code that is repeated, but where each use of that code is a little different. For instance, in phase 3 of the example, it is pointed out that the code to relabel doors for the door graphic is repeated quite often, but each time a different door variable and label is used. However, since functions can take parameters, we identified these two variable values as good parameter candidates.
Find as many pieces of similar, but not necessarily identical, code that can be generalized and wrapped into a single function to reduce the total size of the program. Implement each function in lab8-phase3.cpp and replace the repeated code with invocations of the corresponding function.
Submission
Submit your .cpp files to here. You can view the rubric here.
(Back to top)