Skip to the content.

Documentation with Comments

Lesson Hack #1: Fix the Documentation

Task: The following code has poor documentation. Rewrite it with proper Javadoc comments including preconditions and postconditions.

/**
 * Calculates the sum of all positive even integers in the given array.
 *
 * <p>This method iterates through each element of the input array {@code nums} and adds 
 * the element to the result only if it is both positive and even.</p>
 *
 * <pre>
 * Example:
 * int[] values = {1, 2, -4, 6, 7};
 * doSomething(values); // returns 8 (2 + 6)
 * </pre>
 *
 * @param nums an array of integers to process
 * @return the sum of all positive even numbers in {@code nums}
 *
 * @precondition {@code nums} is not {@code null}.
 * @postcondition the returned value is the total sum of all elements in {@code nums} 
 *                that are greater than zero and divisible by two.
 */
public int doSomething(int[] nums) {
    int result = 0;
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] > 0 && nums[i] % 2 == 0) {
            result += nums[i];
        }
    }
    return result;
}

Your task: Write proper Javadoc documentation for this method in the code cell below.


/**
 * Calculates the sum of all positive even integers in the given array.
 * <p>
 * This method loops through each element of {@code nums} and adds it to a running total
 * only if the element is greater than zero and evenly divisible by two.
 * The method then returns the resulting sum.
 * </p>
 *
 * <p><b>Preconditions:</b></p>
 * <ul>
 *   <li>{@code nums} must not be {@code null}.</li>
 *   <li>{@code nums} may contain any integers (positive, negative, or zero).</li>
 * </ul>
 *
 * <p><b>Postconditions:</b></p>
 * <ul>
 *   <li>Returns the sum of all positive even numbers in {@code nums}.</li>
 *   <li>If there are no positive even numbers, returns {@code 0}.</li>
 * </ul>
 *
 * @param nums an array of integers to evaluate
 * @return the sum of all positive even integers in {@code nums}; {@code 0} if none exist
 *
 * <p><b>Example usage:</b></p>
 * <pre>
 * int[] numbers = {1, 2, 3, 4, -6};
 * int result = doSomething(numbers);  // result = 6
 * </pre>
 */
public int doSomething(int[] nums) {
    int result = 0;
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] > 0 && nums[i] % 2 == 0) {
            result += nums[i];
        }
    }
    return result;
}

Popcorn Hack #2: Write Class Documentation

Your Mission: Add Javadoc comments to document this GradeBook class!

What to include:

  • What does this class do? (purpose)
  • What are the main features? (key methods)
  • How would someone use it? (example)
  • Tags: @author, @version, @since
/**
 * The {@code GradeBook} class represents a digital record of a student's assignments,
 * categories, and grades. It allows users to manage assignments, set category weights,
 * and calculate a weighted final grade. Extra credit can also be applied to improve
 * the overall grade.
 *
 * <p><b>Main Features:</b></p>
 * <ul>
 *   <li>Add and organize assignments by category</li>
 *   <li>Assign weights to grading categories</li>
 *   <li>Calculate the final weighted grade</li>
 *   <li>Generate a detailed performance report</li>
 * </ul>
 *
 * <p><b>Example Usage:</b></p>
 * <pre>
 * GradeBook gb = new GradeBook();
 * gb.setCategoryWeight("Homework", 0.4);
 * gb.setCategoryWeight("Tests", 0.6);
 * gb.addAssignment("Homework", "HW1", 95);
 * gb.addAssignment("Tests", "Midterm", 88);
 * double finalGrade = gb.calculateFinalGrade();
 * System.out.println(gb.generateReport());
 * </pre>
 *
 * @author Aadi Bhat
 * @version 1.0
 * @since 2025-10-12
 */
public class GradeBook {
    private HashMap<String, Double> assignments;
    private HashMap<String, Double> categoryWeights;
    private double extraCredit;
    
