Documentation with Comments Homework
- Lesson Hack #1: Fix the Documentation
- Popcorn Hack #2: Write Class Documentation
- Homework Assignment
- Challenge Problems (Extra Credit)
- Challenge 2: Team Documentation Standard
- Challenge 3: Documentation Detective
Lesson Hack #1: Fix the Documentation
Task: The following code has poor documentation. Rewrite it with proper Javadoc comments including preconditions and postconditions.
// Does stuff with numbers
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 numbers in the given array.
*
* <p>This method iterates through each element in the input array and adds
* any number that is both positive and even to a running total. The final
* sum of these qualifying numbers is then returned.</p>
*
* @param nums an array of integers to be checked
* @return the sum of all positive even numbers in {@code nums}
*
* @precondition {@code nums} is not {@code null}
* @postcondition returns an integer representing the sum of all positive even numbers in {@code nums};
* if no such numbers exist, the return value is 0
*/
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 ```java // TODO: Add your class-level Javadoc here! // Hint: Start with /** and end with */
public class GradeBook { private HashMap<String, Double> assignments; private HashMap<String, Double> categoryWeights; private double extraCredit;
// TODO: Document each method too!
public void addAssignment(String category, String name, double score) { }
public void setCategoryWeight(String category, double weight) { }
public double calculateFinalGrade() { }
public String generateReport() { } }
Check your answer below!
/**
* The {@code GradeBook} class represents a digital record of a student's grades and category weights.
* It allows teachers or students to manage assignments, apply weights by category, calculate a
* final weighted grade, and generate a formatted report of all grades and extra credit.
*
* <p><b>Main Features:</b></p>
* <ul>
* <li>Add assignments with names, categories, and scores.</li>
* <li>Assign weight percentages to different grading categories (e.g., Tests, Homework).</li>
* <li>Calculate a weighted final grade based on category averages and weights.</li>
* <li>Generate a summary report showing all grades and extra credit earned.</li>
* </ul>
*
* <p><b>Example Usage:</b></p>
* <pre>{@code
* GradeBook gb = new GradeBook();
* gb.setCategoryWeight("Tests", 0.6);
* gb.setCategoryWeight("Homework", 0.4);
* gb.addAssignment("Tests", "Midterm", 85);
* gb.addAssignment("Homework", "HW1", 100);
* double finalGrade = gb.calculateFinalGrade();
* System.out.println(gb.generateReport());
* }</pre>
*
* @author Anvay
* @version 1.0
* @since 2025-10-10
*/
public class GradeBook {
private HashMap<String, Double> assignments;
private HashMap<String, Double> categoryWeights;
private double extraCredit;
/**
* Adds a new assignment to the gradebook with the specified category, name, and score.
*
* @param category the category of the assignment (e.g., "Tests", "Homework")
* @param name the name or title of the assignment
* @param score the numeric score received for the assignment
*
* @precondition {@code category} and {@code name} are not null or empty;
* {@code score} is a non-negative value
* @postcondition the assignment is stored and can be used in final grade calculations
*/
public void addAssignment(String category, String name, double score) { }
/**
* Sets the weight for a specific grading category.
*
* @param category the name of the category (e.g., "Quizzes", "Projects")
* @param weight the proportional weight of the category (e.g., 0.3 for 30%)
*
* @precondition {@code weight} is between 0.0 and 1.0
* @postcondition updates the stored weight for the given category
*/
public void setCategoryWeight(String category, double weight) { }
/**
* Calculates the student's final weighted grade based on category weights,
* assignment scores, and extra credit.
*
* @return the computed final grade as a {@code double}
*
* @precondition category weights sum to approximately 1.0
* @postcondition returns a numeric value between 0 and 100 representing the final grade
*/
public double calculateFinalGrade() { return 0.0; }
/**
* Generates a text-based report of all assignments, category averages,
* weights, and final grade.
*
* @return a formatted {@code String} containing the grade summary
*
* @precondition none
* @postcondition returns a readable report summarizing the student's performance
*/
public String generateReport() { return ""; }
}
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.
- 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;
}
}
*/
- Improved version
/**
* The {@code Calculator} class provides basic arithmetic operations.
* This example demonstrates how to use a static method to add two integers
* and print the result to the console.
*
* <p><b>Example Output:</b> ans is 15</p>
*
* @author Anvay
* @version 1.0
* @since 2025-10-10
*/
public class Calculator {
/**
* The main method executes the program by calling {@link #add(int, int)}
* and displaying 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("ans is " + z);
}
/**
* Adds two integer values and returns the result.
*
* @param a the first integer
* @param b the second integer
* @return the sum of {@code a} and {@code b}
*
* @precondition none
* @postcondition returns a + b
*/
static int add(int a, int b) {
return a + b;
}
}
- A brief explanation of what I improved
Explanation of Improvements
- Added a clear class-level Javadoc describing the purpose of the program.
- Added Javadoc comments for each method, including parameters, return values, and conditions.
- Renamed the class from stuff → Calculator for clarity and professionalism.
- Fixed inconsistent formatting and indentation.
- Improved readability with spaces, indentation, and descriptive comments.
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;
}
/**
* Attempts to enroll a student into a specified course for a given semester.
*
* <p>This method checks multiple conditions to ensure the student is eligible
* for enrollment. It verifies the existence of the student and course, checks
* for capacity, schedule conflicts, prerequisite completion, and total credit limits.
* If all conditions are met, the student and course records are updated, and
* the enrollment transaction is recorded.</p>
*
* @param studentId the unique identifier of the student attempting to enroll
* @param courseCode the code representing the course to enroll in
* @param semester the semester identifier (e.g., 20251 for Spring 2025)
* @return {@code true} if enrollment is successful; {@code false} otherwise
*
* @precondition both {@code studentId} and {@code courseCode} correspond to existing records
* @postcondition if successful, the student is enrolled in the course and both records are updated
*
* <p><b>Possible Failure Reasons:</b></p>
* <ul>
* <li>Student or course does not exist</li>
* <li>Course is full</li>
* <li>Schedule conflict detected</li>
* <li>Missing prerequisites</li>
* <li>Exceeds 18 credit hours</li>
* </ul>
*/
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
- Why is documentation more important in team projects than solo projects?
- Documentation is more important in team projects because multiple people work on the same codebase. Clear Javadoc helps others understand how methods, classes, and parameters work without reading every line of code. It prevents confusion, reduces bugs, and makes future maintenance easier. When one developer leaves or another joins, documentation ensures the team can continue smoothly.
- Give an example of when a method SHOULD be documented and when it SHOULD NOT.
- Should be documented: When a method performs a non-obvious or complex task, like
enrollStudent()that includes logic, conditions, or dependencies between objects. - Should not be documented: When a method is private and trivial (e.g., a simple getter or setter) whose behavior is obvious from its name, such as
getName()orsetScore(double score).
- Should be documented: When a method performs a non-obvious or complex task, like
Challenge Problems (Extra Credit)
Challenge 1: Document a Recursive Method
Write complete documentation for a recursive method including base case, recursive case, and complexity analysis.
/**
* Computes the factorial of a given non-negative integer using recursion.
*
* <p>This method repeatedly multiplies the given number {@code n}
* by the factorial of {@code n - 1} until it reaches the base case (n == 0).
* It demonstrates a simple recursive algorithm with clearly defined
* base and recursive cases.</p>
*
* @param n the non-negative integer for which to compute the factorial
* @return the factorial of {@code n} (i.e., n!)
*
* @precondition {@code n >= 0}
* @postcondition returns a non-negative integer value representing {@code n!}
*
* <p><b>Base Case:</b> When {@code n == 0}, returns 1.</p>
* <p><b>Recursive Case:</b> {@code factorial(n) = n * factorial(n - 1)}</p>
*
* <p><b>Complexity Analysis:</b></p>
* <ul>
* <li>Time Complexity: O(n) — one recursive call per decrement of n.</li>
* <li>Space Complexity: O(n) — due to the recursive call stack.</li>
* </ul>
*/
public static long factorial(int n) {
if (n == 0) {
return 1; // Base case
}
return n * factorial(n - 1); // Recursive case
}
Challenge 2: Team Documentation Standard
Create a documentation style guide for a team project. Include:
- When to document (and when not to)
- Required tags for different method types
- Example templates
- Common mistakes to avoid
Challenge 2: Team Documentation Standard
Team Documentation Style Guide
Purpose:
To ensure consistent, readable, and professional Javadoc across all files in the project.
1. When to Document
Document when:
- The method performs a non-trivial or non-obvious operation (loops, recursion, calculations, validation, etc.).
- The method has preconditions, side effects, or depends on other methods.
- The method is public and part of the project’s API.
- The method includes multiple parameters or complex return types.
Do NOT document when:
- The method is private and self-explanatory (for example, simple getters and setters).
- The code block is temporary, commented out, or experimental.
2. Required Tags
| Method Type | Required Tags |
|---|---|
| Public methods | @param, @return, @throws, @precondition, @postcondition |
| Private methods | Brief comment (optional) |
| Constructors | @param for all inputs |
| Recursive methods | @param, @return, @precondition, @postcondition, base/recursive case notes |
| Class-level Javadoc | @author, @version, @since |
3. Example Templates
Class Template
/**
* The {@code StudentManager} class handles registration, record keeping,
* and enrollment logic for students within the system.
*
* @author <name>
* @version 1.0
* @since 2025-10-10
*/
Method Template
/**
* Updates the GPA of a student based on completed courses.
*
* @param studentId the unique identifier for the student
* @return {@code true} if the GPA was successfully updated; {@code false} otherwise
* @throws IllegalArgumentException if {@code studentId} does not exist
*
* @precondition {@code studentId} is valid and non-null
* @postcondition the student's GPA is recalculated and updated in the database
*/
4. Common Mistakes to Avoid
- Writing vague comments such as “Does stuff” or “Handles data”.
- Failing to explain how errors or edge cases are handled.
- Omitting @param, @return, or @throws tags.
- Copying old comments that no longer match the code.
- Using inconsistent grammar, capitalization, or formatting.
Challenge 3: Documentation Detective
Repository used
geektrust/family-java-bad-code
Before (Original Class)
public class SomeClass {
int doX(int a, int b) {
return a * b + 5;
}
}
After (Documented Class)
/**
* SomeClass performs operations related to the “family” domain in the Geektrust challenge.
*
* <p>This class contains methods to compute values used in inheritance rules,
* family relationships, etc.</p>
*
* @author YourName
* @version 1.0
* @since 2025-10-10
*/
public class SomeClass {
/**
* Computes a derived value based on inputs `a` and `b`.
* The formula is: `a * b + 5`.
*
* @param a the first integer parameter; must be non-negative
* @param b the second integer parameter; must be non-negative
* @return the computed integer result
*
* @precondition a >= 0, b >= 0
* @postcondition returns a * b + 5
*/
int doX(int a, int b) {
return a * b + 5;
}
}