Get startedGet started for free

Reviewing and refactoring code

1. Reviewing and refactoring code

Welcome back! The code is looking clean and professional. Now, you'll explore the importance of regular code reviews, and the benefits of refactoring your code.

2. Benefits of periodic code review

Recognizing the value of code reviews, you ask a knowledgeable colleague about their benefits. She highlights that regular reviews improve code quality, facilitate knowledge sharing, and ensure best practices. Frequent reviews catch bugs and inconsistencies early, leading to cleaner, more reliable code. They also foster collaboration and help team members stay aligned and learn from each other. Consistent code reviews maintain high standards and best practices across the project.

3. Code review example

If asked to review this code, here are some key points: The function correctly calculates the factorial for positive numbers and handles \( n = 0 \) well, with solid logic. The code is easy to follow, but it could be even clearer by removing the unnecessary `else` statement. The function doesn't handle negative numbers, which lack a factorial. Adding a check for this would enhance the code.

4. Benefits of refactoring code

You ask your colleague if existing code ever needs rewriting or modification. She explains that refactoring is common and beneficial. Refactoring improves code quality by simplifying and cleaning up the code, making it more efficient, readable, and maintainable. It also speeds up future updates and bug fixes by reducing complexity. By correcting poor design choices, refactoring reduces technical debt, making the code base more sustainable and easier to work with over time.

5. Refactoring example

On the left is the original code. You implement the changes suggested in the code review. First, handle the edge case where n is negative by raising a `ValueError`. The logic for n equals 0 is solid and requires no changes. The `else` statement is unnecessary and can be removed.

6. New function for a new formula

In Chapter 2, you learned the formula for calculating monthly payments based on a loan amount, annual interest rate, and loan term. You can rearrange this formula to solve for the loan amount, given the other variables. You'll code this function in the exercises.

7. Roadmap

Here is a brief recap of how far you've come so far. We are almost done!

8. Let's practice!

Now practice reviewing and refactoring code.

Create Your Free Account

or

By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.