CS 149 Intro to Programming

Fall 2020

CheckStyle Lab -- Creating Stylish Code

Source:https://xkcd.com/1513

Learning Objectives

This lab is designed with the following learning objectives:
  • List (and appreciate) the reasons that writing code in the proper style is important
  • Install, configure, and use Checkstyle to validate the format of your Java code
  • Start using folders to organize the code you will develop this semester
  • Define and follow the checkstyle rules for comments,Javadoc, variable names, constants, literals, indention, and whitespace.

Actions/Deliverables

At the end of this lab, you need to complete these tasks (all of which are explained in the later sections of the lab):
  • Download the required Checkstyle files and configure jGRASP to use them (the checkstyle icons should appear)
  • Correct all style errors in Payroll.java and submit your assignment to Autolab (collaboration allowed, but all must submit).

Background

Virtually every organization that does software development has strict guidelines on how to format source code. Here are two examples of "industrial strength" Java style guides:

In this course, you will follow a simplified version of these guidelines. Rather than memorize a long list of rules, you should develop good habits and intuition when it comes to style.

Checkstyle is a tool (see checkstyle.sourceforge.net) that validate that your code follows a set of style guidelines.

Part 1: Configure jGrasp to run Checkstyle

Download the following files and place them somewhere that is not specific to this lab (as you will need them for all future work). A suggestion would be to create a folder/directory specifically for checkstyle (like ..../CS149_Fall2020/checkstyle).

Once you have downloaded the files listed above, open jGRASP and select:Tools -> Checkstyle -> Configure from the menu (pictured in the following image). After selecting Configure from the menu, the following dialog box will appear: You will need to change the following settings in the Checkstyle Tool Settings dialog box. TIP: you can use the home button (highlighted below) when you select the browse button.
  1. Set Checkstyle Home to the directory/folder where you downloaded the checkstyle-8.35.-all.jar file.
  2. Set Checks File to the full path/location of the cs149.xml file you downloaded.
Now, you need to close and restrt jGRASP and open a Java file. You can download CS149Style.java and open it. If the installation worked, you should see 2 new buttons on your jGRASP toolbar: Checkbutton and . Clicking the first button will run Checkstyle on the current file in the editor window, which should have zero style errors.

Configure jGRASP to Promote Good Style

jGRASP allows you to configure the tab key to move over the correct number of spaces and to insert spaces instead of the control code for a tab (\t). To change this, go to: Settings->CSD Window settings -> Workspace. Perform the following actions:
  1. Check the box for soft tabs (this inserts spaces instead of the special tab (\t) character
  2. Set the tab size to 3 (this is the default, so, you should just need to verify this).

Part 2: Styling a program: An example

This part of the lab focuses on modifying an existing Java program so that it adheres to the style used in this class. Each style component is discussed below, and it is recommend that after each component, you review the example program and modify it so that it follows the formatting rules.

Lab instructions

Below are the instructions for this lab. You are encouraged to work in groups of 2 (and at most 3). Each of you should have your own working copy of the code and submit your own program. It is okay if your files are similar or identifical, as long as all the names of the people in the group are listed at the top comment block in the file.

Actions:

  1. Directory Structure If you haven't already, you should create a top-level CS149 folder/directory to organize all your labs and other assignments for the semester. Create a directory called CheckstyleLab under your CS149 folder.
  2. Download Payroll.java and move Payroll.java into the Checkstyle directory.
  3. Correct all of the style errors in this file, using the (Checkbutton) icon to run checkstyle.
  4. After eliminating all of the style errors, submit your assignment to Autolab. Each student must submit a copy to Autolab to receive credit.

Checkstyle Rules

Style Part A: Comments

Comments are text that explains what the code does and have no impact on the execution of the program (the compiler ignores them). Their purpose is to make it easier for other programs (and yourself) to understand what you meant the code to do. In this class, the following comments will be required.
  1. Every class must contain a Javadoc comment (below is an example). This comment contains:
    • The first line must be a //* as shown in the example. The other lines must start with the aligned astericks characters.
    • A short description of what the class does. This description must end with a period (otherwise Checkstyle will mark it as an error).
    • The next line starts with @author, followed by the name of the original person who wrote the class
    • The next line starts with @version. In this class, you can just put the due date of the assignment for the version.
    • The honor code acknowledge is next.
    • This is a block comment, which ends with the sequence */. Java treats all information between the //* and the */ as a comment (which can span many lines, as it does in this example).
    /**
                              * Overall description of the class goes here.
                              *
                              * @author Your name goes here
                              * @version Due date goes here
                              * Acknowledgements: I received no outside help on this assignment and have
                              * abided by the JMU Honor Code.
                              */
  2. All methods (including main) must contain an applicable Javadoc comment as shown in the following example.
  3. /**
                              * Overall description of the method goes here.
                              *
                              * @param parameterName describe the first parameter
                              * @param parameter2 description of 2nd parameter
                              * @return
                              */
  4. Inline comments (//) should describe major structures and steps within a method.
  5. All comments should use normal English spelling and grammar. Phrases are OK
  6. Comments must come before the code that they are describing or on the same line.

Style Part B: Names

  1. All names should be descriptive and readable. (subTotal rather than s,   grade rather than grd)
  2. Multiple-word names should use capital letters to separate words. (subTotal, not sub_total)
  3. Variable and method names should begin with a lowercase letter, and:
    • Variable names should be nouns or noun phrases. (studentName or subTotal)
    • Method names should be verbs or verb phrases. (printLine or addColumn)
  4. Class names should begin with a capital letter and use title case. (HelloWorld)
  5. Constant names should be all caps with an underscore separator. (PI or INTEREST_RATE)

Style Part C: Declarations

final double CENTIMETERS_PER_INCH = 2.54;
                            centimeters = inches * CENTIMETERS_PER_INCH;    // NOT inches * 2.54;
  1. All constants should be named and initialized at the top of the method in which they are used.
  2. All variables should also be declared at the top of the method, directly after any constant declaraions.
  3. It is strongly recommended (in CS 149) to separate variable declaration and initialization statements.
  4. Each declaration should be on its own line. Comment to the right if the name is not self-explanatory.
Scanner input = new Scanner(System.in);    // discouraged
                            Scanner input;
                            input = new Scanner(System.in);

Style Part D: Literals

  1. Numeric literals should be of the correct type for the context in which they are used.
// integer expressions should use integer literals
                    int a;
                    double b;
                    a = 2;
                    b = 2.0;

                    // double expressions should use double literals
                    double x;
                    double y;
                    double average;
                        average = (x + y) / 2.0;    // NOT 2, which is an integer

Style Part E: Indentation

  1. Subsections of code should be indented consistently with three spaces.
  2. Always use three space characters, not tab characters, for indentation.
  3. Statements too long for one line should be indented on subsequent lines.
  4. All blocks of code (even if one line) should be surrounded by curly braces.
  5. Left braces must appear on the same line as the structure header.

Style Part F: Whitespace

  1. There should be a space after cast operators, commas, and //'s.
  2. Use whitespace to separate logical segments of code. There should be a blank line after variable declarations.
  3. Lines should be kept to a short length (< 80 chars). You should be able to see the full line in your text editor.
  4. Binary operators should be separated from their operands by a single space. (sum = myGrade + yourGrade;)
  5. One exception is the dot (.) operator, which should not have space surrounding it. (System.out.println();)
  6. Unary operators should not be separated by a space. (myGrade++;)

This lab is a modified version of the one developed by Professor Alvin Chao.