Trying to understand what is refactoring, follow the guide from Real Python. https://realpython.com/python-refactoring
1. Functions That Should Be Objects
Without reading the code, you will not know if it will modify the original image or create a new image.
To call the codes:
Symptoms of code using functions that could be refactored into classes:
- Similar arguments across functions
- Higher number of Halstead
h2unique operands (All the variables and constants are considered operands)
- Mix of mutable and immutable functions
- Functions spread across multiple Python files
Here is a refactored version of those 3 functions, where the following happens:
crop()becomes a class method.
get_image_thumbnail()becomes a property.
The thumbnail resolution has become a class property, so it can be changed globally or on that particular instance:
This is how the refactored example would look:
In the resulting code, we have solved the original problems:
- It is clear that
thumbnailreturns a thumbnail since it is a property, and that it doesn’t modify the instance.
- The code no longer requires creating new variables for the crop operation.
2. Objects That Should Be Functions
Here are some tell-tale signs of incorrect use of classes:
- Classes with 1 method (other than
- Classes that contain only static methods
It would make more sense to just have a simple function named
authenticate() that takes
password as arguments:
3. Converting “Triangular” Code to Flat Code
These are the symptoms of highly nested code:
- A high cyclomatic complexity because of the number of code branches
- A low Maintainability Index because of the high cyclomatic complexity relative to the number of lines of code
Refactor this function by “returning early”
Another technique to reduce nesting by list comprehension
Common practise to create list, loop through and check for criteria.
4. Handling Complex Dictionaries With Query Tools
It does have one major side-effect: when dictionaries are highly nested, the code that queries them becomes nested too.
If you wanted to get the line that matched a certain number, this could be achieved in a small function:
If you wanted to get the line number for every line, you could do this:
You can provide more complex queries, like a
<. The syntax is a little unusual for Python developers, so keep the documentation handy for reference.
Find the line with the number