UPI Study › Courses › Data Structures and Algorithms › Free lessons › Lesson 2.2 Free with a free account
Documenting Your Code for Clarity and Team Collaboration
Data Structures and Algorithms · Chapter 2: Planning and Documenting CodeSection 2.2 · lesson 6 of 8713 min · free with a free account
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Data Structures and Algorithms.
Lesson complete
Earn the 3 college credits for Data Structures and Algorithms
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: The Five Pillars of Reusable Software Design →← Designing Program Logic Before Writing Any CodeNext lesson: The Five Pillars of Reusable Software Design →
In this lesson
Write readable Java with clear names, comments, Javadoc and version control.
- Apply Java naming conventions and consistent formatting backed by a style guide
- Distinguish inline comments that explain why from Javadoc that tells callers what
- Write Javadoc with a summary sentence and param, return and throws tags
- Use Git commits, branches and code review to keep shared code clear
Free study notes
Get this lesson's notes by email
The key points and 4 practice questions with answers, in your inbox. One email, free.
One email. Unsubscribe in one click.
Transcript
Everything said in the video, section by section (1,780 words). Read along, or search it.
Opening Question
Code Is Read More Than Written
Here's a method that works. It compiles, and it gives the right answer every time. Can you tell, in five seconds, what it does? Code is written once, but read many times: by teammates who must change it, by reviewers who must approve it, and by you, months later, when the reasons have faded. A program that works but can't be understood is a liability, because every change to it becomes a guess.
Overview
Three Layers of Documentation
Documentation is the set of habits that prevents this, and it has three layers. The foundation is good names and consistent formatting. It applies to every line, and it does the most work. On top of it sit inline comments, used sparingly, only where the code can't speak for itself. At the top is Javadoc, Java's standard format for describing public methods and types, for people who use the code without reading it. And two team habits, version control and code review, keep all three layers healthy as many people change the same code.
Naming Conventions
Camel Case, Snake Case and Packages
A name is the first documentation a reader meets. A naming convention is an agreed pattern, so a reader can tell what kind of thing a name refers to before looking it up. Types use upper camel case nouns, like invoice item. Methods use lower camel case, and start with a verb: calculate total. Variables and parameters use lower camel case nouns, like overdue invoices. Constants are all capitals, with underscores between words: max readings. That's called upper snake case. Packages are all lowercase, like com dot shop dot billing. And a yes or no value reads as a question: is empty, has discount.
Meaningful Names
Four Habits for Revealing Intent
Conventions tell a reader the kind of name. The words tell them its meaning, and four habits help. Reveal intent: say what it holds or does. Spell words out: elapsed days, not e days. Short names like i are for a loop that fits on a few lines. Use one word per idea. If one method is get name, its sibling isn't fetch address. And match length to scope: the more widely a name is visible, the more descriptive it must be. So d becomes elapsed days. Temp two becomes overdue total. List one becomes pending orders. Do stuff becomes apply discount. And flag becomes is paid, which reads naturally in an if.
Formatting
Layout Rules the Compiler Ignores
Formatting is the layout of code: indentation, spacing, line breaks, and where braces go. The compiler ignores it completely. Human readers depend on it. Here's the opening method again, formatted, and with meaningful names. Same behavior. Now the five-second question answers itself: it adds up the positive prices. A few rules make that happen. Indent every level by the same amount, and never mix tabs and spaces. One statement per line, and always braces, even around a single statement. A blank line between logical blocks, spaces around operators, and lines short enough to read without scrolling sideways. Many guides set a hundred characters.
Style Guides
Style Guides, Formatters and Checkers
Nobody can enforce those rules from memory, and teams disagree about details, such as how many spaces to indent. A style guide ends the argument by writing the team's choices down once. Widely used Java examples are the Google Java Style Guide, and Oracle's code conventions. A team adopts one, changes it only by agreement, and lets tools do the policing. Formatters, such as an IDE's auto-format command or google-java-format, rewrite layout automatically. Checkers such as Checkstyle report rule violations. With tools in place, code review can focus on logic instead of spacing.
Comment Types
Inline Comments Versus Javadoc
Java offers two kinds of comments, for two different readers. Inline comments begin with two slashes, or sit between slash-star and star-slash. They live inside a method, beside the line they explain. Their reader is whoever changes the implementation, and their job is to explain why. Javadoc comments begin with slash-star-star, and sit right before a type, a method or a field. Their reader calls the code and never reads its body. So Javadoc says what the code does, needs and returns, and when it fails. The javadoc tool turns these comments into web pages of documentation, and IDEs show them as pop-up help while someone types.
Javadoc
Summary, Param, Return and Throws Tags
Here's Javadoc and an inline comment, working together, on a method that averages readings. Three rules keep Javadoc useful. Begin with a summary sentence in the third person: returns the mean of the given readings. Write one at-param tag per parameter, in order, saying what the value means: the daily temperatures, in degrees. Not just, the readings. Add at-return for any method that doesn't return void, and at-throws for each failure a caller should expect: here, an empty array. Inside, the inline comment explains a why: cast first, because integer division would drop the fraction.
Common Mistakes
Four Recurring Javadoc Errors
Four Javadoc mistakes come up again and again. A tag that repeats the name: at-param readings, the readings. Say what the value means. A missing failure: a method that throws, with no at-throws. Add one tag for each failure a caller should expect. A stale tag: the parameter was renamed, and the tag wasn't. Update it in the same change as the code. And a summary that describes the steps, loops over the array and adds. Describe the result, not the mechanism.
Guiding Principle
Comment What the Code Cannot Say
So what deserves a comment? The guiding principle is short: comment what the code cannot say. Code shows what happens, and how. It can't show why a choice was made, what units a number is in, or what surprising thing might happen. Those gaps are where comments belong: reasons, units and formats, surprises and side effects, a workaround and when it can go, and the contract of a public method. Everything else is noise: a restatement of the line beside it, an end of loop marker, old code left behind, edit history, or vague notes like fix later. And noise has a cost. Every comment must be kept in step with the code, forever.
Better Names
Renaming Instead of Commenting
Before writing a comment, ask whether a better name would remove the need for it. Check if user can vote, says this comment, above a test of a greater than or equal to eighteen, and c. Rename things: boolean eligible to vote equals age at least eighteen, and is citizen. Then, if eligible to vote. The names carry the meaning, and the comment disappears.
Worked Examples
Keep, Fix or Delete a Comment
Judge comments one at a time. I plus plus, add one to i, restates the code. Delete the comment. Returns Celsius, on a method that returns Fahrenheit. The comment contradicts the code, which is worse than no comment at all. Fix whichever is wrong. Total equals price times quantity, left behind as a comment, is dead code. Version control already remembers it. Delete it. But prices are in cents, to avoid rounding errors, explains a decision nobody could guess. Keep it.
Quick Check
Putting the Unit in the Name
Quick check. A teammate writes: int timeout equals thirty, then a comment that says, seconds. Three changes are on the board. Which one is best? Pause, and decide. Rename it. Int timeout seconds equals thirty carries the unit everywhere the variable is used, not just on the line where the comment sits. Keeping the comment works, until someone reads timeout three screens away and guesses milliseconds. And the comment doesn't restate the line: it adds a fact. The name is the better home for that fact.
Version Control
Repositories, Commits, Branches and Merges
Now the team habits. Version control records every change to a set of files, with who made it and when. It lets people work on the same code at once, without overwriting each other. Git is the most widely used system. A repository is the project's files, together with their full history. A commit is one saved set of changes, with a message describing it. A branch is a separate line of commits, so work in progress doesn't disturb the main line. A merge brings one branch's commits into another. And a pull request, which some services call a merge request, asks teammates to review a branch before it's merged.
Git Commands
Everyday Git Commands
The everyday commands are few. Git status lists what changed. Git add stages a change for the next commit. Git commit, dash m, records it with a message. Git switch, dash c, starts a new branch and moves onto it. Git push uploads your commits. Git pull downloads your teammates' work. And git merge combines a finished branch into the current one.
Commit Messages
Imperative Summaries for One Change
The commit message is documentation too, and it survives when comments are deleted. A good one has a short summary line in the imperative mood, add, fix, rename, then an optional body explaining why. And each commit holds one logical change, so it can be reviewed, and undone, on its own. Fix says nothing about what or why. Updated files names no change at all. Final version two, really final, is a version label, and labels belong in tags. Reject empty reading list in average says exactly what changed.
Code Review
Habits for Authors and Reviewers
Code review means a second person reads a change before it joins the main line. It catches mistakes, spreads knowledge of the system, and keeps names and documentation consistent. It works best when changes are small enough to read in one sitting. The author reads the change once before asking anyone, keeps it to one purpose, and explains the reasoning. The reviewer starts by understanding the goal, comments on the code, never the person, asks questions instead of giving orders, and marks each point as required or optional.
Quick Check
A Pull Request Doing Three Things
Quick check. A pull request arrives with a bug fix, three hundred renamed variables, and a whole file reformatted, all in one change. The tests pass. You're the reviewer: of the three replies on the board, which one do you send? Pause, and decide. Ask for it in pieces. Mixed together, the one real logic change hides among hundreds of lines that only moved, so the reviewer can only skim. Passing tests don't replace reading, and another reformat just adds noise. Formatting apart from logic lets each piece be read properly.
Key Takeaways
Names, Comments, Commits and Reviews
To summarize. Names and formatting are the foundation. Follow the conventions, spell words out, and let a style guide and tools settle the layout. Inline comments explain why. Javadoc tells callers what: a summary, at-param, at-return and at-throws. Comment what the code cannot say, prefer a better name to a comment, and keep comments in step with the code. And commit one logical change at a time with a clear message, and review small changes.
Think About It
Could a Teammate Read Your Code
Something to think about. Open some code you wrote a few weeks ago. Could a teammate understand it without asking you anything? Pick the one change that would help them most: a clearer name, a why comment, or Javadoc on a public method. What does your choice say about where your code is hardest to read?
About Data Structures and Algorithms at UPI Study
Data Structures and Algorithms (Computer Science 251) is a self-paced online course of 87 video lessons in 17 chapters, from Java and object-oriented design to arrays, linked lists, recursion, stacks and queues, trees, heaps, hash tables, sorting and graphs. It carries a NCCRS credit recommendation for 3 semester credits.
Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
Compare: Discrete Math vs Data Structures and Algorithms · Intro to Java vs Data Structures and Algorithms
Why take it here
Why students take Data Structures and Algorithms with UPI Study
Where the credit goes
Universities that work with NCCRS
Data Structures and Algorithms carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.
FAQ
Questions students ask us
About Documenting Your Code for Clarity and Team Collaboration
What are the naming conventions in Java?
What is the difference between a Javadoc comment and a regular comment in Java?
How do you write a good Javadoc comment for a method?
What makes a good Git commit message?
About the Data Structures and Algorithms course
How many college credits is Data Structures and Algorithms?
How much does Data Structures and Algorithms cost and what is included?
Which universities accept UPI Study credits?
How long does Data Structures and Algorithms take?
How are the exams done?
How do my credits reach my college?
Ready for the full course? Earn 3 credits in Data Structures and Algorithms.
87 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.
3 credits · NCCRSEnroll →