Continue Developing the calculateDiscount Function

Continue Developing the CalculateDiscount Function

Welcome to your second lesson, which delves deeper into Test Driven Development (TDD) practices using Rust. In this unit, we will extend the functionality of our calculate_discount function by implementing five new requirements.

Building on the previous unit, this course emphasizes practical experience by sequentially providing requirements through tests. Your mission is to implement code that satisfies each test, mirroring a real-world TDD scenario. Consider this guide your pair programmer, offering test-driven prompts to enhance your expertise incrementally.

Understanding the Red-Green-Refactor Cycle

As a reminder, the Red-Green-Refactor cycle is crucial in TDD, steering your development process:

  • Red: Begin by writing a failing test to define what to do next.
  • Green: Develop just enough code to pass the test, concentrating on meeting the functionality.
  • Refactor: Enhance the code for clarity and efficiency without changing its behavior.

More Requirements for CalculateDiscount Function

6. Negative Discount Percentage

  • Description: The function should not accept negative discount percentages and must return an error in such cases.
  • Test Case:
    #[cfg(test)]
    mod tests {
        use project::*;
    
        #[test]
        fn test_calculate_discount_negative_discount_returns_error() {
            // Arrange
            let original_price = 100.0;
            let discount_percentage = -10.0;
    
            // Act
            let result = calculate_discount(original_price, discount_percentage);
    
            // Assert
            assert!(result.is_err());
            assert_eq!(result.unwrap_err(), "discount cannot be negative");
        }
    }

7. Handling Very Small Prices

  • Description: The function should ensure that discounted prices don’t dip below the minimum limit due to very small original prices.
  • Test Case:
    #[cfg(test)]
    mod tests {
        use project::*;
    
        #[test]
        fn test_calculate_discount_handles_very_small_prices_correctly() {
            // Arrange
            let original_price = 0.001;
            let discount_percentage = 1.0;
            let expected_discounted_price = 0.01;
    
            // Act
            let result = calculate_discount(original_price, discount_percentage).unwrap();
    
            // Assert
            assert!((result - expected_discounted_price).abs() < 0.01);
        }
    }

8. Minimum Discount Percentage Application

  • Description: Apply a minimum 1% discount if a lesser discount percentage is provided.
  • Test Case:
    #[cfg(test)]
    mod tests {
        use project::*;
    
        #[test]
        fn test_calculate_discount_should_apply_minimum_discount_amount_when_discount_is_less_than_minimum() {
            // Arrange
            let original_price = 100.0;
            let discount_percentage = 0.1; // 0.1% discount
            let expected_discounted_price = 99.0; // Should apply minimum 1% discount
    
            // Act
            let result = calculate_discount(original_price, discount_percentage).unwrap();
    
            // Assert
            assert!((result - expected_discounted_price).abs() < 0.01);
        }
    }

9. Capping Maximum Discount Amount

  • Description: Cap the discount amount at a maximum dollar value of $500, regardless of higher calculated discounts.
  • Test Case:
    #[cfg(test)]
    mod tests {
        use project::*;
    
        #[test]
        fn test_calculate_discount_should_cap_maximum_discount_amount_at_500() {
            // Arrange
            let original_price = 2500.0;
            let discount_percentage = 30.0;
            let expected_discounted_price = 2000.0;
    
            // Act
            let result = calculate_discount(original_price, discount_percentage).unwrap();
    
            // Assert
            assert_eq!(expected_discounted_price, result);
        }
    }

Summary and Preparation for Practice Exercises

In this section, you explored advanced requirements for the calculate_discount function. It included handling invalid inputs, ensuring very small prices remain above defined limits, and applying specific discount constraints, such as a minimum discount percentage and capping the maximum allowable discount.

As you proceed with practice exercises, remember the Red-Green-Refactor cycle to guide your method:

  • Each test encourages you to sharpen the function's reliability by beginning with a "Red" phase, writing tests for new edge situations.
  • Focus on passing each test in the "Green" phase by progressively implementing the necessary logic, such as input validation and boundary enforcement.
  • The "Refactor" phase allows you to simplify and optimize your code post-testing success, ensuring it is accurate and easily maintainable.

These exercises reinforce your TDD abilities by applying practical constraints and validations, simulating real-world scenarios where the robustness and reliability of code are pivotal.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal