Skip to main content

Practice Code Structure

Section 1.40 Identification

Activity 1.40.1.

    These code blocks are the ones you saw in the previous question and they all have the same functionality. Among these options which one is preferable?
  • public static double calculatePrice(double price, boolean isHoliday, boolean isClearance) {
       if (isHoliday) {
          return price - (price * 0.10);
       } else if (isClearance) {
          return price - (price * 0.20);
       } else {
          return price;
       }
    }
    
  • This code can be improved!
  • public static double calculatePrice(double price, boolean isHoliday, boolean isClearance) {
        double discountRate = 0.0;
        if (isHoliday) {
           discountRate = 0.10;
        } else if (isClearance) {
           discountRate = 0.20;
        }
        return price * (1- discountRate);
    }
    
  • Correct!
  • public static double calculatePrice(double price, boolean isHoliday, boolean isClearance) {
        double finalPrice;
        if (isHoliday) {
          finalPrice = price - (price * 0.10);
        } else if (isClearance) {
          finalPrice = price - (price * 0.20);
        } else {
          finalPrice = price;
        }
        return finalPrice;
    }
    
  • This code can be improved!
You have attempted 1 of 2 activities on this page.