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
length
keyword 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.py
and name ittemplate.py
. -
Now, try to refactor the code in
template.py
to reduce the duplication using a Template Method pattern. Runpython3 template.py
to make sure that your code is still behaving correctly. -
Now, make another copy of
sequence.py
and this time name itstrategy.py
. You can also copy fromtemplate.py
instead if you prefer. - Now, try to refactor the code in
strategy.py
to reduce the duplication using a Strategy pattern. You will also need to update the test code accordingly. Runpython3 strategy.py
to 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!