{"id":18947486,"url":"https://github.com/pepperkit/java-style-guide","last_synced_at":"2026-03-27T02:30:20.046Z","repository":{"id":42994076,"uuid":"343062926","full_name":"pepperkit/java-style-guide","owner":"pepperkit","description":"Java Style Guide Convention","archived":false,"fork":false,"pushed_at":"2023-06-05T15:16:11.000Z","size":30,"stargazers_count":1,"open_issues_count":1,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-01-01T01:18:38.839Z","etag":null,"topics":["checkstyle","checkstyle-checks","code-style","java","style-guide"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/pepperkit.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2021-02-28T09:10:46.000Z","updated_at":"2022-01-10T08:30:32.000Z","dependencies_parsed_at":"2022-09-09T17:11:50.218Z","dependency_job_id":null,"html_url":"https://github.com/pepperkit/java-style-guide","commit_stats":null,"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pepperkit%2Fjava-style-guide","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pepperkit%2Fjava-style-guide/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pepperkit%2Fjava-style-guide/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/pepperkit%2Fjava-style-guide/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/pepperkit","download_url":"https://codeload.github.com/pepperkit/java-style-guide/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":239946876,"owners_count":19723014,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["checkstyle","checkstyle-checks","code-style","java","style-guide"],"created_at":"2024-11-08T13:10:07.075Z","updated_at":"2026-03-27T02:30:19.938Z","avatar_url":"https://github.com/pepperkit.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Java Style Guide\n![Version](https://img.shields.io/badge/Latest%20Version-v1.0.2--9.2-blue)\n![Checkstyle](https://img.shields.io/badge/Checkstyle%20Compatible-v10.12-green)\n\nJava style guide built upon Sun Microsystems and Google style guides, widely accepted best practices. Is offered in \nform of a textual representation, as well as `Checkstyle` and `Intellij IDEA` declarations for automation purposes.\n\n[Checkstyle](https://checkstyle.sourceforge.io/) allows you to conduct static analysis of your Java code and\nhighlights its issues in the means of following the specified code style.\nBut it requires you to specify what is right and what is wrong. There is an official Sun Microsystems style guide, \nbut it's heavily outdated. There are plenty of other style guides but some of them go too far with allowing some \nthings, which can be considered a bad practice, and some are too strict.\n\nIf you struggle to choose a preferred style guide, this particular one is built upon _Sun Microsystems_ and _Google_ style \nguides and is constantly updated to conform to the latest versions of Checkstyle.\nYou can freely use this one, or create a new one - just fork this repository and modify the style guide as it\nbetter suited to your needs.\n\n- [How to use](#how-to-use)\n- [Versioning](#versioning)\n- [Style Guide](#style-guide)\n    - [Project Structure](#project-structure)\n    - [Source Code File](#source-code-file)\n    - [License](#license)\n    - [Import Statements](#import-statements)\n    - [Java Class Structure](#java-class-structure)\n    - [Formatting](#formatting)\n    - [Naming](#naming)\n    - [JavaDoc](#javadoc)\n    - [Tests](#tests)\n- [Resources](#resources)\n\n## How to use\nTo force following your code style guide by all the developers in the team, it's recommended to include Checkstyle\nstatic analysis into the Continuous Integration pipeline, which can be done with the use of the following plugins:\n- [Apache Maven Checkstyle Plugin](https://maven.apache.org/plugins/maven-checkstyle-plugin/)\n- [Gradle Checkstyle Plugin](https://docs.gradle.org/current/userguide/checkstyle_plugin.html)\n\n### Apache Maven\nThen the plugin could be configured in the following way (for Maven):\n```xml\n    \u003cplugins\u003e\n        \u003cplugin\u003e\n            \u003cgroupId\u003eorg.apache.maven.plugins\u003c/groupId\u003e\n            \u003cartifactId\u003emaven-checkstyle-plugin\u003c/artifactId\u003e\n            \u003cversion\u003e3.1.2\u003c/version\u003e\n            \u003cdependencies\u003e\n                \u003cdependency\u003e\n                    \u003cgroupId\u003ecom.puppycrawl.tools\u003c/groupId\u003e\n                    \u003cartifactId\u003echeckstyle\u003c/artifactId\u003e\n                    \u003cversion\u003e10.12.0\u003c/version\u003e\n                \u003c/dependency\u003e\n            \u003c/dependencies\u003e\n            \u003cconfiguration\u003e\n                \u003cconfigLocation\u003ehttps://raw.githubusercontent.com/pepperkit/java-style-guide/v1.0.2-9.2/checkstyle.xml\u003c/configLocation\u003e\n                \u003cencoding\u003eUTF-8\u003c/encoding\u003e\n                \u003cconsoleOutput\u003etrue\u003c/consoleOutput\u003e\n                \u003cfailsOnError\u003etrue\u003c/failsOnError\u003e\n                \u003clinkXRef\u003efalse\u003c/linkXRef\u003e\n            \u003c/configuration\u003e\n        \u003c/plugin\u003e\n    \u003c/plugins\u003e\n```\nBe aware of current versions.\n\n### Suppressions\nCheckstyle allows the definition of a list of files and their line ranges that should be suppressed from reporting any violations see [Using a Suppressions Filter](https://maven.apache.org/plugins/maven-checkstyle-plugin/examples/suppressions-filter.html).\n\nUpdate the plugin configuration like that:\n```xml\n\u003cconfiguration\u003e\n    \u003cconfigLocation\u003ehttps://raw.githubusercontent.com/pepperkit/java-style-guide/v1.0.2-9.2/checkstyle.xml\u003c/configLocation\u003e\n    \u003cencoding\u003eUTF-8\u003c/encoding\u003e\n    \u003cconsoleOutput\u003etrue\u003c/consoleOutput\u003e\n    \u003cfailsOnError\u003etrue\u003c/failsOnError\u003e\n    \u003clinkXRef\u003efalse\u003c/linkXRef\u003e\n    \u003csuppressionsLocation\u003esuppressions.xml\u003c/suppressionsLocation\u003e\n\u003c/configuration\u003e\n```\n\n#### suppressions.xml\n```xml\n\u003c?xml version=\"1.0\"?\u003e\n \n\u003c!DOCTYPE suppressions PUBLIC\n     \"-//Checkstyle//DTD SuppressionFilter Configuration 1.0//EN\"\n     \"https://checkstyle.org/dtds/suppressions_1_0.dtd\"\u003e\n \n\u003csuppressions\u003e\n  \u003csuppress checks=\"ImportOrder\" files=\"\\.java\"/\u003e\n  \u003csuppress checks=\"javadoc\" files=\"\\.java\"/\u003e\n  \u003csuppress checks=\"LineLength\" files=\"\\.java\"/\u003e\n\u003c/suppressions\u003e\n```\n\n### Gradle\nInclude [Checstyle Plugin](https://docs.gradle.org/current/userguide/checkstyle_plugin.html) in the head of `build.gradle` file.\n```\nplugins {\n    id 'checkstyle'\n}\n\ncheckstyle {\n    toolVersion '10.12.0'\n    config project.resources.text.fromUri(new URI(\"https://raw.githubusercontent.com/pepperkit/java-style-guide/v1.0.2-9.2/checkstyle.xml\"))\n}\n```\nBe aware of current versions or any compitible versions.\nIt executes in the build task automatically.\n\n## Versioning\nWhen this style guide is changed, its version increases, it follows semver logic. However, to highlight with which\nversion of Checkstyle this style guide is compatible, the corresponding version of Checkstyle is stated in the version of \nthe style guide.\n\nFor example, if the style guide has version `1.0.2` and it is compatible with Checkstyle version `9.2`, then the version\nof Checkstyle file will be `v1.0.2-9.2`.\n\n## Style Guide\n\n### Project Structure\n\nThe project's structure has to conform to [Standard Directory Layout](https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html).\nThe examples are provided below.\n\n#### Apache Maven\n```text\nproject-name\n├── pom.xml\n├── .gitignore\n├── LICENSE\n├── CHANGELOG.md\n├── README.md\n└── src\n    ├── docker\n    │   └── Dockerfile\n    ├── itest\n    │   ├── java\n    │   ├── kotlin\n    │   └── resources\n    ├── main\n    │   ├── java\n    │   ├── kotlin\n    │   └── resources\n    └── test\n        ├── java\n        ├── kotlin\n        └── resources\n```\n\n#### Gradle\n```text\nproject-name\n├── build.gradle\n├── gradle.properties\n├── setting.gradle\n├── .gitignore\n├── LICENSE\n├── CHANGELOG.md\n├── README.md\n└── src\n    ├── docker\n    │   └── Dockerfile\n    ├── itest\n    │   ├── java\n    │   ├── kotlin\n    │   └── resources\n    ├── main\n    │   ├── java\n    │   ├── kotlin\n    │   └── resources\n    └── test\n        ├── java\n        ├── kotlin\n        └── resources\n```\n\n### Source Code File\n\n#### Encoding\nFiles with the source code have to be in `UTF-8` encoding.\n\n#### Alignment\n* Use spaces (not tabs), one indent - 4 spaces\n* Lines should end with *LF* (Unix way), not CRLF (Windows way)\n* Line's length should not exceed 120 symbols (except import statements)\n* Source code file should end with an empty line\n\n#### Source Code Files Structure\n1. License\n2. Package statements\n3. _Empty line_\n4. Import statements\n5. _Empty line_\n6. One high-level class\n\n### License\nThe license should be put in each source code file in a header.\n\n#### An example of full license text\n```java\n /*\n * Copyright (C) 2021 PepperKit\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *      https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n ```\n\n#### An example of shortened license text\n ```java\n/*\n * Copyright (C) 2021 PepperKit\n *\n * This software may be modified and distributed under the terms\n * of the MIT license. See the LICENSE file for details.\n */\n ```\n\n### Import Statements\nDependencies in *import statements* should be structured in the following way:\n\n* import `java.*`\n* `\u003cblank line\u003e`\n* import `javax.*`\n* `\u003cblank line\u003e`\n* 3rd party imports\n* `\u003cblank line\u003e`\n* import `your.own.imports`\n* `\u003cblank line\u003e`\n* other static imports\n\n\u003e It's not recommended to use *wildcard*s - if there are too many imports it could mean that you should split the\n\u003e class into several classes.\n\n### Java Class Structure\nThe order of the `java` class elements: \n\n1. **static** class fields\n2. **public** instance fields\n3. **protected** instance fields\n4. **private** instance fields\n5. **constructor without parameters**\n6. **other constructors**\n7. **private** methods, which are called from a constructor\n8. **static** fabric methods\n9. **getters**, **setters**\n10. interface methods implementations\n11. **private** or **protected** methods, called from a method with the interface method implementation\n12. other methods\n13. `equals`, `hashCode`, `toString`\n\n### Formatting\n#### Curly Braces\nBraces layout should follow [Kernighan and Ritcle (a.k.a. \"Egyptian brackets\")](https://en.wikipedia.org/wiki/Indentation_style#K.26R):\n* No line breaks before the opening brace\n* One space should precede opening brace\n* A line break should immediately follow opening brace and closing brace, except for multi-block expressions like `if/else` and `try/catch/finally`\n\n##### try/catch example\nCorrect:\n```java\ntry {\n    file = openFile(\"custom_file.txt\");\n} catch (FileNotFoundException e) {\n    file = defaultFile();\n}\n```\n\nIncorrect:\n```java\ntry\n{\n    file = openFile(\"custom_file.txt\");\n}\ncatch (FileNotFoundException e)\n{\n    file = defaultFile();\n}\n```\n\n##### if/else example\nCorrect:\n```java\nif (flag == true) {\n    value = 1000;\n} else {\n    value = 1200);\n}\n```\n\nIncorrect:\n```java\n\nif (flag == true){\n    value = 1000;\n}else{value = 1200);}\n\n```\n\n##### Class definition example\nCorrect:\n```java\npublic class Cat implements Animal {\n\n    @Override\n    protected void speak() {\n        this.meow();\n    }\n}\n```\n\nIncorrect:\n```java\npublic class Cat implements Animal\n{\n    @Override\n    protected void speak()\n    {\n        this.meow();\n    }\n}\n```\n\n#### Line breaks with operators and expressions\nIf the expression's length exceeds **120 symbols**, delimiters (commas, operators, etc.) should be moved to the next line\nto improve readability. In lambda expressions `-\u003e {` should be left on the first line.\n\n##### if example\nCorrect:\n```java\nif (veryImportantFlagWithLongName == true \u0026\u0026 theLineIsLongerThanShouldBe == true\n        \u0026\u0026 importantObject.isPresent() == false) {\n        \n}\n```\n\nIncorrect:\n```java\nif (veryImportantFlagWithLongName == true \u0026\u0026 theLineIsLongerThanShouldBe == true \u0026\u0026\n        importantObject.isPresent() == false) {\n\n}\n```\n\n#### Lambdas example\nCorrect:\n```java\nOptional.ofNullable(configuration.readConfigurations(configPath))\n        .orElse(Lists.newArrayList())\n        .stream()\n        .map(config -\u003e {\n            Setting setting = new Setting(appName);\n            setting.parse(config);\n            return setting;\n        }).collect(Collectors.toList());\n```\n\nIncorrect:\n```java\nOptional.ofNullable(configuration.readConfigurations(configPath))\n        .orElse(Lists.newArrayList())\n        .stream()\n        .map(config \n        -\u003e {\n            Setting setting = new Setting(appName);\n            setting.parse(config);\n            return setting;\n        }).collect(Collectors.toList());\n```\n\nCorrect:\n```java\nstrings.stream()\n\t.filter(s -\u003e s.length() \u003e 2)\n\t.sorted()\n\t.map(s -\u003e s.substring(0, 2))\n\t.collect(Collectors.toList());\n```\n\nIncorrect:\n```java\nstrings.stream().filter(s -\u003e s.length() \u003e 2).sorted()\n\t.map(s -\u003e s.substring(0, 2)).collect(Collectors.toList());\n```\n\n#### Empty lines\nAn empty line should be added after the multi-line method declaration.\n\nCorrect:\n```java\npublic ZooService(CatManagementService catManagementService,\n                                    DogManagementService dogManagementService,\n                                    ElephantManagementService elephantManagementService) {\n        \n    this.catManagementService = catManagementService;\n    this.dogManagementService = dogManagementService;\n    this.elephantManagementService = elephantManagementService;\n}\n```\n\nIncorrect:\n```java\npublic ZooService(CatManagementService catManagementService,\n                                    DogManagementService dogManagementService,\n                                    ElephantManagementService elephantManagementService) {\n        this.catManagementService = catManagementService;\n        this.dogManagementService = dogManagementService;\n        this.elephantManagementService = elephantManagementService;\n        }\n```\n\n#### Semantic separation\nSemantically different blocks of code should be separated by an empty line.\n\n```java\n    VBox frame = new VBox(1);\n    frame.getChildren().add(browser);\n\n    Scene scene = new Scene(frame);\n    stage.setScene(scene);\n    stage.show();\n\n    browser.setPrefSize(3000, 3000);\n    browser.requestFocus();\n```\n\n### Naming\n\n#### Classes\nClass and object names should be a noun or its combination and have **not** to be a verb. \nFor class and interface naming **UpperCamelCase** notation should be used.\n\n#### Interfaces and Implementations\nInterfaces naming with suffix `Impl` is considered an anti-pattern.\n\nCorrect:\n* `Map` - interface for a data structure\n* `HashMap` - implementation of that interface with **hash-tables**\n* `TreeMap` - implementation with **trees**\n\nIncorrect:\n* AuthService - interface for an authentication service\n* AuthService`Impl` - redundant information containing name for the implementation of that interface\n\nNaming convention based on the example of class `Foo`:\n* _Foo_ - interface\n* _Abstract_**_Foo_** - abstract implementation, is supposed to be used as a basis for classes hierarchy\n* _Base_**_Foo_** - concrete implementation, is supposed to be used as a basis for classes hierarchy, where this base class can be used by itself\n* _Default_**_Foo_** - default implementation, is suited for most of the typical use cases\n* _Simple_**_Foo_** - simple implementation, could be served as an example or a skeleton for more complex implementations\n* _{Descriptive}_**_Foo_** - other kinds of implementations, the name should reflect what makes this implementation special\n\n#### Methods\nMethod names should be verbs or verb collocations. \nMethods for getting and setting class fields should have prefixes `get` and `set` correspondingly. \nIf a getting method returns a boolean value, it should be prefixed with `is`. \nFor methods naming **lowerCamelCase** notation should be used.\nMethod name should fully describe what the method does, be consistent, and unambiguous.\n\nCorrect:\n```java\nAuthFilter createAuthenticationFilter();\n```\n\nIncorrect:\n```java\nAuthFilter get_filter();\n```\n\n#### Constants\nUsually, constants are nouns. For naming **CONSTANT_UPPER_CASE** notation should be used - all the letters in upper case,\neach word should be separated by one underscore symbol.\n\nCorrect:\n```java\npublic static final int NUMBER_OF_ELEMENTS_ON_PAGE = 100;\n```\n\nIncorrect:\n```java\npublic static final int numberOfElements = 100;\n```\n\n#### Instance fields, local variables\nShould be in **lowerCamelCase** notation, including *final* fields.\n\nAbbreviations in names should be avoided.\nIf it is impossible, for readability purposes **only the first symbol should be in uppercase**.\n\n\u003eFor example: **_Http_**_Request_, _Product_**_Dao_**\n\n### JavaDoc\nAll public methods and classes should contain JavaDoc. JavaDoc should be explanatory.\n\n#### Formatting\nIt is a good practice to separate paragraphs with `\u003cp\u003e`. Sentences should end with the dot symbol.\n\nOne-sentenced JavaDoc is allowed if it is a class JavaDoc or there are no parameters in a method.\n\nCorrect:\n```java\n/** Animal implementation. */\npublic class Cat implements Animal { }\n```\n\nIncorrect:\n```java\n/**\n * Animal implementation.\n * \u003cp/\u003e\n */\npublic class Cat implements Animal { }\n```\n\n#### Tags\nAny tags used in JavaDoc should not be left empty.\n\nAll tags should follow the order:\n1. **@param** description of a method parameter\n2. **@return** description of a return type\n3. **@throws** exception class name, description of reasons, leading to this exception\n4. **@see** reference to a class, method, field, constant, etc.\n5. **@since** version (from which version tagged element started to be available)\n6. **@deprecated** additional details, including what should be used instead\n\n* To set links to class, field, method, or constant `{@link SomeClass}` tag can also be used.\n* To show text, which should not be interpreted as HTML, the tag `{@code text}` can be used.\n\n\u003eDocumentation on [Tag Conventions](https://www.oracle.com/technetwork/articles/java/index-137868.html).\n\n#### Example\n\n```java\n/**\n * Creates a concrete book file reader by the specified file path. A concrete implementation is chosen based\n * on the file's extension.\n *\n * @param bookFile file referencing a book\n * @return BookFileReader instance\n * @throws IllegalArgumentException      if the specified file does not exist\n * @throws UnsupportedOperationException if an extension of the file is not supported\n * @see TxtFileReader\n */\npublic static BookFileReader createInstance(File bookFile) {\n}\n```\n\n#### Documenting deprecated API\nDeprecated API should be marked with the annotation `@Deprecated` and with the tag `@deprecated` in JavaDoc.\nIt is highly recommended to use the tag `@deprecated` with the commentaries, explaining how to use the new API,\nso that developers had an understandable way to migrate from the old to the new API.\n\n##### Example from JDK\n```java\n/**\n * Makes the {@code Dialog} visible. If the dialog and/or its owner are not yet displayable, both are made displayable.\n * @see Component#hide\n * @deprecated As of JDK version 1.5, replaced by {@link #setVisible(boolean) setVisible(boolean)}.\n */\n@Deprecated\npublic void show() {\n```\n\n##### Javadoc for a new member\nIt should be stated from which version of a library the class, method, field, or constant appeared, with the tag use of tag `@since`.\n\n### Tests\nCode style conventions apply to test classes as well with some particularities described below.\n\n#### Naming Test Classes\n\n##### Unit Tests\nUnit test class names should be ended with postfix `Test`.\n\nExample of unit test on class `Cat.java`:\n```\nCatTest.java\n```\n\n#### Integration Tests\nIntegration test class name should end with postfix `IT` or `IntegrationTest`.\n\nExample of integration test on class `Cat.java`:\n```\nCatIT.java\nCatIntegrationTest.java\n```\n\n#### Recommendations on Naming Test Methods\n\nThe test method's name should reflect the essence of the test.\nIt is recommended to avoid prefixes or postfixes `test` in method names since the test class name already explains that.\n\nIncorrect (it is unclear what this method tests):\n```java\npublic void test1() {}\n```\n\nBetter (it is deductible what is tested, but it is still unclear what particular behavior is tested):\n```java\npublic void testPostNullEntityError() {}\n```\n\nCorrect (test method's name is self-explanatory):\n```java\npublic void shouldThrowExceptionWhenEntityIsNull() {}\n```\n\n## Resources\n1. [Sun Code Conventions](https://github.com/checkstyle/checkstyle/blob/master/src/main/resources/sun_checks.xml)\n2. [Google Java Style Guide](https://google.github.io/styleguide/javaguide.html)\n3. [Spring Code Style](https://github.com/spring-projects/spring-framework/wiki/Code-Style)\n4. \"Clean Code\", Robert Martin\n5. \"Effective Java\", Joshua Bloch\n6. [How to write JavaDoc](https://www.oracle.com/technetwork/java/javase/index-137868.html)\n7. [Impl Classes are evil](https://octoperf.com/blog/2016/10/27/impl-classes-are-evil/)\n8. [Implementations of interfaces](https://blog.joda.org/2011/08/implementations-of-interfaces-prefixes.html)\n9. [How and when to deprecate APIs](https://docs.oracle.com/javase/7/docs/technotes/guides/javadoc/deprecation/deprecation.html)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpepperkit%2Fjava-style-guide","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpepperkit%2Fjava-style-guide","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpepperkit%2Fjava-style-guide/lists"}