SOL FINAL - Attachment 8 - USPTO Java Coding Standards.pdf
PDF 635 KB Posted
- Attached to
- USPTO Enterprise Cloud Modernization (ECM)
- Solicitation number
- 1333BJ26R00280002
About this file
This document is the USPTO Java Coding Standard (Version 4.1), issued by the United States Patent and Trademark Office on June 4, 2024. It establishes mandatory coding standards for all Java development projects delivered to the USPTO, whether developed by internal staff or contractor personnel. The standard is maintained by the Office of the Chief Information Officer, Business Product Delivery Office, with primary contact being the BPDO Code Reviewer or Manager of the Developer Experience Branch.
The standard prescribes comprehensive requirements across source file structure, formatting, naming conventions, programming practices, and documentation. Key technical requirements include: UTF-8 file encoding with Unix line endings; 130-character column limit with a preferred 90-character target; four-space indentation (no tabs); K&R brace style for non-empty blocks; import statement organization in five distinct blocks (java., javax., third-party, gov.uspto.*, and static imports); and prohibition of wildcard imports except in test code. Naming conventions mandate lowercase packages beginning with "gov.uspto.", UpperCamelCase for classes, lowerCamelCase for methods and non-constant fields, and CONSTANT_CASE for constants. The standard requires @Override annotations, comprehensive Javadoc for public classes and members, mandatory exception handling with justification comments, and security adherence to SEI CERT Oracle Coding Standard for Java. Additional programming practices include keeping controllers thin, limiting method complexity (cyclomatic complexity of 15, line-of-code maximum of 65, nesting level maximum of 3), avoiding magic numbers, using meaningful variable names, preferring enumerations for related constants, and eliminating code duplication. The document references the Google Java Style Guide (CC BY 4.0), Spring Framework and Spring Boot Style Guides, Oracle's Secure Coding Guidelines, and related security standards as authoritative sources.
View the file
Other files
Show all 11
On GovTribe
Work with this file
- Download the original file
- Contacts named in this file
- Similar government files
- Ask GovTribe AI about this file
Text version
USPTO Java Coding Standard
Version 4.1 Page 1 of 25 June 4, 2024
USPTO/OCIO
OCIO-STD-003
Version 4.1
June 4, 2024
Version 4.1 Page 2 of 25 June 4, 2024
Record of Changes/Version History (Version History)
Version Number
Date of Change
Sections Affected Type of Change
4.0 June 2, All • Removed outdated sections from version 3.0
• Adopted a subset of the Google Java Style Guide under CC-By 3.0 License
4.0.1 October
6, 2020
6.6 • Add more details and examples
4.0.2 October
14, 2020
• 3.1
• 6.7
• 8
• Modified section 3.1
• Added section ‘Secure code’
• Added references to Java Language and
Virtual Machine Specifications, Secure Coding Guidelines for Java SE, and SEI CERT Oracle Coding Standard for Java
4.1 April 12,
• 1.4, 3.3.3, 4.1.2, 4.1.3, 4.2, 4.4-4.7, 5.2, 6.2.3, 6.3, 7.1.1
• 1.5
• 6.8 - 6.14
• 8.7, 8.8
• Modified sections 1.4, 3.3.3, 4.1.2, 4.1.3, 4.2, 4.4-4.7, 5.2, 6.2.3, 6.3, 7.1.1
• Adopted a subset of the Google Java Style Guide under CC-By 4.0 License
• Added sections to reflect updated Java standard and coding practice
• Added references to Developing with Spring Boot and Spring Boot Style Guide https://google.github.io/styleguide/javaguide.html https://creativecommons.org/licenses/by/3.0/ https://google.github.io/styleguide/javaguide.html https://creativecommons.org/licenses/by/3.0/
Version 4.1 Page 3 of 25 June 4, 2024
Table of Contents 1 Introduction
1.1 Purpose
1.2 Benefits
1.3 Scope
1.4 Office of Primary Interest
1.5 Relationship to Policies and Other Standards
1.6 Document Conventions
1.6.1 Fixed-Width Font
1.6.2 Sample Code
1.6.3 Section 508 Compliance
2 Source File Basics
2.1 File Name
2.2 File Encoding: UTF-8
2.3 Special Characters
3 Source File Structure
3.1 License or Copyright Information
3.2 Package Statement
3.3 Import Statement
3.3.1 No Wildcard Imports
3.3.2 No Line-Wrapping
3.3.3 Ordering and Spacing
3.3.4 No Static Imports
3.4 Class Declaration
3.4.1 Exactly One Top-Level Class Declaration
3.4.2 Ordering of Class Contents
4 Formatting
4.1 Braces
4.1.1 Braces Are Used Where Optional
4.1.2 Nonempty Blocks: K & R Style
4.1.3 Empty Blocks: May Be Concise
4.2 Indentation
4.3 One Statement Per Line
Version 4.1 Page 4 of 25 June 4, 2024
4.4 Column Limit: 130
4.5 Line-Wrapping
4.6 Blank Lines
4.7 Grouping Parentheses
4.8 Class Declaration
5 Naming
5.1 Package Names
5.2 Class/Interface Names
5.3 Method Names
5.4 Constant Names
5.5 Non-Constant Field Names, Parameter Names, Local Variable Names
5.6 Type Variable Names
6 Programming Practices
6.1 @Override: Always Used
6.2 Caught Exceptions: Not Ignored
6.2.1 Do Not Swallow Exceptions
6.2.2 Avoid Destructive Wrapping
6.2.3 Do Not Log and Re-Throw
6.3 Static Members: Qualified Using Class
6.4 Finalizers: Not Used
6.5 Utility Classes
6.6 Field and Method References
6.7 Secure Code
6.8 Avoid Using Magic Numbers
6.9 Use Meaningful Variable Names
6.10 Use Enumerations for Related Constants
6.11 Default Package
6.12 Keep Controller Thin
6.13 Simplify the Tasks of a Method
6.14 Avoid Code Duplication
7 Javadoc
7.1 Formatting
Version 4.1 Page 5 of 25 June 4, 2024
7.1.1 General form
7.1.2 Paragraphs
7.1.3 Block Tags
7.2 The Summary Fragment
7.3 Where Javadoc is Used
7.3.1 Exception: Self-Explanatory Methods
7.3.2 Exception: Overrides
7.3.3 Non-Required Javadoc
8 References
8.1 Google Java Style Guide: https://google.github.io/styleguide/javaguide.html
8.2 Spring Java Style Guide:
https://github.com/spring-projects/spring-framework/wiki/Code-Style
8.3 Java Language and Virtual Machine Specifications:
https://docs.oracle.com/javase/specs/
8.4 Secure Coding Guidelines for Java SE:
https://www.oracle.com/java/technologies/javase/seccodeguide.html
8.5 SEI CERT Oracle Coding Standard for Java:
https://wiki.sei.cmu.edu/confluence/display/java/SEI+CERT+Oracle+Coding+Standard+fo r+Java
8.6 Department of Commerce Open Source Code Policy:
https://www.commerce.gov/about/policies/source-code
8.7 Developing with Spring Boot: https://docs.spring.io/spring-boot/docs/3.2.6/reference/html/using.html#using.structuring-your-code.using-the-default-package
8.8 Spring Boot Style Guide:
https://github.com/helpermethod/spring-boot-style-guide
Version 4.1 Page 6 of 25 June 4, 2024
1 Introduction
1.1 Purpose
This document specifies the Java Coding Standard enforced by the United States Patent and Trademark Office. The standard established by this document pertains to the Java Programming Language and the Application Programming Interfaces (APIs) of Java SE (Standard Edition).
This standard is not comprehensive, and is subject to change over time. Nevertheless, it provides a strong starting point for developing readable, secure code.
1.2 Benefits
Coding standards and guidelines are beneficial for ensuring code quality. Quality code has these fundamental characteristics:
Readable/Concise – code is readily understood by other developers by virtue of its clarity and adherence to expected formatting and naming conventions. The logic is largely self-documenting with sporadic comments used to explain less obvious segments of code. Classes, methods, and non-local variables have explanatory Javadocs. Each class and method has an ideally singular purpose.
Correct/Consistent – code works as intended in all reasonable circumstances, including multi-threaded execution environments and preferably under greater-than-normal application demands (e.g. user loads, network delays, etc.).
Secure – code is not susceptible to problems that would compromise sensitive data or result in prolonged application failure.
1.3 Scope
Compliance with this standard is required of code delivered for any development project using Java, whether produced by USPTO or contractor staff.
1.4 Office of Primary Interest
The U.S. Patent and Trademark Office, Office of the Chief Information Officer, Office of Business Product Delivery Office (BPDO) is the office of primary interest for this document.
Any questions or comments about the content of this document should be addressed to either the BPDO Code Reviewer for a specific product or the Manager of the Developer Experience Branch.
1.5 Relationship to Policies and Other Standards
This version replaces and supersedes Java Coding Standard version 4.0. It is based on the Google Java Style Guide under CC BY 4.0.
https://google.github.io/styleguide/javaguide.html https://creativecommons.org/licenses/by/3.0/
Version 4.1 Page 7 of 25 June 4, 2024
1.6 Document Conventions
1.6.1 Fixed-Width Font
Java keywords, package and class names, and other inline code fragments appear in a fixed-width font to aid in readability.
1.6.2 Sample Code
Sample code appears within text boxes using a fixed-width font. Code is syntax highlighted for easier readability. Sample code is shown within a bordered text box. Some text boxes contain both conformant and non-conformant code. Inline comments like “/* AVOID */” or “// AVOID” indicate which particular lines do not conform. The conforming code has inline comments like // PREFERRED.
Some sample code may take liberties with prescribed naming and/or formatting conventions, especially in regards to blank lines and line length, in order to display appropriately within this document.
1.6.3 Section 508 Compliance
The document has been through the Section 508 compliance validation and evaluation. It contains no Section 508 compliance issues.
2 Source File Basics
2.1 File Name
The source file name consists of the case-sensitive name of the top-level class it contains (of which there is exactly one), plus the .java extension.
2.2 File Encoding: UTF-8
Source files are encoded in UTF-8.
2.3 Special Characters
Aside from the line terminator sequence, the ASCII horizontal space character (0x20) is the only whitespace character that appears anywhere in a source file. All other whitespace characters in string and character literals are escaped. Tab characters are not used for indentation.
Use Unix (LF), not DOS (CRLF) for line endings.
Eliminate all trailing whitespaces.
Version 4.1 Page 8 of 25 June 4, 2024
3 Source File Structure
A source file consists of the following, in the exact order:
1. License or copyright information, if present
2. Package statement
3. Import statements
4. Exactly one top-level class
Exactly one blank line separates each of the above sections.
3.1 License or Copyright Information
Place appropriate license and copyright information here, if any.
If the work contains source code from open source and the open-source code is used as-is, the licensure and copyright information of the open-source code shall be included for that open-source code. If the work contains source code from open source and the open-source code has been modified, then the licensure and copyright of the open-source code must be complied with and shall be included for that modified open-source code, including any requirement to annotate codes changes. In cases where the licensure requires the sharing of any codes changes or modifications to the open-source component(s), the government shall be notified of the intent to use and specific permission to use and contribute those changes must be given before the code may be used.
3.2 Package Statement
The package statement is not line-wrapped. The column limit (See Column limit) doesn’t apply to package statements.
3.3 Import Statement
3.3.1 No Wildcard Imports
Wildcard imports such as import java.util.*; or import static org.assertj.core.api.Assertions.*; are forbidden, even in test code.
3.3.2 No Line-Wrapping
Import statements are not line wrapped. The column limit (See Column limit) doesn’t apply to import statements.
3.3.3 Ordering and Spacing
Import statements are structured as follows:
Version 4.1 Page 9 of 25 June 4, 2024
1. All java.* import statements in a block
2. All javax.* import statements in a block
3. All other third-party non-static import statements in a block
4. All gov.uspto.* import statements in a block
5. All static import statements in a block
A single blank line separates two blocks.
3.3.4 No Static Imports
Static imports should not be used in production code. They should only be used in test code, especially for things like import static org.assertj.core.api.Assertions.assertThat; .
3.4 Class Declaration
3.4.1 Exactly One Top-Level Class Declaration
Each top-level class resides in a source file of its own.
3.4.2 Ordering of Class Contents
The following governs how the members of a class are organized:
1. static fields
2. normal fields
3. constructors
4. (private) methods called from constructors
5. static factory methods
6. JavaBean properties (i.e. getters and setters)
7. method implementation coming from interfaces
8. private or protected templates that get called from method implementations from interfaces
9. other methods
10. equals , hashCode , and toString
Above all, the organization of the code should use some logical order and feel natural.
"Chronological by date added" ordering is not a logical ordering.
4 Formatting
4.1 Braces
4.1.1 Braces Are Used Where Optional
Braces are used with if, else, else if, for, do, and while statements, even when the body is empty or contains only a single statement.
Version 4.1 Page 10 of 25 June 4, 2024
4.1.2 Nonempty Blocks: K & R Style
Braces follow the Kernighan and Ritchie style ("Egyptian brackets") for nonempty blocks and block-like constructs:
• Do not insert a line break before the opening brace.
• Insert a line break after the opening brace.
• Insert a line break before the closing brace.
• Insert a line break after the closing brace, only if that brace terminates a statement or terminates the body of a method, constructor, or named class. For example, there is no line break after the brace if it is followed by else or a comma.
• Do not insert a line break before else, else if, catch and finally statements.
4.1.3 Empty Blocks: May Be Concise
An empty block or block-like structure may be in K & R style. Alternatively, it may be closed immediately after it’s opened, with no characters or line breaks in between unless it’s part of a multi-block statement.
Brace Examples // Examples for non-empty blocks return () -> { while (condition()) { method();
return new MyClass() { @Override public void method() { if (condition()) { try { something();
} catch (ProblemException e) { recover();
} else if (otherCondition()) { somethingElse();
} else { lastThing();
https://google.github.io/styleguide/jsguide.html#formatting-nonempty-blocks
Version 4.1 Page 11 of 25 June 4, 2024
Brace Examples // Examples for empty blocks // Acceptable void doNothing() {}
// Acceptable void doNothingElse() {
// Not acceptable – No concise empty blocks in a multi-block statement try { doSomething();
} catch (Exception e) {}
4.2 Indentation
All indentations should use 4 spaces (NOT tabs).
Each time a new block or block-like construct is opened, the indent increases by 4 spaces. When the block ends, the indent returns to the previous indent level. The indent level applies to both code and comments throughout the block.
When line-wrapping, each line after the first (each continuation line) is indented 4 spaces from the original line.
Annotations applying to a class, method or constructor appear immediately after the documentation block, and each annotation is listed on a line of its own (that is, one annotation per line). These line breaks do not constitute line-wrapping (Section 4.5, Line-wrapping), so the indentation level is not increased.
Line up the dots when chaining Stream or any other fluent API methods and put each method on a separate line.
Indentation Examples // Block-level indentation example if (someCondition) { // do something doSomething();
// Fluent API indentation example listOfStrings.stream() .filter(s -> s.length() > 3) // double indent (eight spaces) first Stream API method
Version 4.1 Page 12 of 25 June 4, 2024
Indentation Examples .map(String::toUpperCase) // align subsequent Stream API methods with first .collect(Collectors.toList()); // ditto
// Annotation indentation example @Override @Nullable public String getNameIfPresent() {
4.3 One Statement Per Line
Each statement is followed by a line break.
4.4 Column Limit: 130
Java code has a column limit of 130 characters. A "character" means any Unicode code point.
Except as noted below, any line that would exceed this limit must be line-wrapped, as explained in Section 4.5, Line-wrapping.
Each Unicode code point counts as one character, even if its display width is greater or less. For example, if using full width characters, you may choose to wrap the line earlier than where this rule strictly requires.
Exceptions:
• Lines where obeying the column limit is not possible (for example, a long URL in Javadoc, or a long JSNI method reference).
• package and import statements (see Sections 3.2 Package statement and 3.3 Import statements).
4.5 Line-Wrapping
With 130 being the column limit, 90 characters is the preferred line length we aim for. In some cases, the preferred length can be achieved by refactoring code slightly. In other cases, it's just not possible.
90 is not a hard limit. Lines between 90-105 are perfectly acceptable in many cases where it aids readability and where wrapping has the opposite effect of reducing readability. This is a judgement call and it's also important to seek consistency. Many times, you can learn by looking how specific situations are handled in other parts of the code.
Lines between 105-130 are allowed but discouraged and should be few.
Version 4.1 Page 13 of 25 June 4, 2024
No lines should exceed 130 characters.
The one big exception to the above line wrapping rules is Javadoc where we aim to wrap around 80 characters for maximum readability in all kinds of contexts, e.g. reading on GitHub, on your phone, etc.
When wrapping a lengthy expression, 90 characters is the length at which we aim to wrap. In general, put the separator symbols at the end of the line rather on the next line (comma separated arguments, etc.) with the exception of the dot separator (.).
Line Wrapping Examples // Acceptable line wrapping for lambda MyLambda<String, Long, Object> lambda = (String label, Long value, Object obj) -> {
// Acceptable line wrapping for lambda Predicate<String> predicate = str -> longExpressionInvolving(str);
// Acceptable - put separator at the end of the line if (thisLengthyMethodCall(param1, param2) && anotherCheck() && yetAnotherCheck()) {
// Acceptable – put dot separator on the next line listOfStrings.stream() .filter(s -> s.length() > 3) // double indent (eight spaces) first Stream API method .map(String::toUpperCase) // align subsequent Stream API methods with first .collect(Collectors.toList()); // ditto
4.6 Blank Lines
A single blank line always appears:
• Between consecutive members or initializers of a class: fields, constructors, methods, nested classes, static initializers, and instance initializers o Exception: A blank line between two consecutive fields is optional.
• After a method signature that is multiline
Version 4.1 Page 14 of 25 June 4, 2024
• As required by other sections of this document (e.g. Source File Structure, and Import statements)
A single blank line may appear anywhere in the code to improve readability or create logical groupings.
Blank Line Examples // Acceptable – no blank line between consecutive fields private String foo;
private String bar;
// Acceptable – blank between consecutive methods public void oneMethod() {
Blank line here public void anotherMethod() {
// Acceptable – one blank line after a multiline method signature @Override protected Object invoke(FooBarOperationContext context, AnotherSuperLongName name) { Blank line here
4.7 Grouping Parentheses
Optional grouping parentheses are recommended.
It is generally a good idea to use parentheses liberally in expressions involving mixed operators to avoid operator precedence problems.
Grouping Parentheses // Acceptable, but no preferred If (a == b && c == d)
// Preferred IF ((a == b) && (c == d)
Version 4.1 Page 15 of 25 June 4, 2024
4.8 Class Declaration
Try as much as possible to put the implements, extends section of a class declaration on the same line as the class itself.
5 Naming
5.1 Package Names
Package names are all lowercase, with consecutive words simply concatenated together (no underscores). USPTO packages must begin with “gov.uspto.”.
5.2 Class/Interface Names
Class names are written in UpperCamelCase.
Class names are typically nouns or noun phrases. For example, Character or ImmutableList.
Interface names may also be nouns or noun phrases (for example, List), but may sometimes be adjectives or adjective phrases instead (for example, Readable).
There are no specific rules or even well-established conventions for naming annotation types.
Test classes are named starting with the name of the class they are testing, and ending with Test.
For example, HashTest or HashIntegrationTest.
5.3 Method Names
Method names are written in lowerCamelCase.
Method names are typically verbs or verb phrases. For example, sendMessage or stop.
Underscores may appear in JUnit test method names to separate logical components of the name, with each component written in lowerCamelCase. One typical pattern is <methodUnderTest>_<state>, for example pop_emptyStack. There is no One Correct Way to name test methods.
5.4 Constant Names
Constant names use CONSTANT_CASE: all uppercase letters, with each word separated from the next by a single underscore.
Constants are static final fields whose contents are deeply immutable and whose methods have no detectable side effects. This includes primitives, Strings, immutable types, and immutable collections of immutable types. If any of the instance's observable state can change, it is not a constant. Constant case should therefore be chosen only if the field is really a constant.
Version 4.1 Page 16 of 25 June 4, 2024
Constant Name Examples // Constants static final int NUMBER = 5;
static final ImmutableList<String> NAMES = ImmutableList.of("Ed", "Ann");
static final ImmutableMap<String, Integer> AGES = ImmutableMap.of("Ed", 35, "Ann", 32);
static final Joiner COMMA_JOINER = Joiner.on(','); // because Joiner is immutable static final SomeMutableType[] EMPTY_ARRAY = {};
enum SomeEnum { ENUM_CONSTANT }
// Not constants static String nonFinal = "non-final";
final String nonStatic = "non-static";
static final Set<String> mutableCollection = new HashSet<String>();
static final ImmutableSet<SomeMutableType> mutableElements = ImmutableSet.of(mutable);
static final ImmutableMap<String, SomeMutableType> mutableValues = ImmutableMap.of("Ed", mutableInstance, "Ann", mutableInstance2);
static final Logger logger = Logger.getLogger(MyClass.getName());
static final String[] nonEmptyArray = {"these", "can", "change"};
5.5 Non-Constant Field Names, Parameter Names, Local Variable Names
These names are written in lowerCamelCase. One-character names should be avoided.
5.6 Type Variable Names
Each type variable is named in one of two of the two styles:
• A single capital letter, optionally followed by a single numeral (such as E, T, X, T2)
• A name in the form used for classes, followed by the capital letter T (examples:
RequestT, FooBarT)
6 Programming Practices
6.1 @Override: Always Used
Always add @Override on methods overriding or implementing a method declared in a super type.
6.2 Caught Exceptions: Not Ignored
It is very rarely correct to do nothing in response to a caught exception. When it is truly appropriate to take no action whatsoever in a catch block, the reason is justified and explained in a comment.
Version 4.1 Page 17 of 25 June 4, 2024
6.2.1 Do Not Swallow Exceptions
An exception is considered “swallowed” when it is not propagated or reported/logged after being caught. Thus, no information is captured when the Exception occurs, including whether or not the Exception ever did indeed occur. At the very least, log a message inside the catch block.
6.2.2 Avoid Destructive Wrapping
Destructive wrapping is a form of exception swallowing; it loses the stack trace of the original exception. If you need to throw a different exception type, make sure to include the original exception.
6.2.3 Do Not Log and Re-Throw
Avoid logging a caught exception, especially its stack trace, and then re-throwing afterwards as-is or wrapped within a different exception type. Logging and re-throwing results in multiple log entries for the same underlying problem, making it more difficult to track down the problem’s source.
Exception Handling Examples // Not acceptable – swallow exception try { // something } catch (NumberFormatException e) {
// Acceptable – justification provided try { // something } catch (NumberFormatException e) { // it’s ok to have this exception; continue
// Avoid – destructive wrapping try { // do something...
} catch (UnsupportedEncodingException e) { throw new IOException("I/O problems");
// Avoid – log and re-throw try {
Version 4.1 Page 18 of 25 June 4, 2024
Exception Handling Examples // do something...
} catch (UnsupportedEncodingException e) { log.error("Un-supported encoding", e);
throw e;
6.3 Static Members: Qualified Using Class
When a reference to a static class member must be qualified, it is qualified with that class's name, not with a reference or expression of that class's type.
Static Member Examples Foo aFoo = ...;
// Preferred Foo.aStaticMethod();
// Avoid aFoo.aStaticMethod();
// Not acceptable somethingThatYieldsAFoor.aStaticMethod;
6.4 Finalizers: Not Used
It is extremely rare to override Object.finalize .
6.5 Utility Classes
A class that is only a collection of static utility methods must be named with an Utils suffix, must have a private default constructor, and must be abstract. Making the class abstract and providing a private default constructor prevent anyone from instantiating it. For example:
Version 4.1 Page 19 of 25 June 4, 2024
Utility Class Examples public abstract MyUtils { private MyUtils() { /* prevent instantiation */ // static utility methods
6.6 Field and Method References
A field of a class should always be referenced using this . A method of class should not be referenced using this except for explicit constructor invocation, i.e., within a constructor, calling another constructor in the same class.
6.7 Secure Code
Adhere to recommended security coding guidelines to minimize the likelihood of security vulnerabilities. SEI CERT Oracle Coding Standard for Java is considered part of USPTO coding standards. Oracle’s Secure Coding Guidelines for Java SE also provides a set of security-specific coding guidelines targeted at the Java programming language.
6.8 Avoid Using Magic Numbers
A Magic Number in Java refers to a numerical value that appears directly in the code. Instead of using raw numbers in Java, assign such values to named constants with descriptive names. This will make the code more readable and maintainable. The exceptions of this rule are:
• The index of a loop
• The values are null, 0, or 1
• It is an empty string, i.e. “”
6.9 Use Meaningful Variable Names
Choosing meaningful variable names not only improves readability but also enhances code maintainability. Avoid using single-letter variables or cryptic abbreviations. Let the names reflect the purpose of the variable. Consider the following example:
Meaningful Variable Names // Avoid int x = 5;
int yz = 10;
// Preferred
Version 4.1 Page 20 of 25 June 4, 2024
Meaningful Variable Names int width = 5;
int height = 10;
6.10 Use Enumerations for Related Constants
Use enums provide a type-safe way to define a fixed number of values, improving code clarity and eliminating the use of magic numbers or string literals.
Use Enumerations for Related Constants // Avoid - Without enums public static final int MONDAY = 1;
public static final int TUESDAY = 2;
public static final int WEDNESDAY = 3;
public static final int THURSDAY = 4;
public static final int FRIDAY = 5;
// Preferred - With enums public enum WeekDay {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY
Day meetingDay = WeekDay.MONDAY;
6.11 Default Package
When a class does not include a package declaration, it is considered to be in the “default package”. The use of the “default package” should be avoid. It can cause problems for some packages. A known example is for Spring Boot applications that use the @ComponentScan, @EntityScan, or @SpringBootApplication annotations.
6.12 Keep Controller Thin
It is import to keep the code easy to maintain. Keep the controller code thin and encapsulate business logic in services classes. An example is listed below:
Version 4.1 Page 21 of 25 June 4, 2024
Keep Controller Thin // Avoid - Mixed business logic in controller @PostMapping("/users") public ResponseEntity<void> postNewUser(@RequestBody UserRequest userRequest) { if (userRequest.isLessThanEighteenYearsOld()) { throw new IllegalArgumentException("Sorry, only users greater or equal than 18 years old.");
if (!userRequest.hasJob()) { throw new IllegalArgumentException("Sorry, only users working.");
if (!this.userService.hasUsernameAvailable(userRequest.getUsername())) { throw new IllegalArgumentException(String.format( "Sorry, [%s] is not an available username.", userRequest.getUsername()));
this.userService.createNewUser(userRequest);
return ResponseEntity.status(HttpStatus.CREATED).build()
// Preferred - Use services class from controller @PostMapping("/users") public ResponseEntity<void> postNewUser(@RequestBody UserRequest userRequest) { this.userService.createNewUser(userRequest);
return ResponseEntity.status(HttpStatus.CREATED).build();
public class UserService{ public void createNewUser(UserRequest userRequest) { this.validateNewUser(userRequest) UserEntity newUserEntity = this.userMapper.mapToEntity(userRequest);
this.userRepository.save(newUserEntity);
private void validateNewUser(UserRequest userRequest) { // business validations
Version 4.1 Page 22 of 25 June 4, 2024
Keep Controller Thin
6.13 Simplify the Tasks of a Method
A single method should not perform too many operations. This can include checking too many conditions, using lots of variables, and ultimately making it difficult to understand, maintain and reuse. In general, the complexity of a method can be measured by the following parameters:
• The maximum cyclomatic complexity, where cyclomatic complexity refers to the number of possible execution paths inside the method; currently allowed: 15
• The maximum number of line-of-code (LOC); currently allowed: 65
• The maximum nesting level; currently allowed: 3
• The maximum number of accessed variables; currently allowed: 7
There are tools, such as SonarQube, to automatically measure of these parameters.
6.14 Avoid Code Duplication
Avoid code duplication is crucial to promoting efficient development and maintaining clean, maintainable codebases. Developers can reduce code duplication by organizing code into methods, classes, and packages based on their responsibilities and functionalities. Reuse these methods and modules instead of duplication the code.
7 Javadoc
7.1 Formatting
7.1.1 General form
The basic formatting of Javadoc blocks is as seen in this example:
Javadoc Examples
* Multiple lines of Javadoc text are written here,
* wrapped normally...
public int method(String p1) { ... }
/** An especially short bit of Javadoc. */
Version 4.1 Page 23 of 25 June 4, 2024
The basic form is always acceptable. The single-line form may be substituted when the entirety of the Javadoc block (including comment markers) can fit on a single line. Note that this only applies when there are no block tags such as @return.
7.1.2 Paragraphs
One blank line—that is, a line containing only the aligned leading asterisk (*)—appears between paragraphs, and before the group of block tags if present. Each paragraph but the first has <p> immediately before the first word, with no space after.
7.1.3 Block Tags
Any of the standard "block tags" that are used appear in the order @param, @return, @throws, @deprecated, and these four types never appear with an empty description. When a block tag doesn't fit on a single line, continuation lines are indented four (or more) spaces from the position of the @.
7.2 The Summary Fragment
Each Javadoc block begins with a brief summary fragment. This fragment is very important: it is the only part of the text that appears in certain contexts such as class and method indexes.
This is a fragment—a noun phrase or verb phrase, not a complete sentence. It does not begin with A {@code Foo} is a..., or This method returns ..., nor does it form a complete imperative sentence like Save the record.. However, the fragment is capitalized and punctuated as if it were a complete sentence.
Tip: A common mistake is to write simple Javadoc in the form /** @return the customer ID */.
This is incorrect, and should be changed to /** Returns the customer ID. */.
7.3 Where Javadoc is Used
At the minimum, Javadoc is present for every public class, and every public or protected member of such a class, with a few exceptions noted below.
Additional Javadoc content may also be present, as explained in Section 7.3.4, Non-required Javadoc.
7.3.1 Exception: Self-Explanatory Methods
Javadoc is optional for "simple, obvious" methods like getFoo, in cases where there really and truly is nothing else worthwhile to say but "Returns the foo".
Important: it is not appropriate to cite this exception to justify omitting relevant information that a typical reader might need to know. For example, for a method named getCanonicalName, do
Version 4.1 Page 24 of 25 June 4, 2024 not omit its documentation (with the rationale that it would say only /** Returns the canonical name. */) if a typical reader may have no idea what the term "canonical name" means!
7.3.2 Exception: Overrides
Javadoc is not always present on a method that overrides a supertype method.
7.3.3 Non-Required Javadoc
Other classes and members have Javadoc as needed or desired.
Whenever an implementation comment would be used to define the overall purpose or behavior of a class or member, that comment is written as Javadoc instead (using /**).
Non-required Javadoc is not strictly required to follow the formatting rules of Sections 7.1.2, 7.1.3, and 7.2, though it is of course recommended.
8 References
8.1 Google Java Style Guide:
https://google.github.io/styleguide/javaguide.html
8.2 Spring Java Style Guide:
https://github.com/spring-projects/spring-framework/wiki/Code-Style
8.3 Java Language and Virtual Machine Specifications:
https://docs.oracle.com/javase/specs/
8.4 Secure Coding Guidelines for Java SE:
https://www.oracle.com/java/technologies/javase/seccodeguide.html
8.5 SEI CERT Oracle Coding Standard for Java:
https://wiki.sei.cmu.edu/confluence/display/java/SEI+CERT+Oracle+Co ding+Standard+for+Java
8.6 Department of Commerce Open Source Code Policy:
https://www.commerce.gov/about/policies/source-code
8.7 Developing with Spring Boot: https://docs.spring.io/spring-boot/docs/3.2.6/reference/html/using.html#using.structuring-your-code.using-the-default-package https://github.com/spring-projects/spring-framework/wiki/Code-Style https://docs.oracle.com/javase/specs/ https://www.oracle.com/java/technologies/javase/seccodeguide.html https://wiki.sei.cmu.edu/confluence/display/java/SEI+CERT+Oracle+Coding+Standard+for+Java https://wiki.sei.cmu.edu/confluence/display/java/SEI+CERT+Oracle+Coding+Standard+for+Java https://www.commerce.gov/about/policies/source-code https://docs.spring.io/spring-boot/docs/3.2.6/reference/html/using.html#using.structuring-your-code.using-the-default-package https://docs.spring.io/spring-boot/docs/3.2.6/reference/html/using.html#using.structuring-your-code.using-the-default-package https://docs.spring.io/spring-boot/docs/3.2.6/reference/html/using.html#using.structuring-your-code.using-the-default-package
Version 4.1 Page 25 of 25 June 4, 2024
8.8 Spring Boot Style Guide:
https://github.com/helpermethod/spring-boot-style-guide
Issued By
Stephan V. Mitchev Director of Business Product Delivery Office Unites Stated Patent & Trademark Office https://github.com/helpermethod/spring-boot-style-guide
| 1 Introduction |
| 1.1 Purpose |
| 1.2 Benefits |
| 1.3 Scope |
| 1.4 Office of Primary Interest |
| 1.5 Relationship to Policies and Other Standards |
| 1.6 Document Conventions |
| 1.6.1 Fixed-Width Font |
| 1.6.2 Sample Code |
| 1.6.3 Section 508 Compliance |
| 2 Source File Basics |
| 2.1 File Name |
| 2.2 File Encoding: UTF-8 |
| 2.3 Special Characters |
| 3 Source File Structure |
| 3.1 License or Copyright Information |
| 3.2 Package Statement |
| 3.3 Import Statement |
| 3.3.1 No Wildcard Imports |
| 3.3.2 No Line-Wrapping |
| 3.3.3 Ordering and Spacing |
| 3.3.4 No Static Imports |
| 3.4 Class Declaration |
| 3.4.1 Exactly One Top-Level Class Declaration |
| 3.4.2 Ordering of Class Contents |
| 4 Formatting |
| 4.1 Braces |
| 4.1.1 Braces Are Used Where Optional |
| 4.1.2 Nonempty Blocks: K & R Style |
| 4.1.3 Empty Blocks: May Be Concise |
| 4.2 Indentation |
| 4.3 One Statement Per Line |
| 4.4 Column Limit: 130 |
| 4.5 Line-Wrapping |
| 4.6 Blank Lines |
| 4.7 Grouping Parentheses |
| 4.8 Class Declaration |
| 5 Naming |
| 5.1 Package Names |
| 5.2 Class/Interface Names |
| 5.3 Method Names |
| 5.4 Constant Names |
| 5.5 Non-Constant Field Names, Parameter Names, Local Variable Names |
| 5.6 Type Variable Names |
| 6 Programming Practices |
| 6.1 @Override: Always Used |
| 6.2 Caught Exceptions: Not Ignored |
| 6.2.1 Do Not Swallow Exceptions |
| 6.2.2 Avoid Destructive Wrapping |
| 6.2.3 Do Not Log and Re-Throw |
| 6.3 Static Members: Qualified Using Class |
| 6.4 Finalizers: Not Used |
| 6.5 Utility Classes |
| 6.6 Field and Method References |
| 6.7 Secure Code |
| 6.8 Avoid Using Magic Numbers |
| 6.9 Use Meaningful Variable Names |
| 6.10 Use Enumerations for Related Constants |
| 6.11 Default Package |
| 6.12 Keep Controller Thin |
| 6.13 Simplify the Tasks of a Method |
| 6.14 Avoid Code Duplication |
| 7 Javadoc |
| 7.1 Formatting |
| 7.1.1 General form |
| 7.1.2 Paragraphs |
| 7.1.3 Block Tags |
| 7.2 The Summary Fragment |
| 7.3 Where Javadoc is Used |
| 7.3.1 Exception: Self-Explanatory Methods |
| 7.3.2 Exception: Overrides |
| 7.3.3 Non-Required Javadoc |
| 8 References |
| 8.1 Google Java Style Guide: https://google.github.io/styleguide/javaguide.html |
| 8.2 Spring Java Style Guide: |
| https://github.com/spring-projects/spring-framework/wiki/Code-Style |
| 8.3 Java Language and Virtual Machine Specifications: https://docs.oracle.com/javase/specs/ |
| 8.4 Secure Coding Guidelines for Java SE: https://www.oracle.com/java/technologies/javase/seccodeguide.html |
| 8.5 SEI CERT Oracle Coding Standard for Java: https://wiki.sei.cmu.edu/confluence/display/java/SEI+CERT+Oracle+Coding+Standard+for+Java |
| 8.6 Department of Commerce Open Source Code Policy: https://www.commerce.gov/about/policies/source-code |
| 8.7 Developing with Spring Boot: https://docs.spring.io/spring-boot/docs/3.2.6/reference/html/using.html#using.structuring-your-code.using-the-default-package |
| 8.8 Spring Boot Style Guide: |
| https://github.com/helpermethod/spring-boot-style-guide |
| 2024-07-10T09:31:52-0400 | |
| Users, Mitchev, Stephan |
File details come from the government source that posted it. Updated .