Popcorn Hack #1: Fix the Documentation

/**
 * Calculates the sum of all positive even integers in the given array.
 *
 * This method iterates through each element in {@code nums} and adds it to a running total
 * only if it is both positive and evenly divisible by 2. The method then returns the resulting sum.
 *
 * Preconditions:
 * - {@code nums} must not be {@code null}.
 *
 * Postconditions:
 * - Returns the sum of all positive even numbers in {@code nums}.
 * - Returns {@code 0} if no such numbers exist.
 *
 * @param nums an array of integers to evaluate
 * @return the sum of all positive even integers in {@code nums}, or {@code 0} if none
 *
 * Example:
 * int[] numbers = {1, 2, 3, 4, -6};
 * int result = doSomething(numbers);  // result = 6
 */
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

/**
 * Represents a grade management system for storing and calculating student grades.
 *
 * This class maintains assignment scores organized by categories, applies custom weights
 * for each category, and can compute a final grade based on those weights. It also supports
 * optional extra credit and generates formatted grade reports.
 *
 * Key Features:
 * - Add assignments and categorize them (e.g., "Tests", "Homework").
 * - Set category weights for calculating final grades.
 * - Include extra credit.
 * - Generate summary reports of all grades.
 *
 * Example Usage:
 * GradeBook gb = new GradeBook();
 * gb.setCategoryWeight("Homework", 0.3);
 * gb.setCategoryWeight("Tests", 0.7);
 * gb.addAssignment("Homework", "HW1", 92.5);
 * double finalGrade = gb.calculateFinalGrade();
 *
 * @author Navie
 * @version 1.0
 * @since 2025-10-09
 */
public class GradeBook {
    private HashMap<String, Double> assignments;
    private HashMap<String, Double> categoryWeights;
    private double extraCredit;

    /**
     * Adds an assignment and its score to a given category.
     *
     * @param category the name of the category
     * @param name the name of the assignment
     * @param score the score received (0-100)
     */
    public void addAssignment(String category, String name, double score) { }

    /**
     * Sets the weight for a given category of assignments.
     *
     * @param category the name of the category
     * @param weight the weight as a decimal (e.g., 0.3 for 30%)
     */
    public void setCategoryWeight(String category, double weight) { }

    /**
     * Calculates the student’s final weighted grade including extra credit.
     *
     * @return the final grade as a percentage
     */
    public double calculateFinalGrade() { return 0.0; }

    /**
     * Generates a formatted grade report containing all categories and assignments.
     *
     * @return a formatted string of the student's grades and weighted averages
     */
    public String generateReport() { return ""; }
}

Homework Part 1: Rewrite the Poorly Documented Code

/**
 * Demonstrates a simple addition operation using a helper method.
 *
 * This program defines a static method {@code add} that takes two integers and returns their sum.
 * The {@code main} method initializes two integers, adds them using {@code add}, and prints the result.
 *
 * Preconditions:
 * - The integer inputs are valid and within range for integer addition.
 *
 * Postconditions:
 * - Outputs the sum of the two integers to the console.
 *
 * Example:
 * Input: 5, 10 → Output: ans is 15
 *
 * @author Navie
 * @version 1.0
 * @since 2025-10-09
 */
public class AdditionExample {
    public static void main(String[] args) {
        int x = 5;
        int y = 10;
        int z = add(x, y);
        System.out.println("ans is " + z);
    }

    /**
     * Adds two integer values and returns their sum.
     *
     * @param a the first integer
     * @param b the second integer
     * @return the sum of {@code a} and {@code b}
     */
    static int add(int a, int b) {
        return a + b;
    }
}

Explanation of improvements:

  • Changed class name to follow Java naming conventions (capitalized, descriptive).

  • Added Javadoc for both class and method.

  • Explained purpose, preconditions, and postconditions.

  • Included an example and author metadata.

  • Improved readability and clarity.

Homework Part 2: Document the Complex Method

/**
 * Attempts to enroll a student into a specific course for a given semester.
 *
 * This method validates several conditions before enrolling a student, including course capacity,
 * schedule conflicts, prerequisite requirements, and total credit hour limits. If all conditions
 * are met, the enrollment is recorded and both the student and course objects are updated.
 *
 * Preconditions:
 * - {@code studentId} and {@code courseCode} must correspond to existing records.
 * - The student must not exceed 18 credit hours after enrollment.
 * - The course must not be full.
 *
 * Postconditions:
 * - The student is added to the course's roster.
 * - The course is added to the student's schedule.
 * - The enrollment transaction is recorded.
 * - Returns {@code true} if successful, {@code false} otherwise.
 *
 * @param studentId unique identifier for the student
 * @param courseCode unique identifier for the course
 * @param semester the semester in which enrollment occurs
 * @return {@code true} if the student was successfully enrolled, otherwise {@code false}
 */
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;
}

Homework Part 3: Reflection Questions

  1. Why is documentation more important in team projects than solo projects? In team projects, documentation ensures everyone understands how code works, what methods expect, and how modules interact. Without it, collaboration slows down and maintenance becomes difficult when multiple people contribute to or inherit the same codebase.

  2. Give an example of when a method SHOULD be documented and when it SHOULD NOT. A method should be documented when it performs complex logic or has non-obvious behavior, such as error handling or algorithmic steps (e.g., recursive functions). It should not be documented when it’s a simple getter or setter that is self-explanatory (e.g., getName() or setScore()).