Refactoring

Refactoring is the process of restructuring existing code without changing its external behavior. It is done to improve the readability, maintainability, and performance of the code.

There are a few general things to look for when identifying 'poor' code:

The Art of Continuous Refactoring

Refactoring should not be a one-time event but rather an ongoing process.

1. Testing

The first step in refactoring is checking the tests. Tests provide a safety-net for developers, allowing them to make changes to the code without fear of breaking existing functionality. Having high test-coverage speeds up refactoring time.

2. Duplicate

Make a new function or module instead of trying to update the existing code. This helps to easily compare the old and new code, possibly run A/B tests, and find their occurrences using logging or Warnings.

3. Import Warnings

The Warnings module in Python is used to alert developers to potential problems in their code. This is especially useful when refactoring code.

# Python can run in a mode where all warnings become errors
python -W error my_code.py

4. Performance Tests

Refactoring does not automatically translate to improved performance. Python's timeit library is a great tool for adding temporary performance tests.

5. Small Steps

Many incremental changes are better than one massive change. These small steps allow to continually test if any of the changes broke anything.

6. Know the Libraries

Quite often, complex code is the result of trying to re-invent some fancy algorithm. The modules itertools, functools, ABC and NumPy are packed with useful patterns and functions.

7. Iterables

Nested loops (with if-statements) can result in complex code. Sometimes it makes sense to move a loop to some function, or create an iterable object with __iter__ and __next__.

8. Focus on Modularity

Creating a simple API around some more complex code often results in more developers using the code. Modular code also allows for greater flexibility and extensibility.

9. Documentation

Refactoring does not lead to self-documenting code. The best moment to update documentation is right after refactoring.