Skip to the content.

Big Idea 1 Lesson 1.8

Big Idea 1 Lesson 1.8

Popcorn Hacks

Popcorn Hack 1

/**
 * Sums all positive even integers in the given array.
 *
 * @param nums array of integers, must not be null
 * @return sum of positive even numbers, or 0 if none
 */

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

/**
 * Grade book for storing assignments, category weights, and extra credit.
 * Can add assignments, set weights, calculate final grade, and generate a report.
 *
 * @author Your Name
 * @version 1.0
 * @since 2025-10-10
 */
public class GradeBook {

    private HashMap<String, Double> assignments;
    private HashMap<String, Double> categoryWeights;
    private double extraCredit;

    /**
     * Adds an assignment with category, name, and score.
     */
    public void addAssignment(String category, String name, double score) { }

    /**
     * Sets the weight for a grading category.
     */
    public void setCategoryWeight(String category, double weight) { }

    /**
     * Calculates the weighted final grade including extra credit.
     */
    public double calculateFinalGrade() { return 0.0; }

    /**
     * Generates a text report of grades and final score.
     */
    public String generateReport() { return ""; }
}

Homework Hack

Part 1

/**
 * Demonstrates adding two integers and printing the result.
 * This class shows basic usage of a utility method for addition.
 */
public class Stuff {

    /**
     * Runs the program: adds two numbers and prints the result.
     * Example usage:
     * java Stuff
     * Output: Result: 15
     *
     * @param args command-line arguments (not used)
     */
    public static void main(String[] args) {
        int x = 5;
        int y = 10;
        int z = add(x, y); // sum x and y
        System.out.println("Result: " + z);
    }
}
    /**
     * Returns the sum of two integers.
     * Assumes neither value will cause integer overflow.
     * Example usage:
     * int result = add(3, 7); // ret*

Part 2

/**
 * Attempts to enroll a student in a course for a given semester.
 *
 * This method performs several checks before enrollment:
 * - Verifies that the student exists.
 * - Verifies that the course exists.
 * - Ensures the course is not full.
 * - Checks for schedule conflicts with the student's existing courses.
 * - Verifies the student meets all prerequisites for the course.
 * - Ensures the student's total credit hours do not exceed 18 after enrollment.
 *
 * If all checks pass, the course is added to the student's schedule,
 * the student is added to the course roster, and the enrollment transaction
 * is recorded.
 *
 * Assumptions:
 * - studentId and courseCode are valid, non-null strings.
 * - semester is a valid semester identifier.
 * - Credit hours for all courses are positive integers.
 *
 * Return value:
 * - true if enrollment succeeds.
 * - false if any check fails (student/course not found, course full, schedule conflict,
 *   missing prerequisites, or exceeding max credit hours).
 *
 * Example usage:
 * boolean success = enrollStudent("S12345", "CS101", 1);
 * if (success) {
 *     System.out.println("Enrollment successful");
 * } else {
 *     System.out.println("Enrollment failed");
 * }
 *
 * @param studentId the unique ID of the student to enroll
 * @param courseCode the unique code of the course to enroll in
 * @param semester the semester number for enrollment
 * @return true if the student was successfully enrolled; false otherwise
 */

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

Why more important in team projects: Documentation ensures everyone understands the code, its purpose, assumptions, and edge cases. It prevents confusion, speeds up onboarding, and reduces bugs when multiple people work on the same code. In solo projects, you can rely on memory, so extensive documentation is less critical.

Example when it SHOULD be documented: A method that calculates a student’s final grade based on multiple rules, weights, and edge cases — because others need to know the why and how.

Example when it SHOULD NOT be documented: A simple getter like getName() — the purpose is obvious and adding a comment adds clutter.

Challenge Problems

Challenge Problem 1