    /**
     * Adds an assignment to the grade book under a specific category with a given score.
     *
     * @param category the category the assignment belongs to (e.g., "Homework", "Tests")
     * @param name the name of the assignment
     * @param score the score achieved on the assignment
     *
     * @precondition {@code category} and {@code name} are not {@code null}; {@code score} ≥ 0
     * @postcondition the assignment is stored in the grade book for grade calculation
     */
    public void addAssignment(String category, String name, double score) { }
    
    /**
     * Sets the weight of a specific category used in final grade calculations.
     *
     * @param category the name of the category
     * @param weight the weight of the category (typically between 0.0 and 1.0)
     *
     * @precondition {@code category} is not {@code null}; 0.0 ≤ {@code weight} ≤ 1.0
     * @postcondition the category weight is updated or added to the grade book
     */
    public void setCategoryWeight(String category, double weight) { }
    
    /**
     * Calculates the final weighted grade for all assignments.
     * The calculation considers category weights and extra credit.
     *
     * @return the final grade as a percentage (0–100)
     *
     * @precondition at least one assignment and category weight exist
     * @postcondition no data is modified during this operation
     */
    public double calculateFinalGrade() { return 0.0; }
    
    /**
     * Generates a formatted report summarizing assignments, category averages,
     * weights, and the final grade.
     *
     * @return a string containing the detailed grade report
     *
     * @precondition the grade book contains at least one assignment
     * @postcondition the returned string provides a readable summary of all grade data
     */
    public String generateReport() { return ""; }
}

Check your answer below!

/**
 * Manages student grades and calculates final grades based on weighted categories.
 * 
 * This class allows teachers to track assignments across different categories
 * (like homework, tests, projects) and calculate final grades using custom weights.
 * 
 * Key Features:
 * - Store assignments by category
 * - Apply custom weights to each category
 * - Track extra credit points
 * - Generate grade reports
 * 
 * Usage Example:
 * GradeBook myGrades = new GradeBook();
 * myGrades.setCategoryWeight("Homework", 0.30);
 * myGrades.setCategoryWeight("Tests", 0.70);
 * myGrades.addAssignment("Homework", "HW1", 95.0);
 * double finalGrade = myGrades.calculateFinalGrade();
 * 
 * @author Your Name
 * @version 1.0
 * @since 2025-10-06
 */
public class GradeBook {
    private HashMap<String, Double> assignments;
    private HashMap<String, Double> categoryWeights;
    private double extraCredit;
    
    /**
     * Adds an assignment score to a specific category.
     * 
     * @param category the category name (e.g., "Homework", "Tests")
     * @param name the assignment name
     * @param score the score earned (0-100)
     */
    public void addAssignment(String category, String name, double score) { }
    
    /**
     * Sets the weight for a grade category.
     * 
     * @param category the category name
     * @param weight the weight as a decimal (e.g., 0.30 for 30%)
     */
    public void setCategoryWeight(String category, double weight) { }
    
    /**
     * Calculates the final weighted grade including extra credit.
     * 
     * @return the final grade as a percentage
     */
    public double calculateFinalGrade() { }
    
    /**
     * Generates a formatted report of all grades and categories.
     * 
     * @return a String containing the grade report
     */
    public String generateReport() { }
}

Homework Assignment

Part 1: Documentation Analysis

Submission: https://docs.google.com/forms/d/e/1FAIpQLSepOCmW6KeE7jw4f80JO4Kad5YWeDUHKTpnNxnCPTtj9WEAsw/viewform?usp=header Rewrite the poorly written code. Write them with proper Javadoc comments.

  1. The original code:
/*
public class stuff{
public static void main(String args[]){
int x=5;
int y=10;
int z=add(x,y);
System.out.println("ans is "+z);
}

static int add(int a,int b){
return a+b;
}
}
 */

My new code:

/**
 * Demonstrates basic addition of two integers and prints the result.
 * <p>
 * This program defines a simple method to add two numbers and uses it in the main method.
 * </p>
 * 
 * <pre>
 * Example:
 * int sum = add(5, 10); // returns 15
 * </pre>
 * 
 * @author Aadi Bhat
 * @version 1.0
 * @since 2025-10-12
 */
