Lesson 2
Refactoring Techniques in Java
Introduction

Hello, Explorer! Today is about refactoring. Consider it as organizing your favorite toys in the toybox. We're going to learn about the Extract Method, Rename Method, and Substitute Algorithm refactorings. Refactoring helps us make our code cleaner and neater while keeping the functionality the same!

Refactoring Overview

Imagine having a complex map. Refactoring transforms it into simpler directions. Our code gets rearranged to make it more readable and efficient without altering what it does. Let's consider a small code snippet before and after refactoring:

Java
1// Before refactoring 2public double calculate(double total, int quantity) { 3 double price = total / quantity; 4 double tax = price * 0.2; 5 double totalPrice = price + tax; 6 return totalPrice; 7} 8 9// After refactoring 10public double calculateTotalPrice(double total, int quantity) { 11 double price = calculatePrice(total, quantity); 12 double tax = calculateTax(price); 13 return price + tax; 14} 15 16public double calculatePrice(double total, int quantity) { 17 return total / quantity; 18} 19 20public double calculateTax(double price) { 21 return price * 0.2; 22}

Both versions of the code do the same thing, but the latter is simpler and easier to understand!

Understanding the Extract Method

Imagine a large recipe for a complete breakfast. The Extract Method technique is like having separate recipes for eggs, toast, coffee, etc., instead of one large recipe. Take a look at this code:

Java
1// Before refactoring 2public String greetUser(String username) { 3 username = username.trim().toLowerCase(); // Prepare the username 4 String message = "Hello, " + username + "!"; // Prepare the message 5 return message; // Return the prepared message 6} 7 8// After refactoring 9public String cleanUsername(String username) { 10 return username.trim().toLowerCase(); // Returns a cleaned version of the username 11} 12 13public String greetUser(String username) { 14 username = cleanUsername(username); // Clean the username 15 String message = "Hello, " + username + "!"; // Prepare and return the message 16 return message; 17}

Here, we moved the username preparation from greetUser into its own function cleanUsername. Nice and tidy!

Using Rename Method

Clear method names make it easy to understand our code, just as clear street names make navigating a city more accessible. Let's have a look at renaming a method:

Java
1// Before refactoring 2public double fx(double x) { 3 return 3.14 * (x * x); // Calculates a value that is pi times the square of x 4} 5 6// After refactoring 7public double calculateCircleArea(double radius) { 8 return 3.14 * (radius * radius); // Calculates the area of a circle with a given radius 9}

Renaming the function fx to calculateCircleArea makes it easier to understand its purpose.

Discovering Substitute Algorithm

Substitute Algorithm involves replacing a part of a code (an algorithm) with a simpler one, analogous to discovering a faster route to school. Here's an example:

Java
1// Before refactoring 2public int findSmallest(int[] numbers) { 3 int smallest = Integer.MAX_VALUE; 4 for (int num : numbers) { 5 if (num < smallest) { 6 smallest = num; 7 } 8 } 9 return smallest; 10} 11 12// After refactoring 13import java.util.Collections; 14import java.util.Arrays; 15import java.util.List; 16 17public int findSmallest(int[] numbers) { 18 List<Integer> numberList = Arrays.stream(numbers).boxed().toList(); 19 return Collections.min(numberList); // Returns the smallest number from 'numbers' 20}

Just like the Collections.min() method in Java, it performs the same job as our previous function, but with less code.

Lesson Summary

Great work! We've learned how to use the Extract Method, Rename Method, and Substitute Algorithm to keep our code clean and efficient. Now, it's time for some hands-on practice with real examples. Remember, practice makes perfect. Let's do some refactoring!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.