├── README.md └── cs1302_checks.xml /README.md: -------------------------------------------------------------------------------- 1 | # CSCI 1302 Code Style Guide 2 | 3 |  4 | 5 | Make sure you read through this document carefully. **In addition to describing why 6 | code style is important and the code style guidelines for CSCI 1302, it also 7 | describes how to use the `check1302` program on `Odin` to check your code as well 8 | as Emacs and Vi configurations that, if used, will reduce the number of style issues 9 | you have in your code moving forward.** 10 | 11 | ## Table of Contents 12 | 13 | * [Compliance](#compliance) 14 | * [Motivation](#motivation) 15 | * [When and How to Check](#when-and-how-to-check) 16 | * [When to Check](#when-to-check) 17 | * [Run Checkstyle](#run-checkstyle) 18 | * [Multiple Files](#multiple-files) 19 | * [Output Examples](#output-examples) 20 | * [Recommended Emacs Configurations](#recommended-emacs-configurations) 21 | * [Additional Emacs Configurations](#additional-emacs-configurations) 22 | * [Automatically Update Emacs Packages](#automatically-update-emacs-packages) 23 | * [Show Style Guide Violations in the Editor](#show-style-guide-violations-in-the-editor) 24 | * [Recommended Vi Configurations](#recommended-vi-configurations) 25 | * [Specific Guidelines](#specific-guidelines) 26 | * [ArrayTypeStyle](#arraytypestyle) 27 | * [CheckStyleException](#checkstyleexception) 28 | * [ConstantName](#constantname) 29 | * [EmptyBlock](#emptyblock) 30 | * [EmptyCatchBlock](#emptycatchblock) 31 | * [EmptyLineSeparator](#emptylineseparator) 32 | * [FileTabCharacter](#filetabcharacter) 33 | * [Indentation](#indentation) 34 | * [JavadocMethod](#javadocmethod) 35 | * [LeftCurly](#leftcurly) 36 | * [LineLength](#linelength) 37 | * [MemberName](#membername) 38 | * [MethodName](#methodname) 39 | * [MethodLength](#methodlength) 40 | * [MissingJavadocMethod](#missingjavadocmethod) 41 | * [MissingJavadocType](#missingjavadoctype) 42 | * [ModifierOrder](#modifierorder) 43 | * [NeedBraces](#needbraces) 44 | * [OneStatementPerLine](#onestatementperline) 45 | * [OneTopLevelClass](#onetoplevelclass) 46 | * [OuterTypeFilename](#outertypefilename) 47 | * [RightCurly](#rightcurly) 48 | * [SummaryJavadoc](#summaryjavadoc) 49 | * [TypeName](#typename) 50 | * [WhitespaceAround](#whitespacearound) 51 | * [References](#references) 52 | * [Publication History](#publication-history) 53 | 54 | ## Compliance 55 | 56 | From a technical standpoint, this style guide serves as the complete definition of 57 | the coding standards for Java source code in CSCI 1302 at the University of Georgia. 58 | When it comes to submitting code for an assignment, a Java source file is described 59 | as being in _valid style_ (or compliant with this code style guide) if and only if 60 | it adheres to the rules herein. 61 | 62 | We recognize that some of the guidelines may be new for some students, so while 63 | this style guide does contain the technical details for each guideline, it also 64 | provides context, examples, and additional information that you may use to 65 | check your code. In some assignments, terms like "checkstyle audit" or 66 | "check1302 audit" will be used to remind you to check your code for compliance 67 | with this style guide. 68 | 69 | We also recognize that the terminal-based text editors used in this course are 70 | new for many students. That is why we include recommendations for how to configure 71 | those editors to help you stay in compliance. These recommendations will not 72 | fix all code style violations, but they should help you avoid writing code that 73 | violates some of the guidelines that are annoying to spot by hand and even more 74 | annoying to fix. 75 | 76 | Finally, we also include information about how to use the `check1302` program 77 | on `odin` to check your code for compliance. This is the same tool that graders 78 | will use to check your code. **It is your responsibility to ensure that all 79 | Java source files included with a submission are compliant.** This obviously 80 | includes code that you write, but it also includes code that may have been given 81 | to you as part of the assignment. It even includes code that may not be used 82 | in your program but is still included with your submission. 83 | 84 | ## Motivation 85 | 86 | Many companies will not let you commit changes for review until your 87 | code meets their established guidelines--a notable example is Google. 88 | Why do these companies do this? The short answer is that enforcing 89 | good style makes things easier for everybody, and while you may not 90 | believe it just yet, it does, in fact, make things easier for you 91 | too. 92 | 93 | In the preface to *The Practice of Programming* [[TPOP](#ref-tpop)] by 94 | [Kernighan](https://en.wikipedia.org/wiki/Brian_Kernighan) 95 | and [Pike](https://en.wikipedia.org/wiki/Rob_Pike), the authors ask the 96 | reader to consider some questions related to several difficult, tedious, 97 | or annoying scenarios that programmers find themselves in when writing 98 | code (i.e., the "not fun" parts). Their last two questions are specifically 99 | worth mentioning here: 100 | 101 | * Have you ever tried to make a modest change in someone else's program? 102 | * Have you ever rewritten a program because you couldn't understand it? 103 | 104 | The authors end their interrogation with the following comments: 105 | 106 | > These things happen to programmers all the time. But dealing with such 107 | > problems is often harder than it should be because topics like testing, 108 | > debugging, portability, performance, design alternatives, and 109 | > style--the *practice* of programming--are not usually the focus of 110 | > computer science or programming courses. Most programmers learn them 111 | > haphazardly as their experience grows, and a few never learn them 112 | > at all. 113 | > **-- Kernighan and Pike** 114 | 115 | Regarding style, they even go on to say: 116 | 117 | > Good style is so important to good programming that we have chosen 118 | > to cover it first. Well-written programs are better than badly-written 119 | > ones--they have fewer errors and are easier to debug and modify--so 120 | > **it is important to think about style from the beginning**. 121 | > **-- Kernighan and Pike** 122 | 123 | If your code looks good, which we will define here as adhering to an 124 | established style guide, then: 125 | 126 | * It is easier to read, especially when compared to code that applies stylistic choices 127 | inconsistently. It is certainly easier to read by those who are familiar with the 128 | conventions outlined in the style guide. 129 | 130 | * It is easier to identify common bugs and syntax errors (e.g., missing a curly brace). 131 | This saves real world time when it comes to fixing problems in your code. 132 | 133 | * It is easier to extend and/or incorporate into other projects. This results in your 134 | code being more useful to others as well as your future self. 135 | 136 | The list could go on. The important thing to remember is that **quality not only 137 | refers to the output of a program but also its effect on the people who interact 138 | with the code**. Rarely, in practice, are you the only one who will read and use 139 | your code. If you're a software engineer, then it is very likely that *many* 140 | people will interact your code over time and that you will interact with *lots* 141 | of code written by others as well. 142 | 143 | ## When and How to Check 144 | 145 | Here is a fair and honest warning: if you wait until you are nearly done 146 | writing some code before checking its style, then do not be surprised if 147 | you significantly increases the overall amount of time you need 148 | to complete an assignment. You won't have a good time. Much of that extra 149 | time will be from: 150 | 151 | * fixing many code style violations; 152 | * fixing bugs introduced by fixing code style violations; 153 | * fixing bugs earlier that would have been easier to spot had your code 154 | been in compliance; and 155 | * rewriting code you wrote earlier because you no longer understand 156 | how it works. 157 | 158 | Why would you subject yourself to that? Is there a better way? Remember, 159 | Kernighan and Pike said, "it is important to think about style from the 160 | beginning." If you're a beginner, then that seems almost as daunting as 161 | the alternative, even if you do nod your head as we list out the 162 | benefits. It's daunting because you may not know what good style is yet. 163 | We know this, and that is why we provide you with access to Checkstyle, 164 | a program that automates the process of checking your code for compliance! 165 | 166 | ### When to Check 167 | 168 | You should check your code early and often. The goal is to help you learn 169 | good style, so every time you see that you're not in compliance, you should 170 | take the time to fix it. Although you may find that you have many violations 171 | early on (that's to be expected), over time you will find that you run into 172 | fewer and fewer violations. This happens because you start to write code 173 | code in good style. It's a pretty neat way to learn. 174 | 175 | If you don't check your code for compliance early and often, then not only 176 | are you dooming yourself to the miserable time sink of "not fun" activities 177 | described earlier, you are actively avoiding learning. 178 | 179 | ### Run Checkstyle 180 | 181 | To check your Java source code for compliance, you can use a custom version 182 | of the Checkstyle program on `odin` called `check1302`. **This program is 183 | only guaranteed to work if your code compiles**, so if you encounter a 184 | crash, then check to make sure your code compiles before proclaiming 185 | defeat. 186 | 187 | To run the `check1302` program on an individual file, say `src/cs1302/Test.java`, 188 | you can execute the command below: 189 | 190 | ``` 191 | $ check1302 src/cs1302/Test.java 192 | ``` 193 | 194 | In the program output, any warnings that appear relate directly 195 | to style guidelines presented elsewhere in this document. For example: 196 | 197 | ``` 198 | [ERROR] src/cs1302/Test.java:2: Missing a Javadoc comment. [MissingJavadocType] 199 | ``` 200 | 201 | Here, we see that the [`MissingJavadocType`](#missingjavadoctype) guideline was 202 | not met on line `2` in `src/cs1302/Test.java`. The output even gives a short 203 | description of what it thinks is wrong. If the short description is not sufficient 204 | to determine what the issue is, then you should consult the section for that 205 | guideline [here](#specific-guidelines) for more information. 206 | 207 | To avoid needless 208 | scrolling, we recommend using the table of contents near the beginning of this 209 | style guide or your browser's "find text" feature whenever you want to find 210 | the section for a specific guideline. 211 | 212 | ### Multiple Files 213 | 214 | You might want to check all the files in some `src` directory. To do this, you can 215 | pass the entire directory to `check1302` as in the following command: 216 | 217 | ``` 218 | $ check1302 src 219 | ``` 220 | 221 | ### Output Examples 222 | 223 | Here is some example output for an **invalid file**: 224 | 225 | ``` 226 | Starting audit... 227 | [ERROR] src/cs1302/Test.java:2: Missing a Javadoc comment. [MissingJavadocType] 228 | [ERROR] src/cs1302/Test.java:7:9: '{' at column 9 should be on the previous line. [LeftCurly] 229 | [ERROR] src/cs1302/Test.java:7:9: Must have at least one statement. [EmptyBlock] 230 | [ERROR] src/cs1302/Test.java:11: 'if' construct must use '{}'s. [NeedBraces] 231 | Audit done. 232 | ``` 233 | 234 | In the example above, the programmer would need to find the four error messages listed in 235 | the [Specific Guidelines](#specific-guidelines) section of this document, and also be sure to 236 | read the description and motivation for each error. Here, the programmer would look up the 237 | `MissingJavadocType`, `LeftCurly`, `EmptyBlock`, and `NeedBraces` details. The `checkstyle` 238 | output usually provides extra information to help you fix the problem as illustrated in 239 | the example above. 240 | 241 | Here is some example output for a **valid file**: 242 | 243 | ``` 244 | Starting audit... 245 | Audit done. 246 | ``` 247 | 248 | ## Recommended Emacs Configurations 249 | 250 | **_This section is intended for Emacs users._** 251 | _If you are a Vi/Vim user, then refer to the 252 | [Recommended Vi Configurations](#recommended-vi-configurations) section._ 253 | 254 | Emacs is used by thousands of programmers every day, and each of those 255 | programmers may need to follow one or more style guides at any given 256 | time. Under its default configuration, Emacs can assist programmers in dealing 257 | with many common style issues, and its configuration settings can be 258 | adjusted to help accommodate additional guidelines related to style. While 259 | the degree to which Emacs provides assistance may vary from guideline to 260 | guideline, any assistance at all saves programmers a lot of time and 261 | energy. 262 | 263 | To update your Emacs configuration settings so that it assists with 264 | more of the specific guidelines described in this code style guide, 265 | you need to add some text to the end of a configuration file. In most 266 | cases, this file is stored in your home directory and named `.emacs` -- this 267 | is a text file that is literally named `.emacs` (instead of something like 268 | `.emacs.txt`). From your home directory on Odin, execute the `ls -a` command. 269 | This will list files that start with a `.`. If you do not have a `~/.emacs` file, 270 | then check to see 271 | if either `~/.emacs.el` or `~/.emacs.d/init.el` exist; if so, then use one 272 | of those files in the steps below. If none of these files exist, then we recommend that 273 | you create `~/.emacs` and store your configuration settings there. 274 | 275 | **If you do not understand what file you need to create or edit, 276 | then please ask your instructor or a TA! The following instructions 277 | assume that your Emacs configuration file is `~/.emacs`, which is the 278 | default for most students.** 279 | 280 | You can open the `~/.emacs` file in Emacs using the following command, regardless 281 | of whether the `~/.emacs` file already exists -- if the file does not yet exist, then 282 | it will be created once you save the file using Emacs: 283 | 284 | ``` 285 | $ emacs ~/.emacs 286 | ``` 287 | 288 | Once your `~/.emacs` file is open in Emacs, take a quick look at it. It may be 289 | empty or it may have some existing lines in it -- either situation is okay. If 290 | there are existing lines, then you are NOT required to understand what they do 291 | for this course. 292 | 293 | Now, select and copy the configuration text below -- we recommend that you select 294 | it with your mouse and copy it using a right click (and selecting "Copy") instead 295 | of using a keyboard shortcut: 296 | 297 | ```emacs 298 | ;; handle multi-line inline lambda expressions 299 | (setq c-offsets-alist '((arglist-cont-nonempty . 0))) 300 | ``` 301 | 302 | Now, return to Emacs where your `~/.emacs` file should still be open, and navigate to 303 | the bottom/end of the file by pressing `M->` (i.e., `M-Shift-.` where `.` is the period) -- if 304 | the file is empty, then you won't go very far (that's okay). Once your cursor is at the 305 | bottom/end of the file, press the Return key once or twice to create some blank lines, then 306 | paste what you copied above by right-clicking on the terminal screen -- if right-clicking does 307 | not paste the text automatically, then right-click and select the "Paste" option to paste 308 | the text. 309 | 310 | Once the text is pasted in the file, press `C-x C-s` to save the file, then `C-x C-c` to 311 | close/exit Emacs. 312 | 313 | The configuration changes should take effect the next time you start Emacs. If you get an 314 | error related to your "Init file" the next time you start Emacs, see an instructor 315 | during office hours for assistance. If you do not encounter an error, then you should be 316 | good to go! 317 | 318 | 368 | 369 | 407 | 408 | #### Show Style Guide Violations in the Editor (Optional) 409 | 410 | Add the lines below to your Emacs configuration file to install and 411 | configure the [`flycheck`](https://www.flycheck.org/) package via 412 | use-package so that style guide violations are shown directly inside 413 | Emacs when editing Java source code files. 414 | 415 | ```elisp 416 | ;; enable on-the-fly syntax checking 417 | (use-package flycheck 418 | :init (global-flycheck-mode) 419 | :commands flycheck-parse-checkstyle 420 | :config 421 | (progn 422 | ;; setup a syntax checker that conforms to the CSCI 1302 Code Style Guide 423 | (flycheck-define-checker java-checkstyle-checker 424 | "A Java style checker using Checkstyle." 425 | :command ("checkstyle" "-c" "/usr/local/mepcott/cs1302/cs1302_checks.xml" "-f" "xml" source) 426 | :error-parser flycheck-parse-checkstyle 427 | :enable t 428 | :modes java-mode) 429 | ;; show style guide violations in emacs when in java-mode 430 | (add-to-list 'flycheck-checkers 'java-checkstyle-checker))) 431 | ``` 432 | 433 | ## Recommended Vi Configurations 434 | 435 | **_This section is intended for Vi/Vim users._** 436 | _If you are an Emacs user, then refer to the 437 | [Recommended Emacs Configurations](#recommended-emacs-configurations) section._ 438 | 439 | Vi/Vim, hereafter referred to as Vi, is used by thousands of programmers every day, 440 | and each of those programmers may need to follow one or more style guides at any 441 | given time. Under its default configuration, Vi can assist programmers in dealing 442 | with many common style issues, and its configuration settings can be adjusted to 443 | help accommodate additional guidelines related to style. While the degree to which Vi 444 | provides assistance may vary from guideline to guideline, any assistance at all 445 | saves programmers a lot of time and energy. 446 | 447 | To update your Vi configuration settings so that it assists with 448 | more of the specific guidelines described in this code style guide, 449 | you need to add some text to the end of a configuration file. In most 450 | cases, this file is stored in your home directory and named `.vimrc` -- this 451 | is a text file that is literally named `.vimrc` (instead of something like 452 | `.vimrc.txt`). 453 | 454 | Let's assume that you want to store your settings in `~/.vimrc`. 455 | You can open that file with Vi, even if it does not yet exist -- it 456 | will get created when you save. Once open, add the lines we present below 457 | to the end of the file (could be the top if it's empty), then save the 458 | file and exit Vi. If you did this correctly, then the settings will 459 | take effect the next time you launch Vi. One quick way to see if you 460 | got it working is to open a `.java` in Vi and see if it shows line 461 | numbers; if so, then you should be good to go! 462 | 463 | **If you do not understand what file you need to create or edit, 464 | then please ask your instructor or a TA!** 465 | 466 | Here are the lines that you should add to your Vi configuration 467 | file: 468 | 469 | ``` 470 | " enable line numbers 471 | set number 472 | 473 | " handle tabs and indents 474 | filetype plugin indent on 475 | set tabstop=4 476 | set shiftwidth=4 477 | set expandtab 478 | 479 | " show trailing whitespace 480 | set list listchars=trail:.,extends:> 481 | ``` 482 | 483 | ## Specific Guidelines 484 | 485 | The name for each of these guidelines corresponds to a Checkstyle module 486 | configured in [`cs1302_checks.xml`](cs1302_checks.xml) for use by the 487 | `check1302` program. This was done so that it's easier for users to relate 488 | `check1302` program output to the actual guidelines. 489 | 490 | ### ArrayTypeStyle 491 | 492 | You must use the Java style for array type declarations and not the C style. 493 | The Java style places the square brackets (i.e., the `[]`) to the left of the 494 | variable name, next to the array's element type. 495 | 496 | ```java 497 | public static void main(String[] args) { // Java style; valid style 498 | ``` 499 | 500 | ```java 501 | public static void main(String args[]) { // C style; invalid style 502 | ``` 503 | 504 | ```java 505 | String[] someVar; // Java style; valid style 506 | ``` 507 | 508 | ```java 509 | String someVar[]; // C style; invalid style 510 | ``` 511 | 512 | **Rationale:** 513 | An array is a type of object in Java. While the C style presented above is 514 | syntactically correct in Java (i.e., it will compile), Oracle advises that, 515 | "convention discourages this form; the brackets identify the array type and 516 | should appear with the type designation." When declaring a variable 517 | that refers to an array object, the Java style results in a declaration that 518 | is consistent with how variables to other, non-array types of objects are 519 | declared. 520 | 521 | ### CheckStyleException 522 | 523 | The checkstyle program assumes that the Java source code files it checks are able to be 524 | compiled. 525 | 526 | ### ConstantName 527 | 528 | Constant names must use `CONSTANT_CASE`: all uppercase letters, with each word separated 529 | from the next by a single underscore. A _constant_ is a `static` and `final` field or an 530 | interface/annotation field, except `serialVersionUID` and `serialPersistentFields`. 531 | 532 | **Note:** A field that is `final` but not `static` is sometimes referred 533 | to as an *instance constant* or *constant instance member* because it looks 534 | like an instance variable that is also declared `final`. Despite being `final`, an 535 | instance constant is not considered a "constant" under the definition 536 | provided by this `[ConstantName]` guideline -- the definition requires that it also be 537 | `static` -- and should follow the same naming convention as instance variables as 538 | described in the [`[MemberName]`](#membername) guideline. 539 | 540 | **Rationale:** 541 | This naming convention for constants is pervasive among Java programmers and is even 542 | the same convention used by Oracle and Google. This specific convention allows most 543 | programmers to easily identify a constant when used in source code. 544 | 545 | ### EmptyBlock 546 | 547 | Empty code blocks are not allowed. 548 | 549 | **Rationale:** 550 | Code blocks are for code. If, for some reason, you believe that you need an empty code 551 | block, then take a step back and rework your control flow. 552 | 553 | **Note:** If the `checkstyle` tool reports this for an empty `catch` block, then please 554 | see the [[EmptyCatchBlock]](#emptycatchblock) policy. 555 | 556 | ### EmptyCatchBlock 557 | 558 | Empty `catch` blocks are not allowed. 559 | 560 | ```java 561 | try { 562 | ... 563 | } catch (IOException ioe) { 564 | // empty; invalid style 565 | } 566 | ``` 567 | 568 | **Rationale:** The purpose of a `catch` block is to handle an exception. 569 | If it is not appropriate for you to handle the exception in a method 570 | directly, then explore the possibility of propagating the exception up 571 | using `throws` in the method signature. 572 | 573 | **Note:** Depending on the parsing behavior of the `checkstyle` program, 574 | an empty `catch` block may trigger the `EmptyBlock` policy instead. 575 | 576 | ### EmptyLineSeparator 577 | 578 | You should ensure that empty line separators are present after the header, 579 | package, all import declarations, fields, constructors, methods, nested classes, 580 | policy is made to allow no empty lines between fields (e.g., between 581 | instance variables in a class). 582 | 583 | ```java 584 | import java.util.Scanner; // not separated by 585 | public class MyClass { // at least one line; 586 | private int x; // invalid style 587 | ... 588 | ``` 589 | 590 | This policy also disallows multiple instance variable declarations on the 591 | same line using the comma operator: 592 | 593 | ```java 594 | private int n, k; // k declaration not separated from previous statement 595 | ``` 596 | 597 | **Rationale:** 598 | This vastly improves readability. 599 | 600 | ### FileTabCharacter 601 | 602 | No tab characters (`\t`) are allowed in the normal whitespace of the source code. 603 | This does not include tabs in string literals. For example, the following 604 | snippet is okay: 605 | 606 | ```java 607 | String s = "word1\tword2"; 608 | ``` 609 | 610 | What tabs are not allowed? Specifically, this policy forbids a tab from 611 | occurring in the underlying whitespace of your source code. Some 612 | examples that illustrate the difference are provided below. When using 613 | `cat` to display a file, the `-T` option can be used to display `TAB` characters 614 | as `^I`. 615 | 616 | * Use the command below to generate `One.java`, a small class that 617 | violates the `FileTabCharacter` guideline by using a single `TAB` 618 | character in the whitespace just before the declaration of 619 | `private int x = 1;`: 620 | 621 | ``` 622 | $ echo -e "public class One {\n\tprivate int x = 1;\n}\n" > One.java 623 | ``` 624 | ``` 625 | $ cat -T One.java 626 | public class One 627 | ^Iprivate int x = 1; 628 | } 629 | ``` 630 | 631 | Since a `TAB` (`\t`) is used in the whitespace, the line with the `TAB` 632 | may appear differently depending on how the program used to view the 633 | file is configured. We can simulate that here: 634 | 635 | ``` 636 | $ tabs 3; cat One.java 637 | public class One 638 | private int x = 1; 639 | } 640 | ``` 641 | ``` 642 | $ tabs 5; cat One.java 643 | public class One 644 | private int x = 1; 645 | } 646 | ``` 647 | ``` 648 | $ tabs 9; cat One.java 649 | public class One 650 | private int x = 1; 651 | } 652 | ``` 653 | 654 | * Use the command below to generate `Two.java`, a small class where 655 | four spaces are used before the declaration of `private int y = 2;`: 656 | 657 | ``` 658 | $ echo -e "public class Two {\n\tprivate int y = 2;\n}\n" > Two.java 659 | ``` 660 | ``` 661 | $ cat -T Two.java 662 | public class Two 663 | private int y = 2; 664 | } 665 | ``` 666 | 667 | Since no `TAB` (`\t`) is used in the whitespace, the line with four 668 | spaces do not appear differently depending on how the program used 669 | to view the file is configured. We can simulate that here: 670 | 671 | ``` 672 | $ tabs 3; cat Two.java 673 | public class Two 674 | private int y = 2; 675 | } 676 | ``` 677 | ``` 678 | $ tabs 5; cat Two.java 679 | public class Two 680 | private int y = 2; 681 | } 682 | ``` 683 | ``` 684 | $ tabs 9; cat Two.java 685 | public class Two 686 | private int y = 2; 687 | } 688 | ``` 689 | 690 | When you go to write the inside/body of a class or method, you likely press the 691 | `TAB` key on your keyboard. Most text editors implement this by placing the 692 | following directly in the contents of the code file where you press the 693 | `TAB` key: 694 | 695 | 1. One `\t` (single tab character); or 696 | 1. Multiple ` ` (single whitespace character). 697 | 698 | This policy specifically forbids the first of these two approaches. 699 | If you use the [recommended Emacs configurations](#recommended-emacs-configurations) 700 | or [recommended Vi configurations](#recommended-vi-configurations), then 701 | you will be to avoid _future_ non-conformance of this policy. 702 | 703 | **Fix using Emacs:** 704 | If you are an Emacs user who has set up the 705 | [recommended Emacs configurations](#recommended-emacs-configurations), then you 706 | can fix individual lines that violate `FileTabCharacter` by moving to the start 707 | of an offending line and using the following command: `M-x untabify RET` 708 | (i.e., type `M-x`, the entire word `untabify`, then the 709 | return key). To fix an entire file, move to the beginning of the file and use the 710 | following command: `C-u M-x untabify`. 711 | 712 | **Rationale:** 713 | The use of tabs instead of spaces may result in different text editors displaying 714 | the same file in different ways, depending on the tab width configured for the 715 | given editor. Developers should not need to configure the tab width of their 716 | text editors in order to be able to read source code. 717 | 718 | ### Indentation 719 | 720 | The following indentation rules must be followed: 721 | 722 | | Property | Description | Spaces | 723 | |---------------------------|-----------------------------------------------------------------------------|--------| 724 | | `basicOffset` | how far the new indentation level should be indented when on the next line | 4 | 725 | | `braceAdjustment` | how far a brace should be indented when on the next line | 0 | 726 | | `caseIndent` | how far a case label should be indented when on the next line | 0 | 727 | | `throwsIndent` | how far a throws clause should be indented when on the next line | 4 | 728 | | `arrayInitIndent` | how far an array initializer list item should be indented when on next line | 4 | 729 | | `lineWrappingIndentation` | how far the continuation line should be indented when line-wrapping is present | 4 | 730 | 731 | Sometimes, indentation rules are a little hard to parse when parentheses and 732 | curly braces are involved, as is sometimes the case with multi-line inline lambda 733 | expressions. An inline lambda expression is a lambda expression that is used as 734 | a parameter to a method. Here is an example: 735 | 736 | ```java 737 | // BAD INDENTATION 738 | Arrays.sort(array, (a, b) -> { 739 | return a.compareTo(b); // 'block' child has incorrect indentation 740 | }); // 'block rcurly' has incorrect indentation 741 | ``` 742 | 743 | ```java 744 | // GOOD INDENTATION 745 | Arrays.sort(array, (a, b) -> { 746 | return a.compareTo(b); 747 | }); 748 | ``` 749 | 750 | If these rules make one of your inline lambda expressions look less readable, 751 | then you are encouraged to refactor your lambda expression, if possible, to 752 | avoid indentation. Here is the same inline lambda written using one line of 753 | code: 754 | 755 | ```java 756 | // HOWEVER, if you can write using one line, then please do so 757 | Arrays.sort(array, (a, b) -> a.compareTo(b)); 758 | ``` 759 | 760 | ### JavadocMethod 761 | 762 | All methods, except the `main` method, must have **full** Javadoc documentation, 763 | including documentation of parameters, exceptions, and return value. 764 | For example: 765 | 766 | ```java 767 | /** 768 | * Returns {@code true} if this list contains the specified string. More formally, returns 769 | * {@code true} if, and only if, this list contains at least one element {@code s} such that 770 | * {@code o.equals(s)}. 771 | * 772 | * @param o string whose presence in this list is to be tested 773 | * @return true if this list contains the specified string 774 | * @throws NullPointerException if the specified string is {@code null} 775 | * @throws IllegalArgumentException if the specified string is empty 776 | */ 777 | public boolean contains(String o); 778 | ``` 779 | 780 | ### LeftCurly 781 | 782 | Left curly braces (`{`) for code blocks must always be on the end of the line. 783 | For example: 784 | 785 | ```java 786 | if (condition) { 787 | ... 788 | ``` 789 | 790 | **Rationale:** 791 | This convention for curly braces is pervasive among Java programmers and 792 | is even the same convention used by companies like Google. 793 | 794 | ### LineLength 795 | 796 | You should limit the number of characters, including whitespace, on any given 797 | line to 100 characters. Except as noted below, any line that would exceed this 798 | limit must be manually line-wrapped in a consistent manner. Exceptions to the 799 | column limit include: 800 | * lines where obeying the column limit is not possible (for example, a long URL 801 | in Javadoc, or a long JSNI method reference); 802 | * package and import statements; and 803 | * command line input examples in a comment that may be cut-and-pasted into a shell. 804 | 805 | **Rationale:** Long lines are hard to read in printouts or if developers have 806 | limited screen space for the source code, e.g. if the editor displays additional 807 | information like line numbers, multiple files, project tree, class hierarchy, etc. 808 | 809 | ### MemberName 810 | 811 | Instance variable names must be written in `lowerCamelCase`. 812 | 813 | **Rationale:** 814 | This naming convention for instance variables is pervasive among Java programmers and 815 | is even the same convention used by Oracle. 816 | 817 | ### MethodName 818 | 819 | Method names must be written in `lowerCamelCase`. 820 | 821 | **Rationale:** 822 | This naming convention for methods is pervasive among Java programmers and 823 | is even the same convention used by Oracle. 824 | 825 | ### MethodLength 826 | 827 | The bodies of methods and constructors should never exceed 60 lines. 828 | This includes the line(s) with the method's signature and opening curly brace, 829 | all lines in the body of the method (including blank lines), and the line with the 830 | method's ending curly brace. The method length does not include a method's Javadoc 831 | comment, however, it does include any comments and blank lines contained within the 832 | body of the method. 833 | 834 | **Rationale:** 835 | If a method becomes very long it is hard to understand. Here is the spirit of this 836 | guideline: methods that are too big and/or repetitive should be refactored to include 837 | proper looping constructs and/or broken up into smaller methods to improve readability. 838 | 839 | **Instructor Note:** 840 | You should always try to limit the number of lines for a method so that the 841 | entire method can be seen on the screen at once, even when multiple files 842 | are open at the same time on a single screen. 843 | 844 | ### MissingJavadocMethod 845 | 846 | All methods, except the `main` method, must have Javadoc documentation. 847 | 848 | If a method is annotated with `@Override`, then it is assumed to have 849 | Javadoc documentation inherited from the method it's overriding. 850 | If a method overrides a method without using the `@Override` annotation, 851 | then you are required to explicitly provide a Javadoc comment for that 852 | method to stay compliant with this style guide. 853 | 854 | If you want to explicitly write a Javadoc comment for an override that 855 | inherits its documentation from the method it is overriding, then use 856 | the following comment: 857 | 858 | ```java 859 | /** {@inheritDoc} */ 860 | ``` 861 | 862 | If the Javadoc tool does not have access to the source code for the class or interface, then 863 | it is suggested that you use the following comment, replacing the sentence with something appropriate, 864 | in order to avoid a blank description in the generated documentation website: 865 | 866 | ```java 867 | /** 868 | * Summary sentence. 869 | * 870 | *
871 | * {@inheritDoc} 872 | */ 873 | ``` 874 | 875 | You can even add more text after the `{@inheritDoc}` if you want to provide more details 876 | in addition to what is inherited: 877 | 878 | ```java 879 | /** 880 | * Summary sentence. 881 | * 882 | *
883 | * {@inheritDoc} 884 | * 885 | *
886 | * A sentence or two concerning how this method behaves in a 887 | * particular way due to the underlying implementation. 888 | */ 889 | ``` 890 | 891 | **NOTE:** The `
` tags in the Javadoc comments above just start new paragraphs in the website output. 892 | 893 | **Rationale:** 894 | Providing sufficiently detailed documentation helps make code maintenance and bug 895 | identification much easier. Additionally, it's critical for code that others will 896 | use but not necessarily see the actual implementation (e.g., when you use a `String` 897 | method). 898 | 899 | **Instructor Note:** 900 | Well-documented code is just as important as correctly working code. 901 | 902 | ### MissingJavadocType 903 | 904 | All class, enum, interface, and annotation interface definitions must have Javadoc 905 | documentation. 906 | 907 | **Rationale:** 908 | Just like methods, type documentation is also important. Oftentimes class and interface 909 | documentation provide important high-level details about implementation, naming 910 | conventions, etc. In some cases, even code examples are provided directly in the 911 | documentation to make things easier for programmers who wish to use the code. 912 | 913 | **Instructor Note:** 914 | Well-documented code is just as important as correctly working code. 915 | 916 | ### ModifierOrder 917 | 918 | When using modifier keywords, you should ensure that their order conforms to 919 | the suggestions in the Java Language Specification, sections 920 | [8.1.1, 8.3.1, 8.4.4](https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html), and 921 | [9.4](https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html). 922 | 923 | The correct order is: 924 | 925 | ``` 926 | public 927 | protected 928 | private 929 | abstract 930 | default 931 | static 932 | final 933 | transient 934 | volatile 935 | synchronized 936 | native 937 | strictfp 938 | ``` 939 | 940 | **Rationale:** 941 | This ordering convention for methods is pervasive among Java programmers and 942 | is even the same convention used by Oracle and Google. 943 | 944 | ### NeedBraces 945 | 946 | Curly braces are always used where technically optional. Braces should be used with 947 | `if`, `else`, `for`, `do`, and `while` statements, even when the body is empty 948 | or contains only a single statement. 949 | 950 | **Rationale:** 951 | Consider `if` statements without curly braces. In Java, only the first statement 952 | following such `if` statements is executed when the conditional's expression 953 | evaluates to `true`. Potential bugs can be avoided by using curly braces to 954 | clearly indicating what statement or statements are to execute when the 955 | conditional's expression evaluates to `true`. 956 | 957 | **Instructor Note:** 958 | One common bug that we've seen over the years is students adding statements 959 | to a brace-less `if` statement with the intent that those statements only 960 | execute when the conditional's expression evaluates to `true`. That is, 961 | they forgot to add the curly braces. This guideline helps protect you 962 | against that scenario and improves readability. 963 | 964 | ### OneStatementPerLine 965 | 966 | In general, you only have one statement per line. The policy specifically checks 967 | the following types of statements: variable declaration statements, empty statements, 968 | import statements, assignment statements, expression statements, increment statements, 969 | object creation statements, for loop statements, break statements, 970 | continue statements, and return statements. 971 | 972 | **Rationale:** 973 | It's very difficult to read multiple statements on one line. 974 | In the Java programming language, statements are the fundamental unit of execution. 975 | All statements except blocks are terminated by a semicolon. 976 | Blocks are denoted by open and close curly braces. 977 | 978 | ### OneTopLevelClass 979 | 980 | Each top-level class, interface, or enum resides in a source file of its own. 981 | The official description of a 'top-level' term: 982 | [7.6. Top Level Type Declarations](https://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.6). 983 | If the file does not contain a `public` class, enum, or interface, then the top-level 984 | type is the first type in the file. 985 | 986 | ### OuterTypeFilename 987 | 988 | In any given `.java` file, the outer type name and the file name must match. 989 | For example, the class `Foo` must be in a file named `Foo.java`. 990 | 991 | **Rationale:** Although this is only technically required by the Java Language 992 | Specification when the outer type is declared with `public` visibility, we 993 | stick to this convention for other visibilities as well. In any case, most of 994 | the time your outer type will be declared as `public`. 995 | 996 | ### RightCurly 997 | 998 | Right curly braces (`}`) for single-part blocks must be on their own line. 999 | Right curly braces for multi-part blocks must be on the same line as the 1000 | next part of a multi-block statement. For example: 1001 | 1002 | ```java 1003 | if (a > 0) { 1004 | ... 1005 | } // this is okay 1006 | ``` 1007 | 1008 | ```java 1009 | if (a > 0) { 1010 | ... 1011 | } else { // this is okay 1012 | ... 1013 | ``` 1014 | 1015 | ```java 1016 | if (a > 0) { 1017 | ... 1018 | } // this is not okay 1019 | else { 1020 | ... 1021 | ``` 1022 | 1023 | **Rationale:** 1024 | This convention for curly braces is pervasive among Java programmers and 1025 | is even the same convention used by companies like Google. 1026 | 1027 | ### SummaryJavadoc 1028 | 1029 | In Javadoc comments, the 1030 | [summary sentence](https://www.oracle.com/technetwork/java/javase/documentation/index-137868.html#firstsentence) 1031 | should always be present and correctly punctuated. 1032 | The only exception to this rule is when the first statement in the comment 1033 | is `{@inheritDoc}`. 1034 | 1035 | **Rationale:** 1036 | The first sentence of a Javadoc comment is the text that appears in the 1037 | summary lists of a generated Javadoc website. Failure to either include a summary 1038 | or correctly punctuate the summary can result in poor output. 1039 | 1040 | ### TypeName 1041 | 1042 | Type names for classes, interfaces, enums, and annotations must be written in _UpperCamelCase_. 1043 | Class names are typically nouns or noun phrases. For example, `Character` or `ImmutableList`. 1044 | Interface names may also be nouns or noun phrases (for example, `List`), but may sometimes be 1045 | adjectives or adjective phrases instead (for example, `Readable`). 1046 | 1047 | **Rationale:** 1048 | This convention for type names is pervasive among Java programmers and 1049 | is even the same convention used by companies like Oracle and Google. 1050 | 1051 | ### WhitespaceAround 1052 | 1053 | You need to ensure that code tokens are surrounded by whitespace. 1054 | 1055 | ```java 1056 | if (n==0) { // invalid 1057 | ... 1058 | ``` 1059 | ```java 1060 | if (n == 0) { // valid 1061 | ... 1062 | ``` 1063 | ```java 1064 | while(n == 0) { // invalid 1065 | ... 1066 | ``` 1067 | ```java 1068 | while (n == 0) { // valid 1069 | ... 1070 | ``` 1071 | 1072 | Empty constructor, method, class, enum, interface, loop bodies (blocks), 1073 | lambdas of the forms presented below are exempt: 1074 | 1075 | ```java 1076 | public MyClass() {} // empty constructor 1077 | public void func() {} // empty method 1078 | public interface Foo {} // empty interface 1079 | public class Foo {} // empty class 1080 | public enum Foo {} // empty enum 1081 | MyClass c = new MyClass() {}; // empty anonymous class 1082 | while (i == 1) {} // empty while loop 1083 | for (int i = 1; i > 1; i++) {} // empty for loop 1084 | do {} while (i == 1); // empty do-while loop 1085 | Runnable noop = () -> {}; // empty lambda 1086 | public @interface Beta {} // empty annotation type 1087 | ``` 1088 | 1089 | **Rationale:** 1090 | This convention improves readability. 1091 | 1092 | ## References 1093 | 1094 | * Diamond, M. ([@dimo414](https://github.com/dimo414)). 2016. *Google Java Style Guide.* URL: https://google.github.io/styleguide/javaguide.html 1095 | * Kernighan, B.W. and Pike, R. 1999. *The Practice of Programming.* Addison-Wesley Professional. ISBN: 9780133133448. 1096 | 1097 | ## Publication History 1098 | 1099 | | DOI | Tag | Date | Description | 1100 | |-----|-----|------|-------------| 1101 | | [10.5281/zenodo.3370471](https://doi.org/10.5281/zenodo.3370471) | NA | NA | All Versions | 1102 | | [10.5281/zenodo.3579521](https://doi.org/10.5281/zenodo.3579521) | `v2019fa` | Dec 16, 2019 | Fall 2019 | 1103 | | [10.5281/zenodo.3370472](https://doi.org/10.5281/zenodo.3370472) | `v2019su` | Aug 18, 2019 | Summer 2019 | 1104 | 1105 |