Refactoring

What is Refactoring?

  • rewriting code
  • fixing bugs
  • improve observable aspects of software such as its interface

Code Complexity in Python

Metrics for Measuring Complexity

Lines of Code

x = 5
value = input("Enter a number: ")
y = int(value)
if x < y:
print(f"{x} is less than {y}")
elif x == y:
print(f"{x} is equal to {y}")
else:
print(f"{x} is more than {y}")
x = 5; y = int(input("Enter a number:"))
equality = "is equal to" if x == y else "is less than" if x < y else "is more than"
print(f"{x} {equality} {y}")

Cyclomatic Complexity

x = 1
x = 1
if x < 2:
x += 1
x = 2
# cyclomatic_example.py
import sys
def main():
if len(sys.argv) > 1: # 1
filepath = sys.argv[1]
else:
print("Provide a file path")
exit(1)
if filepath: # 2
with open(filepath) as fp: # 3
for line in fp.readlines(): # 4
if line != "\n": # 5
print(line, end="")
if __name__ == "__main__": # Ignored.
main()
$ pip install radon
  1. The type of analysis (cc for cyclomatic complexity)
  2. A path to the file or folder to analyze
$ radon cc cyclomatic_example.py -s
cyclomatic_example.py
F 4:0 main - B (6)
  • F means function, M means method, and C means class.
  • main is the name of the function.
  • 4 is the line the function starts on.
  • B is the rating from A to F. A is the best grade, meaning the least complexity.
  • The number in parentheses, 6, is the cyclomatic complexity of the code.
  1. The red phase — is when you write a test case for the functionality you want to add. When your test fails, your code is incomplete, and you have to implement the missing functionality.
  2. The green phase — is when you write the minimal amount of code needed to make the test pass. As soon as your test passes, the implementation of this feature is done (at least for now).
  3. The refactoring phase — is the final step in the TDD cycle. It’s when you change or improve existing code without changing its external behavior. In this phase, you improve the design without breaking any functionality. You will know if you have broken a functionality if an existing test fails during refactoring. TDD naturally leads to high code coverage.

Benefits of Refactoring

  • Refactoring improves the objective attributes of the code. The components included are length, duplication, coupling and cohesion, and cyclomatic complexity which will have an impact on ease of maintenance
  • refactoring helps other people understand the code created
  • refactoring encourages every developer to think about and understand code design, especially in developing a sense of ownership of the code that has been created
  • refactoring will be very helpful when there are reusable design elements as well as modules

Sources

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store