public class Calculator {

    /**
     * Main method to run the program. Initializes two numbers, adds them, 
     * and prints the result.
     * 
     * @param args command-line arguments (not used)
     */
    public static void main(String[] args) {
        int x = 5;
        int y = 10;
        int z = add(x, y);
        System.out.println("The sum is " + z);
    }

    /**
     * Adds two integers and returns the sum.
     * 
     * @param a the first integer
     * @param b the second integer
     * @return the sum of {@code a} and {@code b}
     *
     * @precondition none
     * @postcondition returns the correct sum of the two input integers
     */
    static int add(int a, int b) {
        return a + b;
    }
}

Submit:

  1. Your improved version
  2. A brief explanation of what you improved

Part 2:

Problem 1: Document a Complex Method Write complete Javadoc documentation for this method:

public boolean enrollStudent(String studentId, String courseCode, int semester) { Student student = findStudentById(studentId); if (student == null) return false;

Course course = findCourseByCode(courseCode);
if (course == null) return false;

if (course.isFull()) return false;
if (student.hasScheduleConflict(course)) return false;
if (!student.hasPrerequisites(course)) return false;
if (student.getCreditHours() + course.getCreditHours() > 18) return false;

student.addCourse(course);
course.addStudent(student);
recordEnrollmentTransaction(studentId, courseCode, semester);
return true; }

My documenation:

/**
 * Attempts to enroll a student in a specific course for a given semester.
 *
 * <p>This method performs several checks before enrollment:
 * <ul>
 *     <li>Verifies that the student exists.</li>
 *     <li>Verifies that the course exists.</li>
 *     <li>Checks if the course is full.</li>
 *     <li>Checks for schedule conflicts with the student's existing courses.</li>
 *     <li>Checks that the student has completed all prerequisites for the course.</li>
 *     <li>Ensures that enrolling in this course does not exceed the 18-credit-hour limit.</li>
 * </ul>
 * If all checks pass, the student is added to the course, the course is added to the
 * student's schedule, and the enrollment transaction is recorded.
 * </p>
 *
 * @param studentId the unique identifier of the student attempting to enroll
 * @param courseCode the unique code of the course to enroll in
 * @param semester the semester number for which the enrollment is requested
 * @return {@code true} if enrollment was successful, {@code false} otherwise
 *
 * @precondition {@code studentId} and {@code courseCode} are not null or empty; {@code semester} > 0
 * @postcondition if the method returns {@code true}, the student is added to the course and
 *                the enrollment is recorded; otherwise, no changes are made
 */
public boolean enrollStudent(String studentId, String courseCode, int semester) {
    Student student = findStudentById(studentId);
    if (student == null) return false;

    Course course = findCourseByCode(courseCode);
    if (course == null) return false;

    if (course.isFull()) return false;
    if (student.hasScheduleConflict(course)) return false;
    if (!student.hasPrerequisites(course)) return false;
    if (student.getCreditHours() + course.getCreditHours() > 18) return false;

    student.addCourse(course);
    course.addStudent(student);
    recordEnrollmentTransaction(studentId, courseCode, semester);
    return true;
}

Part 3: Reflection Questions

  1. Why is documentation more important in team projects than solo projects?

Answer:

Documentation is more important in team proejcts than in solo projects, because in team projects it is important that other people understand what your code does and that you understand what other people’s code does. Documentation helps to convey what your code does among other information. In solo projects, you would likely have a good idea of all aspects of the code you created, so there is not much reason to be documenting it unless you plan on sharing it with others.

  1. Give an example of when a method SHOULD be documented and when it SHOULD NOT.

Answer:

Complex methods that have multiple checks or have important side effects should always have detailed documentation. Simple helper methods don’t really need documentation, especially if the name of the method describes its purpose well enough.

Submit: A Jupyter notebook or Java file with all three parts completed.