Skip to content

AI Code Review Findings #3

@NaveedBhat

Description

@NaveedBhat

Hello. I have reviewed your code. While the logic for calculating the average is correct, there are several issues regarding resource management, naming conventions, and robustness.

Here is the detailed code review:

1. Resource Leak (Bugs / Best Practice)

  • Severity: Medium
  • Description: The Scanner object is opened but never closed. In Java, objects that wrap underlying resources (like System.in) should be closed to prevent memory leaks and resource exhaustion.
  • Recommendation: Use a try-with-resources block or call sc.close() in a finally block.

2. Lack of Input Validation (Runtime Errors)

  • Severity: Medium
  • Description: The code assumes the user will always enter a valid double. If a user enters text (e.g., "abc"), the program will throw an InputMismatchException and crash.
  • Recommendation: Use sc.hasNextDouble() to check input before reading or wrap the logic in a try-catch block to handle invalid inputs gracefully.

3. Violation of Naming Conventions (Code Quality)

  • Severity: Low
  • Description: The method is named Average (starting with an uppercase letter). In Java, method names should follow lowerCamelCase. Additionally, the class name Exercise_1_Question_1 uses underscores, which is generally discouraged in favor of PascalCase (e.g., AverageCalculator).
  • Recommendation: Rename the method to calculateAverage or printAverage. Rename the class to AverageCalculator.

4. Logic Separation / Single Responsibility Principle (Best Practice)

  • Severity: Low
  • Description: The method Average performs two tasks: it calculates the value AND prints it. This makes the method less reusable. If you later wanted to use the average for another calculation without printing it, you couldn't use this method.
  • Recommendation: The method should return the double value, and the printing should be handled by the caller (the main method).

5. Hardcoded Divisor (Best Practice)

  • Severity: Low
  • Description: While using 3 is mathematically correct here, when working with floating-point math, it is best practice to use double literals (e.g., 3.0) to ensure precision is maintained throughout the operation and to avoid any accidental integer division in future modifications.
  • Recommendation: Change the formula to (a + b + c) / 3.0.

Optimized Code Example

Here is a refactored version of your code addressing the points above:

import java.util.Scanner;
import java.util.InputMismatchException;

/**
 * A utility to calculate the average of three numbers.
 */
public class AverageCalculator {

    /**
     * Calculates the average of three double values.
     * @return the average result
     */
    public static double calculateAverage(double a, double b, double c) {
        return (a + b + c) / 3.0;
    }

    public static void main(String[] args) {
        // Try-with-resources ensures the Scanner is closed automatically
        try (Scanner sc = new Scanner(System.in)) {
            System.out.println("Enter Three Numbers: ");
            
            double a = sc.nextDouble();
            double b = sc.nextDouble();
            double c = sc.nextDouble();

            double result = calculateAverage(a, b, c);
            System.out.printf("The Average of the numbers is: %.2f%n", result);
            
        } catch (InputMismatchException e) {
            System.err.println("Error: Please enter valid numeric values.");
        }
    }
}

Key Changes Made:

  1. Try-with-resources: Added try (Scanner sc = ...) to prevent resource leaks.
  2. Naming: Renamed the method to calculateAverage (lowerCamelCase).
  3. Return Value: The method now returns a double instead of printing directly.
  4. Error Handling: Added a try-catch block to handle non-numeric input.
  5. Formatting: Used System.out.printf to control decimal places in the output for a cleaner UI.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions