CSE 142/143 Unofficial Commenting Guide Eric Arendt, Alyssa Harding, Melissa Winstanley

Similar documents
CSE143 Notes for Monday, 4/25/11

Formal Methods of Software Design, Eric Hehner, segment 1 page 1 out of 5

Math Modeling in Java: An S-I Compartment Model

PROFESSOR: Last time, we took a look at an explicit control evaluator for Lisp, and that bridged the gap between

CSE 143: Computer Programming II Summer 2017 HW5: Anagrams (due Thursday, August 3, :30pm)

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

Classes, interfaces, & documentation. Review of basic building blocks

CSE 143: Computer Programming II Summer 2015 HW6: 20 Questions (due Thursday, August 13, :30pm)

The compiler is spewing error messages.

CSE 143: Computer Programming II Spring 2015 HW7: 20 Questions (due Thursday, May 28, :30pm)

printf( Please enter another number: ); scanf( %d, &num2);

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

CSE331 Winter 2014, Midterm Examination February 12, 2014

Documentation Nick Parlante, 1996.Free for non-commerical use.

Tips from the experts: How to waste a lot of time on this assignment


Tips from the experts: How to waste a lot of time on this assignment

Stage 11 Array Practice With. Zip Code Encoding

CSE 331 Final Exam 3/16/15 Sample Solution

CSE 331. Programming by contract: pre/post conditions; Javadoc

CSE 143, Winter 2013 Programming Assignment #8: Huffman Coding (40 points) Due Thursday, March 14, 2013, 11:30 PM

CS 161 Computer Security

Notes - Recursion. A geeky definition of recursion is as follows: Recursion see Recursion.

MITOCW watch?v=0jljzrnhwoi

A function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-3).

CSE 143 Lecture 10. Recursion

CS 3 Introduction to Software Engineering. 3: Exceptions

************ THIS PROGRAM IS NOT ELIGIBLE FOR LATE SUBMISSION. ALL SUBMISSIONS MUST BE RECEIVED BY THE DUE DATE/TIME INDICATED ABOVE HERE

CSE143X: Computer Programming I & II Programming Assignment #10 due: Friday, 12/8/17, 11:00 pm

