This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Exercise 3

Refactoring

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

  1. Download sequence.py.

  2. 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.
  3. Run the code (python3 sequence.py). It should work and generate the correct sequences.

  4. 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.

  5. Make a copy of sequence.py and name it template.py.

  6. Now, try to refactor the code in template.py to reduce the duplication using a Template Method pattern. Run python3 template.py to make sure that your code is still behaving correctly.

  7. Now, make another copy of sequence.py and this time name it strategy.py. You can also copy from template.py instead if you prefer.

  8. 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. Run python3 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!