Refactoring Exercise
This exercise is supplementary to my live lectures on refactoring in Week 6. I will assume that you have already attended/watched the live lecture, or already know what Template Method and Strategy Patterns are.
Just like my live coding session in the lecture, you now get the chance to refactor some code using the Template Method Pattern and the Strategy Pattern.
Many thanks to Robert Chatley for allowing me to reuse this exercise from his Software Engineering Design course. I have adapted the code to Python and reworked it to suit my needs.
Your task
-
Download sequence.py.
- Examine the code.
- There are two classes: FibonacciSequence and TriangleNumberSequence. Try to understand what each class does.
- What does the
term()method of each class return? - How is the
lengthkeyword argument in both constructors used? - The
__iter__()and__next__()methods allow Python to treat these classes as a Sequence.
-
Run the code (
python3 sequence.py). It should work and generate the correct sequences. -
Now compare the two classes. There seems to be a lot of duplication, doesn’t it? Identify parts of the code that are similar, and parts that are different.
-
Make a copy of
sequence.pyand name ittemplate.py. -
Now, try to refactor the code in
template.pyto reduce the duplication using a Template Method pattern. Runpython3 template.pyto make sure that your code is still behaving correctly. -
Now, make another copy of
sequence.pyand this time name itstrategy.py. You can also copy fromtemplate.pyinstead if you prefer. - Now, try to refactor the code in
strategy.pyto reduce the duplication using a Strategy pattern. You will also need to update the test code accordingly. Runpython3 strategy.pyto test that your code is behaving as expected.
I will provide a sample solution for this exercise some time in Week 9. Do try this exercise yourself first before peeking at the solutions!