Example Program. public class ComputeArea {

CS 2505 Computer Organization I Test 1. Do not start the test until instructed to do so!

CS 315 Software Design Homework 3 Preconditions, Postconditions, Invariants Due: Sept. 29, 11:30 PM

Skill 1: Multiplying Polynomials

Full file at

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

CSE143X: Computer Programming I & II Programming Assignment #9 due: Monday, 11/27/17, 11:00 pm

Exceptions and Design

CSE 230 Computer Science II (Data Structure) Introduction

Intro. Speed V Growth

CS112 Lecture: Defining Classes. 1. To describe the process of defining an instantiable class

Write for your audience

Who am I? I m a python developer who has been working on OpenStack since I currently work for Aptira, who do OpenStack, SDN, and orchestration

CS159. Nathan Sprague

COMP 202 Java in one week

Java Programming. Computer Science 112

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

CS61A Notes Week 6: Scheme1, Data Directed Programming You Are Scheme and don t let anyone tell you otherwise

How to Improve Your Campaign Conversion Rates

MITOCW watch?v=se4p7ivcune

CSE wi Midterm Exam 2/8/18. Name UW ID #

CSCI 200 Lab 1 Implementing and Testing Simple ADTs in Java

Java Programming Constructs Java Programming 2 Lesson 1

Chapter Fourteen Bonus Lessons: Algorithms and Efficiency

CS 177 Recitation. Week 1 Intro to Java

CSE wi Midterm Exam 2/8/18 Sample Solution

These are notes for the third lecture; if statements and loops.

Supplemental Handout: Exceptions CS 1070, Spring 2012 Thursday, 23 Feb 2012

CSE 143: Computer Programming II Winter 2019 HW6: AnagramSolver (due Thursday, Feb 28, :30pm)

What did we talk about last time? Course overview Policies Schedule

Introduction to Programming

CS 142 Style Guide Grading and Details

Hardware versus software

Outline. Computer Science 331. Information Hiding. What This Lecture is About. Data Structures, Abstract Data Types, and Their Implementations

Programming Lecture 4

MITOCW watch?v=4dj1oguwtem

Garbage Collection (1)

(A) Good C++ Coding Style 1

05. SINGLETON PATTERN. One of a Kind Objects

Specifications. Prof. Clarkson Fall Today s music: Nice to know you by Incubus

MITOCW watch?v=zm5mw5nkzjg

Programming Lecture 4

Instructor (Mehran Sahami):

CS 211 Programming Practicum Fall 2018

Tips from the experts: How to waste a lot of time on this assignment

Java Style Guide. 1.0 General. 2.0 Visual Layout. Dr Caffeine

MITOCW watch?v=rvrkt-jxvko

Slide 1 CS 170 Java Programming 1

CSE 143: Computer Programming II Summer 2017 HW4: Grammar (due Tuesday, July :30pm)

CSCI 2101 Java Style Guide

The Design Process. General Development Issues. C/C++ and OO Rules of Thumb. Home

Chapter 2. Designing a Program. Input, Processing, and Output Fall 2016, CSUS. Chapter 2.1

CSE 331 Final Exam 6/5/17. Name UW ID#

CSE 114 Computer Science I

STUDENT LESSON A12 Iterations

Recursively Enumerable Languages, Turing Machines, and Decidability

Halting Measures and Termination Arguments

The Stack, Free Store, and Global Namespace

Post Experiment Interview Questions

Note: This is a miniassignment and the grading is automated. If you do not submit it correctly, you will receive at most half credit.

MITOCW watch?v=flgjisf3l78

1 Lecture 5: Advanced Data Structures

MITOCW watch?v=w_-sx4vr53m

CSCA08 Winter 2018 Week 3: Logical Operations, Design Recipe. Marzieh Ahmadzadeh, Brian Harrington University of Toronto Scarborough

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

In our first lecture on sets and set theory, we introduced a bunch of new symbols and terminology.

User Interface Programming OOP/Java Primer. Step 3 - documentation

Advanced Computer Programming

Iteration Preview of Coming Attractions The Need to Get Your Act Together A Process for Developing While Statements

CSE 331 Final Exam 12/9/13

(f) d={ alchemist :( a, t ), shaman : ( s, n ), wizard : ( w, z )} d[ shaman ][1]

Transcription:

CSE 142/143 Unofficial Commenting Guide Eric Arendt, Alyssa Harding, Melissa Winstanley In Brief: What You Need to Know to Comment Methods in CSE 143 Audience o A random person you don t know who wants to use your code but doesn t care how it works. o NOT your TA, who (hopefully) understands the code. o NOT you, who wrote the code. o If you need help, check out the Java API documentation and see how they write. Format o Include a header comment with your name, section, TA, and brief description of the program, which describes what the program does (avoiding implementation details see below). o The format should be pre/post (see section on pre/post below), JavaDoc, or some other format that includes all the required information. o Limit comments to 80 characters per line. Longer lines look horrible and will anger your TA. o NOT in all caps. o DO NOT write a book for your comments. This page, for example, is much too long. o Use either multiline comments (/* */) or single line comments (//). Language o Just say what the method does (ex. Calculates a sum ) instead of This method calculates o Don t say the method should do something if you programmed it correctly, it will do it. o Do not copy from the spec. The write up usually gives too much information for the comments. It is a good idea to pull the key points for your comments from the write up and put them in your own words, but only the appropriate information the client needs. Implementation details o Avoid things that describe how your program works. Avoid mentioning the following things: Local variable names, private field names For loop, while loop, if/else, recursion, inner data structures, calls to other methods (note that this list is not comprehensive other things may be implementation detail) If some implementation detail is vitally important (ex. Uses a SortedMap to maintain sorted order ), reformat the detail in a client-oriented way (ex. Maintains sorted order ). o Maybe later you learn some new technique and decide to change how a method works. But if you have documented that the code uses a for loop, for example, you can't go back and change it. It is therefore better to tell what the method does rather than how it does it. Parameters o Describe what each parameter represents, either in a list or as part of the method description. o Describe why each parameter is needed. o Comment any special cases the client may care about, ex. The given list should be in sorted order. Output or return value o If the program produces output, describe it. Where does the output appear? On the console, in a file, etc. What is the output? A list of numbers, a paragraph, the result of a computation, etc. What is the output format? On multiple lines, in reverse order, separated by spaces, etc. o If the program returns a value, describe what the returned value represents in relation to the input. o Comment any special cases the client may care about, ex. Does it return null in a particular case? Exceptions o Tell the user precisely what will cause an exception. o Include the exact type of any exceptions that are thrown next to their causes, so the client knows what could happen.

Internal comments o Just because implementation details are bad in method comments does not mean that you shouldn t describe how your code works. o Place the comments inside the body of the method, letting anyone reading your code know what you are doing. o Do not comment trivial code, only code that is important, confusing, or tricky. o Use single line comments (// comment here) Private methods o Same rules as for public methods, but slightly less strict. o Still try to avoid commenting implementation details. Fields o Put a brief comment on each field describing what it represents. o If the comment is essentially a repeat of the field s name, then you may usually omit it. o Comments on public fields or constants should avoid implementation details. A good example program (replace the information with your own): // Stuart Reges // CSE 143 AA with Eric Arendt // Homework 0 // A MyClass calculates sums and can print values, counting the number // of times that it sums. public class MyClass { // The number of times this class is used to find a sum. private int count; // Pre: values must not be null (throws an IllegalArgumentException // otherwise. All values in the values array must be non-negative // (throws an IllegalArgumentException otherwise). // // Post: Calculates and returns the sum of the integers in the given // array. public int findsum(int[] values) {... // Pre: given value must be non-negative (throws // IllegalArgumentException otherwise). // // Post: Prints the given integer value to the console four times, // each on its own line. public void printfour(int value) {...

In Detail: Commenting in General and With Explanation of Why What are comments? Comments are specially marked lines of text in your code that can be used to describe what's happening in your program. Java ignores comments when it runs your program, so they're not necessary for actually making code work properly. There's no exact formula to writing comments. The important details of a method or program are different depending on what the program or method does. The simplest way to know if your comments are sufficient is to ask yourself this: "If I didn't understand the code in this method, would I still be able to use it properly by reading only the comment and the method header?" Why comments are useful? It may seem like comments are a bit unnecessary, since you re the one writing your code. The purpose of comments isn't necessarily for the author's benefit (though they can be very useful as programs get more and more complex), but rather for the benefit of others who read your code. You might have a useful method that someone wants to use for another program, for example. Another programmer shouldn't have to reinvent the wheel - they should use your method instead of writing their own. If your method is properly commented, all they should have to read to know how your method works is the comment and the first line of the method (the header). Behavior vs. Implementation Comments should describe the behavior of a method (what it does) but generally should not describe its implementation (how it does it). If someone is really interested in exactly how a method works they can read through the code. When writing a comment, avoid discussing the commands or variables you used or what calls the method, and don't discuss what you thought about when you wrote the method or what you want it to do. Just describe what it actually does. Descriptions of the Program Descriptions of the program should follow the same ideas as method comments but at a higher level. Describe concisely but completely what someone can expect when they use the program, and don't go through all of the details of how it works. Internal vs. External Comments Comments don't need to be restricted to the description of a method. You can comment lines of code inside your method as well. Internal comments should be used to describe the behavior (not the implementation) of more complicated pieces of code. Don't comment the obvious - it can actually make your code less readable. Comment Tags There are a couple of ways to designate a comment in Java.

// You can write comments with two slashes for every line of comments // You need to put slashes on every line, which can be tedious. /* */ You can also write blocks of comments using comment open/close tags. The commented section starts with /* and ends when a */ appears. Do not use these for internal method comments. ///////////////////////////////////////////////////////////////////// /* * Comments can also be done more creatively, but use this style * in special cases. It's useful for giving an overall description * of large files, such as an entire library of methods that has * hundreds or thousands of lines of code, or for multiple files * that all need a description. You shouldn't use this style with * the short programs assigned in CSE 142 / 143. */ ///////////////////////////////////////////////////////////////////// Commenting Simple Methods Let s look at examples of commenting a simple method that prints an introduction: public static void intro() { System.out.println("This program compares two applicants to"); System.out.println("determine which one seems like the stronger"); System.out.println("applicant. For each candidate I will need"); System.out.println("either SAT or ACT scores plus a weighted GPA."); The following comment is too brief. It doesn't answer the most basic question of "what does the method do?" // Intro public static void intro() { The following comment is much better. It concisely describes the method's behavior. // Prints an introduction to the program to the console public static void intro() { The next version of the comment isn't very helpful. It mentions that it prints an introduction to the program, which describes its behavior, but it also includes unnecessary details about the method's implementation. If someone wants to know how the printing happens they can read the code. // Uses four println statements to print four lines of introduction to // the program. Each line is different, so each one needs a separate // println statement. public static void intro() {

Commenting Parameters Suppose you have a useful method that prints a list of numbers up to and including a number passed in as a parameter. A good comment (and all someone using the method should have to read) is this: // Takes an int representing a maximum and prints a list of numbers to the // console up to and including max in the format: 1, 2, 3,..., max public static void printnumberlist(int max) { for (int i = 1; i < max; i++) { System.out.print(i + ", "); System.out.println(max); That seems pretty straightforward. The method and its parameters are well-named, and the comment is concise but descriptive. What if you were to encounter the exact same method but it was named and commented like this? // Lists the numbers using a for loop public static void list(int n) { It's very difficult to tell what this method does. It could print a list up to but not including n (an important difference) or it could print the list starting at n and going down to one. You can't even tell if it prints a list. Maybe it adds the parameter n to some list, or maybe it makes "n" lists. The only way to know what this method does and how to use it is to read all of the code and figure it out. This can be very time consuming. It's also good to note that the name of a method and the names of its parameters - everything in the header - help describe what the method does. Commenting Methods with Return Values Sometimes what a method returns might not be immediately obvious. A method that returns an int might be returning a result it calculates, or it might print the result to the console and instead return the number of seconds the calculation took. It's important to describe what the return value of a method represents so that people know what to expect when they use it. This first version of the method below is well commented. The comments are concise and correctly describe what the method takes as a parameter and what it returns. The code is straightforward and explains itself. Internal comments aren't really necessary here. // Takes an integer n as a parameter and returns the factorial of n public static int factorial(int n) { int result = 1; while (n > 1) { result *= n; n--; return result; The next comment isn't descriptive enough - it doesn't describe the input and output parameters. It calculates the factorial of what? What does the int it returns represent?

// Calculates the factorial public static int factorial(int n) { The next version of the comments contains too many implementation details, and the internal comments actually make the code less readable. If the code is correctly indented, it's perfectly obvious that the while loop is a while loop and that it ends where its brackets end. n-- is obviously an update of n, and we can tell the return statement is a return. Save internal comments for more complicated statements. // Uses a result variable and a while loop to calculate the result of // n factorial. The while loop runs until the result is calculated, // and a return statement is used to return result. public static int factorial(int n) { int result = 1; // initialize result // while loop while (n > 1) { result *= n; n--; // update n // end of while loop return result; // return Describing Behavior and Internal Comments The method below has appropriate internal and external comments. The comments concisely describe the behavior of the method as well as the input parameters without discussing the implementation. The internal comment is there to describe what an odd-looking piece of code is doing. It's sometimes good to leave whitespace before an internal comment so that it's easier to read. // Takes a Scanner "input" and a PrintStream "output" as parameters. // Prints the contents of the input Scanner to output with trimmed // whitespace and line breaks every 10 tokens. Existing line breaks // in intro are ignored. public static void addlinebreaks(scanner input, PrintStream output) { int tokencount = 0; while (input.hasnext()) { output.print(input.next()); tokencount++; // Add a line break every 10th line if( tokencount % 10 == 0) { output.println(); The next method description isn't sufficient. It doesn't correctly answer the questions "what does this code do?" "what are the parameters?". If someone were to read these comments, they might be confused about what the Scanner was supposed to contain and where the output was being printed to. // prints out a file with line breaks every 10 tokens public static void addlinebreaks(scanner input, PrintStream output) {

The next version of the comments isn't appropriate because it deals with implementation details. We don't need to know that the code uses a while loop in order to use it. If someone wants to find out HOW the code gets the job done, they can read the code. // Uses a while loop and a scanner to output the Scanner file // with line breaks every 10 tokens. public static void addlinebreaks(scanner input, PrintStream output) { Commenting Exceptions and Pre/Post conditions Exceptions are an important part of the behavior of the method. When commenting a method that may throw an exception, it's necessary to include the type of the exception and the conditions that throw it in your comments. You can also provide a short explanation of why the exception was thrown in the Exception itself. This is a nice way to give a user a little more information than just the exception type. When these exceptions are thrown, the string describing why shows up in the exception trace. Pre conditions and post conditions are a way to assert what must be true before and after a method runs. For the findmax method to run properly, the preconditions for valid parameters must be true - it will throw an exception otherwise. A post condition might be used to describe something that must have changed after the method is run. A method that sorts a list, for example, has the post condition that the list is sorted. Some methods may not have a post condition or (more rarely) may not have a pre condition. /* * Pre: start >= 0, end <= list.length, start >= end * Throws an IllegalArgumentException if preconditions not met. * * Post: Takes an integer list and two integers representing the start * and end of a range in the list in which to search. Returns the * maximum value found in the list of integers between start and end, * start inclusive and end exclusive. */ public static int findmax(int[] list, int start, int end) { if (start < 0 end > list.length) throw new IllegalArgumentException("start or end out of range"); if (start >= end) throw new IllegalArgumentException("start is greater than end"); int max = list[start]; // Search the list for a maximum for (int i = start + 1; i < end; i++) max = Math.max(max, list[i]); return max; Commenting Fields Fields, representing the state of the class, should be commented as well. Describe what the field represents. These comments should not be lengthy, but they should help anyone reading your code to understand why the field is important. However, be careful to only provide useful comments. If the field s name is very selfexplanatory and your comment would add nothing, then it may be acceptable to omit the comment.

In the following example, the first two comments are good: they describe briefly what the field stores and the format of the data. The last comment is poor because it merely repeats the name of the field. This comment is okay to include, but not necessary. A better comment might be The student s age in years. public class Student { // The first and last name of the student. private String name; // The student s score (from 0 to 100) on their latest test. private int score; // The student s age. private int age;