RustBrock/Reducing_Code_Duplication.md
2025-01-31 19:28:27 -07:00

2.6 KiB

Removing Duplcation by Extracting a Function

Generics allow us to replace specific tpyes with a placeholder that represents multiple values

Lets look at how to remove duplication in a way that doesnt invlove generic types by extracting a function that replaces specific values with a generics.

By being able to recognize duplicated code you can extract into a funct, you can start to recognize duplicated code that use generics

Lets look at some code that finds the largest number in a list

fn main() {
    let number_list = vec![34, 50, 25, 100, 65];

    let mut largest = &number_list[0];

    for number in &number_list {
        if number > largest {
            largest = number;
        }
    }

    println!("The largest number is {largest}");

    let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];

    let mut largest = &number_list[0];

    for number in &number_list {
        if number > largest {
            largest = number;
        }
    }

    println!("The largest number is {largest}");
}

Although it owrks, duplicated code is tedious and error prone, also you have to update the code in multiple places when we want to change it

To eliminate duplication you can create an abstraction by defining a function that operates on any list of integers passed in as a parameter

This makes our code clearer

Here is the same code by extracted into a function that finds the largest number in a i32 list

fn largest(list: &[i32]) -> &i32 {
    let mut largest = &list[0];

    for item in list {
        if item > largest {
            largest = item;
        }
    }

    largest
}

fn main() {
    let number_list = vec![34, 50, 25, 100, 65];

    let result = largest(&number_list);
    println!("The largest number is {result}");

    let number_list = vec![102, 34, 6000, 89, 54, 2, 43, 8];

    let result = largest(&number_list);
    println!("The largest number is {result}");
}

The parameter of the largest function called list represents any concrete slice of i32 values that might be passed into the funct

Here are the steps taken to change the code from the original to the second with the abstracted function:

  1. Identify duplicate code
  2. Extract the duplicated code into a function, and specify the inputs and return values of that code in the funct signature
  3. Update the two instances of dplicated code to make a call to the funct instead

We can use these smae steps with generics to reduce code duplication, in the same way the fnction body can operate on an abstract list instead of specific values

Generics allow code to operate on abstract types