Reviewing and refactoring code

Case Study: Building Software in Python

Mark Pedigo

Principal Data Scientist

Benefits of periodic code review

  • Improved code quality
    • Catch inconsistencies early
  • Knowledge sharing
    • Collaboration
    • Staying aligned
  • Consistency and best practices
    • High standards

Two people reviewing code on a computer

Case Study: Building Software in Python

Code review example

def factorial(n):
    if n == 0:
        return 1
    else:
        result = 1
        for i in range(1, n + 1):
            result *= i
        return result

Give feedback concerning:

  • Functionality
  • Readability
    • Example - Unnecessary else
  • Edge Cases
    • Example - Negative numbers for a factorial
Case Study: Building Software in Python

Benefits of refactoring code

  • Improved code quality
  • Easier maintenance
  • Reduced technical debt

Spaghetti gets transformed to a flow chart

Case Study: Building Software in Python

Refactoring example

# Original code
def factorial(n):
    if n == 0:
        return 1
    else:
        result = 1
        for i in range(1, n + 1):
            result *= i
        return result
# Refactored code
def factorial(n):
    if n < 0:
        raise ValueError("Not defined")

if n == 0: return 1
result = 1 for i in range(1, n + 1): result *= i return result
Case Study: Building Software in Python

New function for a new formula

Previous formula $$m = P \cdot \frac{r (1 + r)^N}{(1+r)^N - 1}$$ where $m$ is the monthly payment, $P$ is the loan amount, $r$ is the monthly interest rate, and $N$ is the number of monthly payments

New formula $$P = m \cdot \frac{(1+r)^N - 1}{r (1 + r)^N}$$

Case Study: Building Software in Python

Roadmap

Roadmap showcasing what parts of the project we've finished and which we'll be starting

Case Study: Building Software in Python

Let's practice!

Case Study: Building Software in Python

Preparing Video For Download...