/**
 * Computes the factorial of a non-negative integer using recursion.
 *
 * This method multiplies the given number by the factorial of (n-1)
 * until it reaches the base case of 0 or 1.
 *
 * Base case:
 * - If n is 0 or 1, returns 1.
 *
 * Recursive case:
 * - Returns n multiplied by factorial(n - 1).
 *
 * Assumptions:
 * - n must be non-negative.
 *
 * Time complexity:
 * - O(n) because the method makes n recursive calls.
 *
 * Space complexity:
 * - O(n) due to the recursion stack.
 *
 * Example usage:
 * int result = factorial(5); // returns 120
 *
 * @param n the non-negative integer whose factorial is to be computed
 * @return the factorial of n
 * @throws IllegalArgumentException if n is negative
 */
public static int factorial(int n) {
    if (n < 0) throw new IllegalArgumentException("n must be non-negative");
    if (n == 0 || n == 1) return 1; // base case
    return n * factorial(n - 1); // recursive case
}

Challenge Problem 2

1. When to Document

Document a method/class when:

  • Implements complex logic, algorithms, or business rules.
  • Has assumptions, edge cases, or constraints.
  • Will be used by other team members or external code.
  • Modifies state, handles I/O, or interacts with external systems.

Do NOT document:

  • Simple getters/setters.
  • Obvious one-line operations (x = 5;).
  • Code that will be immediately clear to any competent developer.

2. Required Tags

Method Type Required Tags
Complex method @param, @return, @throws, usage example, assumptions, complexity (if recursive/algorithmic)
Simple method @param, @return (only if not obvious)
Constructor @param for arguments
Class @author, @version, @since, purpose, main features, usage example

3. Example Templates

Complex method example:

/**
 * Computes the sum of positive even integers in an array.
 *
 * Assumes the array is not null.
 *
 * Example:
 * int result = sumPositiveEven(new int[]{1,2,3,4}); // returns 6
 *
 * @param nums array of integers, must not be null
 * @return sum of positive even integers
 * @throws NullPointerException if nums is null
 */

4. Common Mistakes to Avoid

  • Using vague descriptions like “processes data.”
  • Over-documenting trivial code (getters/setters).
  • Forgetting edge cases (null, empty arrays, invalid input).
  • Letting documentation become outdated when code changes.
  • Using HTML tags in Javadoc — always use plain text.

Challenge Problem 3

OSS Project: https://github.com/rsyslog/rsyslog

Before: Original Class Documentation

/**
 * Class to manage user accounts.
 */
public class UserAccount {
    private String username;
    private String password;

    public UserAccount(String username, String password) {
        this.username = username;
        this.password = password;
    }

    public boolean authenticate(String password) {
        return this.password.equals(password);
    }

    public void changePassword(String newPassword) {
        this.password = newPassword;
    }
}

Issues:

  • Lacks detailed explanations of methods and parameters.
  • No information about assumptions, edge cases, or limitations.
  • No examples provided.

After: Improved Documentation

/**
 * Represents a user account with authentication and password management capabilities.
 *
 * This class provides methods to authenticate a user, change their password,
 * and retrieve the username associated with the account.
 *
 * Assumptions:
 * - The username is unique and immutable.
 * - Passwords are stored in plain text (consider hashing for production).
 *
 * Example usage:
 * UserAccount user = new UserAccount("john_doe", "securePassword123");
 * boolean isAuthenticated = user.authenticate("securePassword123");
 * if (isAuthenticated) {
 *     user.changePassword("newSecurePassword456");
 * }
 *
 * @author Your Name
 * @version 1.1
 * @since 2025-10-10
 */
public class UserAccount {
    private String username;
    private String password;

    /**
     * Constructs a UserAccount with the specified username and password.
     *
     * @param username the unique identifier for the user
     * @param password the user's password
     */
    public UserAccount(String username, String password) {
        this.username = username;
        this.password = password;
    }

    /**
     * Authenticates the user by comparing the provided password with the stored password.
     *
     * @param password the password to authenticate
     * @return true if the provided password matches the stored password; false otherwise
     */
    public boolean authenticate(String password) {
        return this.password.equals(password);
    }

    /**
     * Changes the user's password to the specified new password.
     *
     * @param newPassword the new password to set
     */
    public void changePassword(String newPassword) {
        this.password = newPassword;
    }

    /**
     * Retrieves the username associated with this account.
     *
     * @return the username of the account
     */
    public String getUsername() {
        return username;
    }
}