From 187fba8ef31e9ee801308f726d2cf80ca7d68f3d Mon Sep 17 00:00:00 2001 From: soWhoAmI Date: Mon, 14 Dec 2020 15:37:12 +0300 Subject: [PATCH 1/5] feature/wp-update ### What's done: * Fixed bugs in GenerationDocs.kt * Updated wp --- .../ruleset/generation/GenerationDocs.kt | 10 + .../cqfn/diktat/ruleset/utils/LatexUtils.kt | 2 +- wp/sections/appendix.tex | 425 +++++++++++++----- 3 files changed, 320 insertions(+), 117 deletions(-) diff --git a/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt b/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt index 53236edca7..7e2d2e8910 100644 --- a/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt +++ b/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt @@ -53,6 +53,15 @@ private fun generateCodeStyle() { ?.removePrefix("") ?.trim() if (name.isNullOrEmpty() || number.isNullOrEmpty()) { + if (number.isNullOrEmpty() && name.isNullOrEmpty()) { + when (line.takeWhile { it == '#' }.count()) { + 1 -> writer.writeln("""\section*{\textbf{${line.removePrefix("#").trim()}}}""") + 2 -> writer.writeln("""\subsection*{\textbf{${line.removePrefix("##").trim()}}}""") + 3 -> writer.writeln("""\subsubsection*{\textbf{${line.removePrefix("###").trim()}}}${"\n"}\leavevmode\newline""") + else -> {} + } + continue + } error("String starts with # but has no number or name - $line") } when (number.count { it == '.' }) { @@ -93,6 +102,7 @@ private fun generateCodeStyle() { line = iterator.next() while (iterator.hasNext() && line.trim().startsWith("|")) { writer.writeln(line + .replace("&", "\\&") .replace('|', '&') .drop(1) .dropLast(1) diff --git a/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/utils/LatexUtils.kt b/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/utils/LatexUtils.kt index b1c1484c27..139ae78840 100644 --- a/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/utils/LatexUtils.kt +++ b/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/utils/LatexUtils.kt @@ -17,7 +17,7 @@ val ITALIC_TEXT = Regex("""\*([A-Za-z ]+)\*""") // finds italic text in regular @Suppress("VARIABLE_NAME_INCORRECT_FORMAT") val BACKTICKS_TEXT = Regex("""`([^`]*)`""") // finds backtick in regular text (not used for now, may be we will need to use it in future) @Suppress("VARIABLE_NAME_INCORRECT_FORMAT") -val ANCHORS = Regex("""\(#(.*)\)""") // finds anchors on rules and deletes them +val ANCHORS = Regex("""\(#([a-zA-Z0-9-.]*)\)""") // finds anchors on rules and deletes them @Suppress("VARIABLE_NAME_INCORRECT_FORMAT") val TABLE_COLUMN_NAMES = Regex("""[A-Za-z ]*""") // used to find column names in tables only const val REGEX_PLACEHOLDER = "RE_PL_AC_E_ME" diff --git a/wp/sections/appendix.tex b/wp/sections/appendix.tex index 4d8063fb55..153ebd0a47 100644 --- a/wp/sections/appendix.tex +++ b/wp/sections/appendix.tex @@ -12,6 +12,55 @@ \section*{guide} \lstMakeShortInline[basicstyle=\ttfamily\bfseries]` + + + + +\section*{\textbf{Diktat Coding Convention}} + + + +\subsubsection*{\textbf{Content}} +\leavevmode\newline + + + +\begin{center} + +\begin{tabular}{ |p{7,5cm}|p{7,5cm}| } + +\hline + +Chapter&Content\\ + +\hline + + [0. Preface] & [Purpose], [General principles], [Terminology], [Exceptions] \\ + + [1. Naming] & [Identifiers], [Package names], [Classes, enumeration and interfaces], [Functions], [Constants], [Variables] \\ + + [2. Docs] & [Kdoc], [File header], [Comments on function header ], [Code comments] \\ + + [3. General formatting] & [File-related rules], [Braces], [Indentation], [Empty blocks], [Line length], [Line breaks (newlines)], [Blank lines], [Horizontal space], [Enumerations], [Variable declaration], [When expression], [Annotations], [Layout of comments], [Modifiers and constant values], [Strings]\\ + + [4. Variables and types] & [Variables], [Types], [Null safety and variable declarations]\\ + + [5. Functions] & [Function design], [Function arguments]\\ + + [6. Classes] & [Classes], [Extension functions], [Interfaces], [Objects] \\ + + [7. Kotlin \& Java] & \\ + +\hline + +\end{tabular} + +\end{center} + + + + + \section*{\textbf{Preface}} \subsection*{\textbf{Purpose of this document}} @@ -52,7 +101,7 @@ \subsection*{\textbf{General principles}} 2. Simplicity — a code is easy to understand and implement. -3. Consistency — enables a code to be easily modified, reviewed and understood by the team members. Unification is particularly important when the same team works on the same project, utilizing similar styles.enables code to be easily modified, reviewed and understood by the team members. +3. Consistency — enables a code to be easily modified, reviewed, and understood by the team members. Unification is particularly important when the same team works on the same project, utilizing similar styles enabling a code to be easily modified, reviewed, and understood by the team members. @@ -68,9 +117,9 @@ \subsection*{\textbf{General principles}} Both of these paradigms are trusted and well-known software engineering practices. - As a young programming language, Kotlin is built on the top of well-established languages such as Java, C++, C\#, and Scala. + As a young programming language, Kotlin is built on top of well-established languages such as Java, C++, C\#, and Scala. - This enables Kotlin to introduce many features that help you write cleaner, more readable code, while also reducing the number of complex code structures. For example, type and null safety, extension functions, infix syntax, immutability, val/var differentiation, expression-oriented features, when statements, much easier work with collections, type auto conversion, and other syntactic sugar. + This enables Kotlin to introduce many features that help a developer write cleaner, more readable code while also reducing the number of complex code structures. For example, type and null safety, extension functions, infix syntax, immutability, val/var differentiation, expression-oriented features, "when" statements, much easier work with collections, type auto conversion, and other syntactic sugar. @@ -126,7 +175,7 @@ \subsection*{\textbf{Exceptions}} Even though exceptions may exist, it is essential to understand why rules and recommendations are needed. -Depending on your project situation or personal habits, you can break some of the rules. However, remember that one exception may lead to many and eventually can destroy code consistency. As such, there should be very few exceptions. +Depending on a project situation or personal habits, you can break some of the rules. However, remember that one exception may lead to many and eventually can destroy code consistency. As such, there should be very few exceptions. When modifying open-source code or third-party code, you can choose to use the code style from this open-source project (instead of using the existing specifications) to maintain consistency. @@ -134,7 +183,7 @@ \subsection*{\textbf{Exceptions}} \section*{\textbf{1. Naming}} -In programming, it is not always easy to meaningfully and appropriately name variables, functions, classes, etc. Using meaningful names helps you clearly express your code's main ideas and functionality and avoid misinterpretation, unnecessary coding and decoding, "magic" numbers, and inappropriate abbreviations. +In programming, it is not always easy to meaningfully and appropriately name variables, functions, classes, etc. Using meaningful names helps to clearly express your code's main ideas and functionality and avoid misinterpretation, unnecessary coding and decoding, "magic" numbers, and inappropriate abbreviations. @@ -144,7 +193,7 @@ \section*{\textbf{1. Naming}} \subsection*{\textbf{1.1 Identifier names}} -\subsubsection*{\textbf{1.1.1}} +\subsubsection*{\textbf{Rule 1.1.1}} \leavevmode\newline @@ -159,7 +208,7 @@ \subsubsection*{\textbf{1.1.1}} Name lengths of less than 31 characters are generally recommended. However, this depends on the project. Otherwise, a class declaration with generics or inheritance from a superclass can cause line breaking. -No special prefix or suffix should be used in the names. The following examples are inappropriate: name\_, mName, s\_name, and kName. +No special prefix or suffix should be used in names. The following examples are inappropriate names: name\_, mName, s\_name, and kName. @@ -249,7 +298,7 @@ \subsubsection*{\textbf{1.1.1}} \end{center} -\textbf{Exceptions} +\textbf{Exceptions:} - The i,j,k variables used in loops are part of the industry standard. One symbol can be used for such variables. @@ -296,7 +345,7 @@ \subsubsection*{\textbf{Rule 1.2.1}} Each file should have a `package` directive. -Package names are all written in lowercase, and consecutive words are concatenated together (no underscores). Package names should contain both the product and module names, and the department (or team) name to prevent conflicts with other teams. Numbers are not permitted. For example: `org.apache.commons.lang3`, `xxx.yyy.v2`. +Package names are all written in lowercase, and consecutive words are concatenated together (no underscores). Package names should contain both the product or module names and the department (or team) name to prevent conflicts with other teams. Numbers are not permitted. For example: `org.apache.commons.lang3`, `xxx.yyy.v2`. @@ -306,7 +355,7 @@ \subsubsection*{\textbf{Rule 1.2.1}} - In certain cases, such as open-source projects or commercial cooperation, package names should not start with `your.company.domain.` -- If the package name starts with a number or other characters that cannot be used at the beginning of the Java/Kotlin package name, then underscores are allowed. For example: `com.example._123name`. +- If the package name starts with a number or other character that cannot be used at the beginning of the Java/Kotlin package name, then underscores are allowed. For example: `com.example._123name`. - Underscores are sometimes permitted if the package name contains reserved Java/Kotlin keywords, such as `org.example.hyphenated_name`, `int_.example`. @@ -369,7 +418,7 @@ \subsubsection*{\textbf{Rule 1.4.1}} For example: `sendMessage`, `stopProcess`, or `calculateValue`. -To name functions use the following formatting rules: +To name functions, use the following formatting rules: @@ -449,18 +498,18 @@ \subsubsection*{\textbf{Rule 1.5.1 Constant names should be in UPPER case}} -1. Constants are attributes created with the const keyword, or top-level/`val` local variables of an object that holds immutable data. In most cases, constants can be identified as a `const val` property from the `object`/`companion object`/file top level. These variables contain a fixed constant value that typically should never be changed by programmers. This includes basic types, strings, immutable types, and immutable collections of immutable types. If an object state can be changed, the value is not a constant. - +2. Constant names should contain only uppercase letters separated by underscores. They should have a `val` or `const val` (`const` should be used only with primitive types) modifier to make them final (immutable) explicitly. In most cases, if you need to specify a constant value, then you need to create it with the `const val` modifier. Note that not all `val` variables are constants. -2. Constant names should contain only uppercase letters separated by underscores. They should have a val or const val modifier to explicitly make them final. In most cases, if you need to specify a constant value, then you need to create it with the "const val" modifier. Note that not all `val` variables are constants. -3. Objects that have immutable content, such as `Logger` and `Lock`, can be in uppercase as constants or have camel case as regular variables. +3. Objects with immutable content, such as `Logger` and `Lock`, can be in uppercase as constants or have camel case as regular variables. 4. Use meaningful constants instead of `magic numbers`. SQL or logging strings should not be treated as magic numbers, nor should they be defined as string constants. + + Magic constants like `NUM_FIVE = 5` or `NUM_5 = 5` should not be treated as constants. This is because mistakes will easily be made if they are changed to `NUM_5 = 50` or 55. These constants typically represent business logic values, such as measures, capacity, scope, location, tax rate, promotional discounts, and power base multiples in algorithms. @@ -469,7 +518,7 @@ \subsubsection*{\textbf{Rule 1.5.1 Constant names should be in UPPER case}} - Using library functions and APIs. For example, instead of checking that `size == 0`, use `isEmpty()` function. To work with `time`, use built-ins from `java.time API`. -- Enumerations can be used to name patterns. Refer to [Recommended usage scenario for enumeration in 3.9] +- Enumerations can be used to name patterns. Refer to [Recommended usage scenario for enumeration in 3.9]. @@ -500,7 +549,7 @@ \subsubsection*{\textbf{Rule 1.6.1}} Non-constant field names should use camel case and start with a lowercase letter. -A local variable cannot be treated as a constant even if it is final and immutable. Therefore, it should not use the preceding rules. Names of collection type variables (sets, lists, etc.) should contain plural nouns. +A local variable cannot be treated as constant even if it is final and immutable. Therefore, it should not use the preceding rules. Names of collection type variables (sets, lists, etc.) should contain plural nouns. For example: `var namesList: List` @@ -532,7 +581,7 @@ \subsubsection*{\textbf{Rule 1.6.2}} -Avoid using Boolean variable names with negative meaning. When using a logical operator and name with negative meaning, the code may be difficult to understand, which is referred to as the "double negative". +Avoid using Boolean variable names with a negative meaning. When using a logical operator and name with negative meaning, the code may be difficult to understand, which is referred to as the "double negative". For instance, it is not easy to understand the meaning of !isNotError. @@ -622,19 +671,53 @@ \subsubsection*{\textbf{Rule 2.1.1}} -At a minimum, KDoc should be used for every public, protected, or internal decorated class, interface, enumeration, method, and member field (property). Other code blocks can also have KDocs if needed. +At a minimum, KDoc should be used for every public, protected, or internal decorated class, interface, enumeration, method, and member field (property). + +Other code blocks can also have KDocs if needed. + +Instead of using comments or KDocs before properties in the primary constructor of a class - use `@property` tag in a KDoc of a class. + +All properties of the primary constructor should also be documented in a KDoc with a `@property` tag. + + + +\textbf{Incorrect example:} + +\begin{lstlisting}[language=Kotlin] +/** + * Class description + */ +class Example( + /** + * property description + */ + val foo: Foo, + // another property description + val bar: Bar +) +\end{lstlisting} -Instead of using comments before properties in class - use `@property` tag in a KDoc of a class. -All properties of the primary constructor should be also documented in a KDoc with a `@property` tag. +\textbf{Correct example:} +\begin{lstlisting}[language=Kotlin] +/** + * Class description + * @property foo property description + * @property bar another property description + */ +class Example( + val foo: Foo, + val bar: Bar +) +\end{lstlisting} \textbf{Exceptions:} -1. For setters/getters of properties, obvious comments (like `this getter returns field`) are optional. Note, that Kotlin generates simple `get/set` methods under the hood. +1. For setters/getters of properties, obvious comments (like `this getter returns field`) are optional. Note that Kotlin generates simple `get/set` methods under the hood. @@ -657,11 +740,6 @@ \subsubsection*{\textbf{Rule 2.1.1}} Note: You can skip KDocs for a method's override if it is almost the same as the superclass method. -\subsubsection*{\textbf{Rule 2.1.2}} -\leavevmode\newline - -When the method has arguments, return value, or can throw exceptions, it must be described in the KDoc block: with @param, @return, @throws - \subsubsection*{\textbf{Rule 2.1.2}} @@ -726,7 +804,7 @@ \subsubsection*{\textbf{Rule 2.1.3}} - One empty line, followed by regular `@param`, `@return`, `@throws`, and other comments. -- The conventional standard "block labels" arranged in the following order: `@param`, `@return`, `@throws`. +- The conventional standard "block labels" are arranged in the following order: `@param`, `@return`, `@throws`. Kdoc should not contain: @@ -738,17 +816,21 @@ \subsubsection*{\textbf{Rule 2.1.3}} -If a tag block cannot be described in one line, you should indent the content of the new line by `four spaces` from the `@` position to achieve alignment (`@` counts as one + three spaces). +If a tag block cannot be described in one line, indent the content of the new line by \textit{four spaces} from the `@` position to achieve alignment (`@` counts as one + three spaces). + + + +\textbf{Exception:} -\textbf{Exception:} When the descriptive text in a tag block is too long to wrap, you can indent the alignment with the descriptive text in the last line. The descriptive text of multiple tags does not need to be aligned. +When the descriptive text in a tag block is too long to wrap, you can indent the alignment with the descriptive text in the last line. The descriptive text of multiple tags does not need to be aligned. See [3.8 Horizontal space]. -In Kotlin, compared to Java, you are able to put several classes inside one file, so each class should have a Kdoc formatted comment (as stated in rule 2.1). +In Kotlin, compared to Java, you can put several classes inside one file, so each class should have a Kdoc formatted comment (as stated in rule 2.1). This comment should contain @since tag. The right style is to write the application version when its functionality is released. It should be entered after the `@since` tag. @@ -767,7 +849,7 @@ \subsubsection*{\textbf{Rule 2.1.3}} \end{lstlisting} -Other KDoc tags (such as @param type parameters and @see.) can be added as follow: +Other KDoc tags (such as @param type parameters and @see.) can be added as follows: \begin{lstlisting}[language=Kotlin] /** @@ -785,7 +867,7 @@ \subsubsection*{\textbf{Rule 2.2.1}} -Comments on the file header should be placed before the package name and imports. If you need to add more content to the comment, you can subsequently add it in the same format. +Comments on the file header should be placed before the package name and imports. If you need to add more content to the comment, subsequently add it in the same format. @@ -807,7 +889,7 @@ \subsubsection*{\textbf{Rule 2.2.1}} -- The \textbf{copyright statement} can use your company's subsidiaries. For example: \ +- The \textbf{copyright statement} can use your company's subsidiaries, as shown in the below examples: \ Chinese version: `版权所有 (c) 海思半导体 2012-2020` \ @@ -832,11 +914,11 @@ \subsubsection*{\textbf{Rule 2.2.1}} - File header comments must start from the top of the file. If it is a top-level file comment, there should be a blank line after the last Kdoc `*/` symbol. If it is a comment for a top-level class, the class declaration should start immediately without using a newline. -- Maintain a unified format. The specific format can be formulated by the project (for example, if you use existing opensource project), and you need to follow it. +- Maintain a unified format. The specific format can be formulated by the project (for example, if you use an existing opensource project), and you need to follow it. - A top-level file-Kdoc must include a copyright and functional description, especially if there is more than one top-level class. -- Do not include empty comment blocks.If there is no content after the option `@apiNote`, the entire tag block should be deleted. +- Do not include empty comment blocks. If there is no content after the option `@apiNote`, the entire tag block should be deleted. - The industry practice is not to include historical information in comments. The corresponding history can be found in VCS (git, svn, etc.). Therefore, it is not recommended to include historical data in the comments of the Kotlin source code. @@ -872,9 +954,9 @@ \subsubsection*{\textbf{Rule 2.4.1}} - There must be one space between the comment character and the content of the comment -- There must be a newline between a Kdoc and the pressiding code +- There must be a newline between a Kdoc and presiding code -- An empty line should not exist between a Kdoc and the code it is describing. You do not need to add a blank line before the first comment in a particular name space (code block) (for example, between the function declaration and first comment in a function body). +- An empty line should not exist between a Kdoc and the code it is describing. You do not need to add a blank line before the first comment in a particular namespace (code block) (for example, between the function declaration and first comment in a function body). @@ -921,7 +1003,7 @@ \subsubsection*{\textbf{Rule 2.4.1}} - Leave one single space between the comment on the right side of the code and the code. -If you use conditional comments in the `if-else-if` scenario, put the comments inside the `else-if` branch or in the conditional block, but not before the `else-if`. This makes your code more understandable. +If you use conditional comments in the `if-else-if` scenario, put the comments inside the `else-if` branch or in the conditional block, but not before the `else-if`. This makes the code more understandable. When the if-block is used with curly braces, the comment should be placed on the next line after opening the curly braces. @@ -956,7 +1038,7 @@ \subsubsection*{\textbf{Rule 2.4.1}} \end{lstlisting} -- Start all comments (including KDoc) with a space after the first symbol (`//`, `/*`, `/**` and `*`) +- Start all comments (including KDoc) with space after the first symbol (`//`, `/*`, `/**` and `*`) @@ -974,11 +1056,11 @@ \subsubsection*{\textbf{Rule 2.4.2}} A code is not used to store history. Git, svn, or other VCS tools should be used for this purpose. -Unused imports increase the coupling of the code and are not conducive to maintenance. The commented out code cannot be properly maintained. +Unused imports increase the coupling of the code and are not conducive to maintenance. The commented out code cannot be appropriately maintained. -When you attempt to reuse the code, there is a high probability that you will introduce defects that are easily missed. +In an attempt to reuse the code, there is a high probability that you will introduce defects that are easily missed. -The correct approach is to delete the unnecessary code directly and immediately when it is not used. +The correct approach is to delete the unnecessary code directly and immediately when it is not used anymore. If you need the code again, consider porting or rewriting it as changes could have occurred since you first commented on the code. @@ -995,7 +1077,7 @@ \subsubsection*{\textbf{Recommendation 2.4.3}} -\textbf{For example}: +\textbf{Example}: \begin{lstlisting}[language=Kotlin] // TODO(): Jira-XXX - support new json format @@ -1027,6 +1109,8 @@ \subsubsection*{\textbf{Rule 3.1.2}} A source file contains code blocks in the following order: copyright, package name, imports, and top-level classes. They should be separated by one blank line. + + a) Code blocks should be in the following order: 1. Kdoc for licensed or copyrighted files @@ -1051,7 +1135,7 @@ \subsubsection*{\textbf{Rule 3.1.2}} -d) \textbf{Recommendation}: One `.kt` source file should contain only one class declaration, and its name should match the filename +d) \textbf{Recommendation}. One `.kt` source file should contain only one class declaration, and its name should match the filename @@ -1108,11 +1192,11 @@ \subsubsection*{\textbf{Recommendation 3.1.4}} The declaration parts of class-like code structures (class, interface, etc.) should be in the following order: compile-time constants (for objects), class properties, late-init class properties, init-blocks, constructors, public methods, internal methods, protected methods, private methods, and companion object. Blank lines should separate their declaration. -Notes: -1. There should be no blank lines between properties. -\textbf{Exceptions}: When there is a comment before a property on a separate line or annotations on a separate line. +Notes: + +1. There should be no blank lines between properties with the following \textbf{exceptions}: when there is a comment before a property on a separate line or annotations on a separate line. 2. Properties with comments/Kdoc should be separated by a newline before the comment/Kdoc. @@ -1215,9 +1299,9 @@ \subsubsection*{\textbf{Rule 3.2.2 For}} - The closing brace is on its own new line. -- The closing brace can be followed by a newline. The only exceptions are `else`, `finally`, and `while` (from `do-while` statement), or `catch` keywords. +- The closing brace can be followed by a newline character. The only exceptions are `else`, `finally`, and `while` (from `do-while` statement), or `catch` keywords. -These keywords should not be split from the closing brace by a newline. +These keywords should not be split from the closing brace by a newline character. @@ -1225,7 +1309,7 @@ \subsubsection*{\textbf{Rule 3.2.2 For}} -1) For lambdas, there is no need to put a newline after the first (function-related) opening brace. A newline should appear only after an arrow (`->`) (see [point 5 of Rule 3.6.2]. +1) For lambdas, there is no need to put a newline character after the first (function-related) opening brace. A newline character should appear only after an arrow (`->`) (see [point 5 of Rule 3.6.2]). @@ -1289,7 +1373,7 @@ \subsubsection*{\textbf{Rule 3.3.1}} Only spaces are permitted for indentation, and each indentation should equal `four spaces` (tabs are not permitted). -If you prefer using tabs, simply configure them to automatically change to spaces in your IDE. +If you prefer using tabs, simply configure them to change to spaces in your IDE automatically. These code blocks should be indented if they are placed on the new line, and the following conditions are met: @@ -1355,7 +1439,7 @@ \subsubsection*{\textbf{Rule 3.3.1}} \textbf{Exceptions}: -- When breaking parameter list of a method/class constructor it can be aligned with `8 spaces`. A parameter that was moved to a new line can be on the same level as the previous argument: +- When breaking the parameter list of a method/class constructor, it can be aligned with `8 spaces`. A parameter that was moved to a new line can be on the same level as the previous argument: @@ -1380,7 +1464,7 @@ \subsubsection*{\textbf{Rule 3.3.1}} \end{lstlisting} -- A list of supertypes should be indented with `4 spaces` if they are on different lines, or with `8 spaces` if the leading colon is also on a separate line +- A list of supertypes should be indented with `4 spaces` if they are on different lines or with `8 spaces` if the leading colon is also on a separate line @@ -1415,7 +1499,7 @@ \subsubsection*{\textbf{Recommendation 3.4.1}} \end{lstlisting} -\textbf{Valid examples} (but note once again, that generally empty blocks are prohibited): +\textbf{Valid examples} (note once again that generally empty blocks are prohibited): @@ -1455,7 +1539,7 @@ \subsubsection*{\textbf{Recommendation 3.5.1}} The international code style prohibits `non-Latin` (`non-ASCII`) symbols. -(See [Rule 1.1.1: Identifiers] However, if you still intend on using them, follow the following convention: +(See [Rule 1.1.1: Identifiers]) However, if you still intend on using them, follow the following convention: @@ -1518,15 +1602,15 @@ \subsubsection*{\textbf{Rule 3.6.2}} -1) Unlike Java, Kotlin allows you not to put a semicolon (`;`) after each statement separated by a newline. +1) Unlike Java, Kotlin allows you not to put a semicolon (`;`) after each statement separated by a newline character. There should be no redundant semicolon at the end of the lines. -When a newline is needed to split the line, it should be placed after operators like `\&\&`/`||`/`+`/etc. and all infix functions (for example, `xor`). +When a newline character is needed to split the line, it should be placed after such operators as `\&\&`/`||`/`+`/etc. and all infix functions (for example, `xor`). -However, the newline should be placed before operators such as `.`, `?.`, `?:`, and `::`. +However, the newline character should be placed before operators such as `.`, `?.`, `?:`, and `::`. @@ -1587,7 +1671,7 @@ \subsubsection*{\textbf{Rule 3.6.2}} 5) If a lambda statement contains more than one line in its body, a newline should be placed after an arrow if the lambda statement has explicit parameters. - If it uses an implicit parameter (`it`), the newline should be placed after the opening brace (`{`). + If it uses an implicit parameter (`it`), the newline character should be placed after the opening brace (`{`). The following examples illustrate this rule: @@ -1705,7 +1789,7 @@ \subsubsection*{\textbf{Recommendation 3.7.1}} By reducing unnecessary blank lines, you can display more code on one screen, which improves code readability. -- Blank lines should separate content based on relevance and should be placed between groups of fields, constructors, methods, nested classes, `init` blocks, and objects (see [Rule 3.1.2]. +- Blank lines should separate content based on relevance and should be placed between groups of fields, constructors, methods, nested classes, `init` blocks, and objects (see [Rule 3.1.2]). - Do not use more than one line inside methods, type definitions, and initialization expressions. @@ -1794,7 +1878,7 @@ \subsubsection*{\textbf{Rule 3.8.1}} 5. Use spaces after (`,`), (`:`), and (`;`), except when the symbol is at the end of the line. - However, note that this code style prohibits the use of (`;`) in the middle of a line ([Rule 3.2.2]. + However, note that this code style prohibits the use of (`;`) in the middle of a line ([Rule 3.2.2]). There should be no whitespaces at the end of a line. @@ -1806,7 +1890,7 @@ \subsubsection*{\textbf{Rule 3.8.1}} - - when `:` is used to separate a type and a super type, including an anonymous object (after object keyword) + - when `:` is used to separate a type and a supertype, including an anonymous object (after object keyword) - when delegating to a superclass constructor or different constructor of the same class @@ -1825,7 +1909,7 @@ \subsubsection*{\textbf{Rule 3.8.1}} \end{lstlisting} -6. There should be \textit{only one space} between the identifier and it's type: `list: List` +6. There should be \textit{only one space} between the identifier and its type: `list: List` If the type is nullable, there should be no space before `?`. @@ -1853,7 +1937,7 @@ \subsubsection*{\textbf{Rule 3.8.1}} -10. There should be no spaces between prefix/postfix operator (like `!!` or `++`), and it's an operand. +10. There should be no spaces between a prefix/postfix operator (like `!!` or `++`) and its operand. @@ -1870,7 +1954,7 @@ \subsubsection*{\textbf{Recommendation 3.8.2}} - Long identifier names will break the alignment and lead to less presentable code. -- Alignment possesses more disadvantages than advantages. To reduce maintenance costs, misalignment is the best choice. +- There are more disadvantages than advantages in alignment. To reduce maintenance costs, the best choice is not to use horizontal alignment. @@ -1992,7 +2076,7 @@ \subsubsection*{\textbf{Recommendation 3.10.2}} Local variables are usually initialized during their declaration or immediately after. -The member fields of the class should be declared collectively (see [Rule 3.1.2]. +The member fields of the class should be declared collectively (see [Rule 3.1.2] for details on the class structure). @@ -2018,7 +2102,7 @@ \subsubsection*{\textbf{Recommendation 3.12.1}} -1. Annotations applied to the class, method or constructor are placed on separate lines (one annotation per line). +1. Annotations applied to the class, method, or constructor are placed on separate lines (one annotation per line). @@ -2138,7 +2222,7 @@ \subsubsection*{\textbf{Rule 3.15.1}} [String templates](https://kotlinlang.org/docs/reference/basic-types.html\#string-templates), [Raw strings](https://kotlinlang.org/docs/reference/basic-types.html\#string-literals) -As such, compared to using explicit concatenation, code looks much better when proper Kotlin strings are used for short lines and you do not need to split them with newlines. +Therefore, compared to using explicit concatenation, code looks much better when proper Kotlin strings are used for short lines, and you do not need to split them with newline characters. @@ -2185,7 +2269,7 @@ \subsubsection*{\textbf{Rule 3.15.2}} -In case string template contains only one variable - there is no need to use string template. Use this variable directly. +In case a string template contains only one variable - there is no need to use the string template. Use this variable directly. @@ -2232,7 +2316,7 @@ \subsubsection*{\textbf{Rule 4.1.1}} -\textbf{Invalid example:} \ +\textbf{Invalid example}: \ Float values containing more than six or seven decimal numbers will be rounded. @@ -2241,7 +2325,7 @@ \subsubsection*{\textbf{Rule 4.1.1}} \end{lstlisting} -\textbf{Valid example} (when precise calculations are needed): +\textbf{Valid example}: (when precise calculations are needed): \begin{lstlisting}[language=Kotlin] val income = BigDecimal("2.0") @@ -2337,14 +2421,12 @@ \subsubsection*{\textbf{Recommendation 4.2.1}} \end{lstlisting} -Also Kotlin 1.3 introduced [Contracts](https://kotlinlang.org/docs/reference/whatsnew13.html\#contracts) that provide enhanced logic for smart-cast. +Also, Kotlin 1.3 introduced [Contracts](https://kotlinlang.org/docs/reference/whatsnew13.html\#contracts) that provide enhanced logic for smart-cast. -Contracts are used and are very stable in `stdlib`. +Contracts are used and are very stable in `stdlib`, for example: -For example: - \begin{lstlisting}[language=Kotlin] @@ -2428,7 +2510,7 @@ \subsection*{\textbf{4.3 Null safety and variable declarations}} \subsubsection*{\textbf{Recommendation 4.3.1}} \leavevmode\newline -To avoid `NullPointerException` and help compiler to prevent Null Poniter Exceptions, avoid using nullable types (with `?` symbol). +To avoid `NullPointerException` and help the compiler prevent Null Pointer Exceptions, avoid using nullable types (with `?` symbol). @@ -2446,11 +2528,11 @@ \subsubsection*{\textbf{Recommendation 4.3.1}} \end{lstlisting} -Nevertheless, if you use Java libraries extensively, you will have to use nullable types and enrich your code with `!!` and `?` symbols. +Nevertheless, when using Java libraries extensively, you have to use nullable types and enrich the code with `!!` and `?` symbols. Avoid using nullable types for Kotlin stdlib (declared in [official documentation](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/)). -Try to use initializers for empty collections. For example, if you want to initialize a list instead of `null` use `emptyList()`. +Try to use initializers for empty collections. For example, if you want to initialize a list instead of `null`, use `emptyList()`. @@ -2498,13 +2580,126 @@ \subsubsection*{\textbf{Recommendation 4.3.2}} \begin{lstlisting}[language=Kotlin] val myVariable: Map = emptyMap() \end{lstlisting} + + +\subsubsection*{\textbf{Null-safety}} +\leavevmode\newline + +\subsubsection*{\textbf{4.3.3 Explicit null checks}} +\leavevmode\newline + + + +Try to avoid explicit null checks (explicit comparison with `null`) + +Kotlin is declared as [Null-safe](https://kotlinlang.org/docs/reference/null-safety.html) language. + +However, Kotlin architects wanted Kotlin to be fully compatible with Java; that's why the `null` keyword was also introduced in Kotlin. + + + +There are several code-structures that can be used in Kotlin to avoid null-checks. For example: `?:`, `.let {}`, `.also {}`, e.t.c + + + +\textbf{Invalid example:} + +\begin{lstlisting}[language=Kotlin] +// example 1 +var myVar: Int? = null +if (myVar == null) { + println("null") + return +} + +// example 2 +if (myVar != null) { + println("not null") + return +} + +// example 3 +val anotherVal = if (myVar != null) { + println("not null") + 1 + } else { + 2 + } +// example 4 +if (myVar == null) { + println("null") +} else { + println("not null") +} +\end{lstlisting} + + +\textbf{Valid example:} + +\begin{lstlisting}[language=Kotlin] +// example 1 +var myVar: Int? = null +myVar?: run { + println("null") + return +} + +// example 2 +myVar?.let { + println("not null") + return +} + +// example 3 +val anotherVal = myVar?.also { + println("not null") + 1 + } ?: 2 + +// example 4 +myVar?.let { + println("null") +} ?: run { println("not null") } +\end{lstlisting} + + +\textbf{Exceptions:} + + + +In the case of complex expressions, such as multiple `else-if` structures or long conditional statements, there is common sense to use explicit comparison with `null`. + + + +\textbf{Valid examples:} + + + +\begin{lstlisting}[language=Kotlin] +if (myVar != null) { + println("not null") +} else if (anotherCondition) { + println("Other condition") +} +\end{lstlisting} + + +\begin{lstlisting}[language=Kotlin] +if (myVar == null || otherValue == 5 && isValid) {} +\end{lstlisting} + + +Please also note, that instead of using `require(a != null)` with a not null check - you should use a special Kotlin function called `requireNotNull(a)`. + + + \section*{\textbf{5. Functions}} \subsection*{\textbf{5.1 Function design}} -You can write clean code by gaining knowledge of how to build design patterns and avoid code smells. +Developers can write clean code by gaining knowledge of how to build design patterns and avoid code smells. -You should utilize this approach, along with functional style, when you write Kotlin code. +You should utilize this approach, along with functional style, when writing Kotlin code. The concepts behind functional style are as follows: @@ -2514,9 +2709,9 @@ \subsection*{\textbf{5.1 Function design}} The code in functions should be simple and not conceal the author's original intentions. -Additionally, it should have a clean abstraction, and control statements should be used in a straightforward manner. +Additionally, it should have a clean abstraction, and control statements should be used straightforwardly. -The side effects (code that does not affect a function's return value, but affects global/object instance variables) should not be used for state changes of an object. +The side effects (code that does not affect a function's return value but affects global/object instance variables) should not be used for state changes of an object. The only exceptions to this are state machines. @@ -2524,11 +2719,11 @@ \subsection*{\textbf{5.1 Function design}} Kotlin is [designed](https://www.slideshare.net/abreslav/whos-more-functional-kotlin-groovy-scala-or-java) to support and encourage functional programming, featuring the corresponding built-in mechanisms. -In addition, standard collections and sequences feature methods that enable functional programming (for example, `apply`, `with`, `let`, and `run`), Kotlin Higher-Order functions, function types, lambdas, and default function arguments. +Also, it supports standard collections and sequences feature methods that enable functional programming (for example, `apply`, `with`, `let`, and `run`), Kotlin Higher-Order functions, function types, lambdas, and default function arguments (???). As [previously discussed], Kotlin supports and encourages the use of immutable types, which in turn motivates programmers to write pure functions that avoid side effects and have a corresponding output for specific input. -The pipeline data flow for the pure function comprises a functional paradigm. It is easy to implement concurrent programming when you have chains of function calls, and each step features the following characteristics: +The pipeline data flow for the pure function comprises a functional paradigm. It is easy to implement concurrent programming when you have chains of function calls, where each step features the following characteristics: 1. Simplicity @@ -2557,7 +2752,7 @@ \subsubsection*{\textbf{Rule 5.1.1}} The function should be displayable on one screen and only implement one certain logic. -If a function is too long, it often means that it is complex and be split or made more primitive. Functions should consist of 30 lines (non-empty and non-comment) in total. +If a function is too long, it often means complex and could be split or simplified. Functions should consist of 30 lines (non-empty and non-comment) in total. @@ -2569,7 +2764,7 @@ \subsubsection*{\textbf{Rule 5.1.1}} Even if a long function works well, new problems or bugs may appear due to the function's complex logic once it is modified by someone else. -Therefore, it is recommended that you split such functions into several separate and shorter functions that are easier to manage. +Therefore, it is recommended to split such functions into several separate and shorter functions that are easier to manage. This approach will enable other programmers to read and modify the code properly. @@ -2582,11 +2777,11 @@ \subsubsection*{\textbf{Rule 5.1.2}} Each nesting level will increase the amount of effort needed to read the code because you need to remember the current "stack" (for example, entering conditional statements and loops). -\textbf{Exception:} The nesting levels of the lambda expressions, local classes, and anonymous classes in functions are calculated based on the innermost function wheres the nesting levels of enclosing methods are not accumulated. +\textbf{Exception:} The nesting levels of the lambda expressions, local classes, and anonymous classes in functions are calculated based on the innermost function. The nesting levels of enclosing methods are not accumulated. Functional decomposition should be implemented to avoid confusion for the developer who reads the code. -This will help the reader switch between context. +This will help the reader switch between contexts. @@ -2595,7 +2790,7 @@ \subsubsection*{\textbf{Rule 5.1.3}} Nested functions create a more complex function context, thereby confusing readers. -With nested functions the visibility context may not be evident to the code reader. +With nested functions, the visibility context may not be evident to the code reader. @@ -2618,7 +2813,7 @@ \subsubsection*{\textbf{Rule 5.2.1}} -With such notation, it is easier to use curly brackets, which in turn leads to better code readability. +With such notation, it is easier to use curly brackets, leading to better code readability. @@ -2644,7 +2839,7 @@ \subsubsection*{\textbf{Rule 5.2.2}} A long argument list is a [code smell](https://en.wikipedia.org/wiki/Code\_smell) that leads to less reliable code. -It is recommended that you reduce the number of parameters. Having \textbf{more than five} parameters leads to difficulties in maintenance and conflicts merging. +It is recommended to reduce the number of parameters. Having \textbf{more than five} parameters leads to difficulties in maintenance and conflicts merging. If parameter groups appear in different functions multiple times, these parameters are closely related and can be encapsulated into a single Data Class. @@ -2655,7 +2850,7 @@ \subsubsection*{\textbf{Rule 5.2.2}} \subsubsection*{\textbf{Rule 5.2.3 Use default values for function arguments instead of overloading them}} \leavevmode\newline -In Java, default values for function arguments are prohibited. That is why when you need to create a function with fewer arguments, the function should be overloaded. +In Java, default values for function arguments are prohibited. That is why the function should be overloaded when you need to create a function with fewer arguments. In Kotlin, you can use default arguments instead. @@ -2688,7 +2883,7 @@ \subsection*{\textbf{6.1 Classes}} \subsubsection*{\textbf{Rule 6.1.1}} \leavevmode\newline -In case class contains only one explicit constructor - it should be converted to a primary constructor. +In case the class contains only one explicit constructor - it should be converted to a primary constructor. @@ -2711,7 +2906,7 @@ \subsubsection*{\textbf{Rule 6.1.1}} // ... } -// in case of any annotations or modifiers used on constructor: +// in case of any annotations or modifiers used on a constructor: class Test private constructor(var a: Int) { // ... } @@ -2721,7 +2916,7 @@ \subsubsection*{\textbf{Rule 6.1.1}} \subsubsection*{\textbf{Rule 6.1.2}} \leavevmode\newline -Some people say that the data class is a code smell. But if you need to use it, and as a result, your code is becoming more simple, you can use Kotlin `data class`. The main purpose of this class is to hold data, +Some people say that the data class is a code smell. However, if you need to use it (which makes your code more simple), you can utilize the Kotlin `data class`. The main purpose of this class is to hold data, but also `data class` will automatically generate several useful methods: @@ -2774,18 +2969,18 @@ \subsubsection*{\textbf{Rule 6.1.2}} \end{lstlisting} -\textbf{Exception \#1}: Note, that data classes cannot be abstract, open, sealed or inner, that's why these types of classes cannot be changed to a data class. +\textbf{Exception 1}: Note that data classes cannot be abstract, open, sealed, or inner; that is why these types of classes cannot be changed to a data class. -\textbf{Exception \#2}: No need to convert a class to data class if this class extends some other class or implements an interface. +\textbf{Exception 2}: No need to convert a class to a data class if this class extends some other class or implements an interface. \subsubsection*{\textbf{Rule 6.1.3}} \leavevmode\newline -The primary constructor is a part of the class header; it goes after the class name and (optional) type parameters but can be omitted if it is useless. +The primary constructor is a part of the class header; it is placed after the class name and type parameters (optional) but can be omitted if it is not used. @@ -2798,7 +2993,7 @@ \subsubsection*{\textbf{Rule 6.1.3}} var b: Int = 0 } -// empty primary constructor is not needed here also +// empty primary constructor is not needed here // it can be replaced with a primary contructor with one argument or removed class Test() { var a = "Property" @@ -2817,7 +3012,7 @@ \subsubsection*{\textbf{Rule 6.1.3}} \textbf{Valid example}: \begin{lstlisting}[language=Kotlin] -// the good example here is a data class, but this example shows that you should get rid of braces for primary constructor +// the good example here is a data class; this example also shows that you should get rid of braces for the primary constructor class Test { var a: Int = 0 var b: Int = 0 @@ -2828,17 +3023,15 @@ \subsubsection*{\textbf{Rule 6.1.3}} \subsubsection*{\textbf{Rule 6.1.4}} \leavevmode\newline -The primary constructor cannot contain any code. That's why Kotlin has introduced `init` blocks. +The primary constructor cannot contain any code. That is why Kotlin has introduced `init` blocks. -These blocks are used to store the code that should be run during the initialization of the class. +These blocks store the code to be run during the class initialization. -Kotlin allows writing multiple initialization blocks that are executed in the same order as they appear in the class body. +Kotlin allows writing multiple initialization blocks executed in the same order as they appear in the class body. Even when you follow (rule 3.2)[\#r3.2], this makes your code less readable as the programmer needs to keep in mind all init blocks and trace the execution of the code. -So in your code, you should try to use a single `init` block to reduce the complexity. In case you need to do some logging or make some calculations before the assignment - -of some class property, you can use powerful functional programming. This will reduce the possibility of the error if your `init` blocks' order is accidentally changed and +Therefore, you should try to use a single `init` block to reduce the code's complexity. . If you need to do some logging or make some calculations before the class property assignment, you can use powerful functional programming. This will reduce the possibility of the error if your `init` blocks' order is accidentally changed and make the code logic more coupled. It is always enough to use one `init` block to implement your idea in Kotlin. @@ -2879,7 +3072,7 @@ \subsubsection*{\textbf{Rule 6.1.4}} The `init` block was not added to Kotlin to help you initialize your properties; it is needed for more complex tasks. -Therefore if the `init` block contains only assignments of variables - move it directly to properties, so that they will be correctly initialized near the declaration. +Therefore if the `init` block contains only assignments of variables - move it directly to properties to be correctly initialized near the declaration. In some cases, this rule can be in clash with [6.1.1], but that should not stop you. @@ -2909,7 +3102,7 @@ \subsubsection*{\textbf{Rule 6.1.4}} \subsubsection*{\textbf{Rule 6.1.5}} \leavevmode\newline -This rule is applicable for both interfaces and classes. +This rule is applicable to both interfaces and classes. @@ -2987,7 +3180,7 @@ \subsubsection*{\textbf{Rule 6.1.7}} \end{lstlisting} -In this case the name of the backing property (`_table`) should be the same as the name of the real property (`table`) but should have an underscore (`_`) prefix. +In this case, the name of the backing property (`_table`) should be the same as the name of the real property (`table`) but should have an underscore (`_`) prefix. It is one of the exceptions from the [identifier names rule] @@ -2998,7 +3191,7 @@ \subsubsection*{\textbf{Recommendation 6.1.8}} Kotlin has a perfect mechanism of [properties](https://kotlinlang.org/docs/reference/properties.html\#properties-and-fields). -Kotlin compiler automatically generates `get` and `set` methods for properties and also provides the possibility to override it. +Kotlin compiler automatically generates `get` and `set` methods for properties and can override them. @@ -3055,7 +3248,7 @@ \subsubsection*{\textbf{Recommendation 6.1.8}} \subsubsection*{\textbf{Rule 6.1.9}} \leavevmode\newline -If you have ignored [recommendation 6.1.8] you should be careful with using the name of the property in your custom getter/setter +If you ignored [recommendation 6.1.8], be careful with using the name of the property in your custom getter/setter as it can accidentally cause a recursive call and a `StackOverflow Error`. Use the `field` keyword instead. @@ -3080,7 +3273,7 @@ \subsubsection*{\textbf{Recommendation 6.1.10 no trivial getters and setters are Trivial setters - are merely setting the field with a value without any transformation. -However, in Kotlin, trivial getters/setters are generated by the default. There is no need to use it explicitly for all types of data structures in Kotlin. +However, in Kotlin, trivial getters/setters are generated by default. There is no need to use it explicitly for all types of data structures in Kotlin. @@ -3113,7 +3306,7 @@ \subsubsection*{\textbf{Recommendation 6.1.10 no trivial getters and setters are \subsubsection*{\textbf{Rule 6.1.11}} \leavevmode\newline -In Java, before functional programming became popular, many classes from common libraries used configuration paradigm. +In Java, before functional programming became popular, many classes from common libraries used the configuration paradigm. To use these classes, you had to create an object with the constructor with 0-2 arguments and set the fields needed to run the object. @@ -3236,7 +3429,7 @@ \subsubsection*{\textbf{Rule 6.4.1}} As described in [6.2 Extension functions], extension functions are a powerful. Instead of using utility classes/objects, use it extention functions. -This allows you to avoid unnecessary complexity and class/object wrapping and use top-level functions instead. +This enables you to avoid unnecessary complexity and class/object wrapping and use top-level functions instead. @@ -3266,7 +3459,7 @@ \subsubsection*{\textbf{Rule 6.4.1}} \subsubsection*{\textbf{Recommendation 6.4.2}} \leavevmode\newline -Kotlin’s objects are extremely useful when you need to implement some interface from an external library that doesn’t have any state. +Kotlin’s objects are extremely useful when you need to implement some interface from an external library that does not have any state. There is no need to use classes for such structures. From 8fa93bd296074bd82b96100a2890de714d870c56 Mon Sep 17 00:00:00 2001 From: soWhoAmI Date: Wed, 16 Dec 2020 16:26:39 +0300 Subject: [PATCH 2/5] feature/wp-update ### What's done: * Fixed bugs --- .../ruleset/generation/GenerationDocs.kt | 3 +- wp/sections/appendix.tex | 2638 +++++++++++++++-- 2 files changed, 2313 insertions(+), 328 deletions(-) diff --git a/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt b/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt index 7e2d2e8910..17ed549f66 100644 --- a/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt +++ b/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt @@ -33,7 +33,6 @@ private fun generateCodeStyle() { val lines = file.readLines().toMutableList() tempFile.printWriter().use { writer -> val iterator = lines.iterator() - writer.writeln("\\section*{guide}") writer.writeln("\\lstMakeShortInline[basicstyle=\\ttfamily\\bfseries]`") while (iterator.hasNext()) { var line = iterator.next() @@ -128,7 +127,7 @@ private fun generateCodeStyle() { } } val appendixFileLines = File("wp/sections/appendix.tex").readLines().toMutableList() - appendixFileLines.removeAll(appendixFileLines.subList(appendixFileLines.indexOf("\\section*{guide}"), appendixFileLines.lastIndex + 1)) + appendixFileLines.removeAll(appendixFileLines.subList(appendixFileLines.indexOf("\\lstMakeShortInline[basicstyle=\\ttfamily\\bfseries]`"), appendixFileLines.lastIndex + 1)) appendixFileLines.addAll(tempFile.readLines()) File("wp/sections/appendix.tex").writeText(appendixFileLines.joinToString(separator = "\n")) } diff --git a/wp/sections/appendix.tex b/wp/sections/appendix.tex index 0a16ef8d8d..d3e4b35937 100644 --- a/wp/sections/appendix.tex +++ b/wp/sections/appendix.tex @@ -9,325 +9,601 @@ \subsection{Use-case diagram} \subsection{Package diagram} \includegraphics[scale=0.65]{pictures/package.png} \lstMakeShortInline[basicstyle=\ttfamily\bfseries]` -\section*{available-rules} -\scriptsize -\begin{longtable}{ |l|p{0.8cm}|p{0.8cm}| p{3cm} | } -\hline -\multicolumn{4}{|c|}{Available Rules} \\ -\hline -\textbf{diKTat rule} & \textbf{code style} & \textbf{autofix} & \textbf{config} \\ -\hline -VARIABLE\underline{ }NAME\underline{ }INCORRECT & 1.1.1 & no & no \\ -VARIABLE\underline{ }HAS\underline{ }PREFIX & 1.1.1 & yes & no \\ -IDENTIFIER\underline{ }LENGTH & 1.1.1 & no & no \\ -GENERIC\underline{ }NAME & 1.1.1 & yes & no \\ -BACKTICKS\underline{ }PROHIBITED & 1.1.1 & no & no \\ -FILE\underline{ }NAME\underline{ }INCORRECT & 1.1.1 & yes & no \\ -EXCEPTION\underline{ }SUFFIX & 1.1.1 & yes & no \\ -CONFUSING\underline{ }IDENTIFIER\underline{ }NAMING & 1.1.1 & no & no \\ -PACKAGE\underline{ }NAME\underline{ }MISSING & 1.2.1 & yes & no \\ -PACKAGE\underline{ }NAME\underline{ }INCORRECT\underline{ }CASE & 1.2.1 & yes & no \\ -PACKAGE\underline{ }NAME\underline{ }INCORRECT\underline{ }PREFIX & 1.2.1 & yes & no \\ -PACKAGE\underline{ }NAME\underline{ }INCORRECT\underline{ }SYMBOLS & 1.2.1 & no & no \\ -PACKAGE\underline{ }NAME\underline{ }INCORRECT\underline{ }PATH & 1.2.1 & yes & no \\ -INCORRECT\underline{ }PACKAGE\underline{ }SEPARATOR & 1.2.1 & yes & no \\ -CLASS\underline{ }NAME\underline{ }INCORRECT & 1.3.1 & yes & no \\ -OBJECT\underline{ }NAME\underline{ }INCORRECT & 1.3.1 & yes & no \\ -ENUM\underline{ }VALUE & 1.3.1 & yes & enumStyle: snakeCase, pascalCase \\ -FUNCTION\underline{ }NAME\underline{ }INCORRECT\underline{ }CASE & 1.4.1 & yes & no \\ -CONSTANT\underline{ }UPPERCASE & 1.5.1 & yes & no \\ -VARIABLE\underline{ }NAME\underline{ }INCORRECT\underline{ }FORMAT & 1.6.1 & yes & no \\ -FUNCTION\underline{ }BOOLEAN\underline{ }PREFIX & 1.6.2 & yes & no \\ -MISSING\underline{ }KDOC\underline{ }TOP\underline{ }LEVEL & 2.1.1 & no & no \\ -MISSING\underline{ }KDOC\underline{ }CLASS\underline{ }ELEMENTS & 2.1.1 & no & no \\ -MISSING\underline{ }KDOC\underline{ }ON\underline{ }FUNCTION & 2.1.1 & yes & no \\ -KDOC\underline{ }NO\underline{ }CONSTRUCTOR\underline{ }PROPERTY & 2.1.1 & yes & no \\ -KDOC\underline{ }EXTRA\underline{ }PROPERTY & 2.1.1 & no & no \\ -KDOC\underline{ }NO\underline{ }CONSTRUCTOR\underline{ }PROPERTY\underline{ }WITH\underline{ }COMMENT & 2.1.1 & yes & no \\ -KDOC\underline{ }WITHOUT\underline{ }PARAM\underline{ }TAG & 2.1.2 & yes & no \\ -KDOC\underline{ }WITHOUT\underline{ }RETURN\underline{ }TAG & 2.1.2 & yes & no \\ -KDOC\underline{ }WITHOUT\underline{ }THROWS\underline{ }TAG & 2.1.2 & yes & no \\ -KDOC\underline{ }EMPTY\underline{ }KDOC & 2.1.3 & no & no \\ -KDOC\underline{ }WRONG\underline{ }SPACES\underline{ }AFTER\underline{ }TAG & 2.1.3 & yes & no \\ -KDOC\underline{ }WRONG\underline{ }TAGS\underline{ }ORDER & 2.1.3 & yes & no \\ -KDOC\underline{ }NEWLINES\underline{ }BEFORE\underline{ }BASIC\underline{ }TAGS & 2.1.3 & yes & no \\ -KDOC\underline{ }NO\underline{ }NEWLINES\underline{ }BETWEEN\underline{ }BASIC\underline{ }TAGS & 2.1.3 & yes & no \\ -KDOC\underline{ }NO\underline{ }NEWLINE\underline{ }AFTER\underline{ }SPECIAL\underline{ }TAGS & 2.1.3 & yes & no \\ -KDOC\underline{ }NO\underline{ }DEPRECATED\underline{ }TAG & 2.1.3 & yes & no \\ -KDOC\underline{ }NO\underline{ }EMPTY\underline{ }TAGS & 2.2.1 & no & no \\ -HEADER\underline{ }WRONG\underline{ }FORMAT & 2.2.1 & yes & no \\ -HEADER\underline{ }MISSING\underline{ }OR\underline{ }WRONG\underline{ }COPYRIGHT & 2.2.1 & yes & mandatoryCopyright \\ -WRONG\underline{ }COPYRIGHT\underline{ }YEAR & 2.2.1 & yes & no \\ -HEADER\underline{ }CONTAINS\underline{ }DATE\underline{ }OR\underline{ }AUTHOR & 2.2.1 & no & no \\ -HEADER\underline{ }MISSING\underline{ }IN\underline{ }NON\underline{ }SINGLE\underline{ }CLASS\underline{ }FILE & 2.2.1 & no & no \\ -HEADER\underline{ }NOT\underline{ }BEFORE\underline{ }PACKAGE & 2.2.1 & yes & no \\ -KDOC\underline{ }TRIVIAL\underline{ }KDOC\underline{ }ON\underline{ }FUNCTION & 2.3.1 & no & no \\ -WRONG\underline{ }NEWLINES\underline{ }AROUND\underline{ }KDOC & 2.4.1 & yes & no \\ -FIRST\underline{ }COMMENT\underline{ }NO\underline{ }SPACES & 2.4.1 & yes & no \\ -COMMENT\underline{ }WHITE\underline{ }SPACE & 2.4.1 & yes & maxSpaces \\ -IF\underline{ }ELSE\underline{ }COMMENTS & 2.4.1 & yes & no \\ -COMMENTED\underline{ }OUT\underline{ }CODE & 2.4.2 & no & no \\ -FILE\underline{ }IS\underline{ }TOO\underline{ }LONG & 3.1.1 & no & maxSize ignoreFolders \\ -FILE\underline{ }CONTAINS\underline{ }ONLY\underline{ }COMMENTS & 3.1.2 & no & no \\ -FILE\underline{ }INCORRECT\underline{ }BLOCKS\underline{ }ORDER & 3.1.2 & yes & no \\ -FILE\underline{ }NO\underline{ }BLANK\underline{ }LINE\underline{ }BETWEEN\underline{ }BLOCKS & 3.1.2 & yes & no \\ -FILE\underline{ }UNORDERED\underline{ }IMPORTS & 3.1.2 & yes & no \\ -FILE\underline{ }WILDCARD\underline{ }IMPORTS & 3.1.2 & no & allowedWildcards \\ -FILE\underline{ }NAME\underline{ }MATCH\underline{ }CLASS & 3.1.2 & yes & no \\ -WRONG\underline{ }ORDER\underline{ }IN\underline{ }CLASS\underline{ }LIKE\underline{ }STRUCTURES & 3.1.4 & yes & no \\ -BLANK\underline{ }LINE\underline{ }BETWEEN\underline{ }PROPERTIES & 3.1.4 & yes & no \\ -WRONG\underline{ }DECLARATIONS\underline{ }ORDER & 3.1.4 & yes & no \\ -NO\underline{ }BRACES\underline{ }IN\underline{ }CONDITIONALS\underline{ }AND\underline{ }LOOPS & 3.2.1 & yes & no \\ -BRACES\underline{ }BLOCK\underline{ }STRUCTURE\underline{ }ERROR & 3.2.2 & yes & openBraceNewline closeBraceNewline \\ -WRONG\underline{ }INDENTATION & 3.3.1 & yes & extendedIndentOfParameters alignedParameters extendedIndentAfterOperators extendedIndentBeforeDot indentationSize \\ -EMPTY\underline{ }BLOCK\underline{ }STRUCTURE\underline{ }ERROR & 3.4.1 & yes & allowEmptyBlocks styleEmptyBlockWithNewline \\ -LONG\underline{ }LINE & 3.5.1 & yes & lineLength \\ -MORE\underline{ }THAN\underline{ }ONE\underline{ }STATEMENT\underline{ }PER\underline{ }LINE & 3.6.1 & yes & no \\ -REDUNDANT\underline{ }SEMICOLON & 3.6.2 & yes & no \\ -WRONG\underline{ }NEWLINES & 3.6.2 & yes & no \\ -TOO\underline{ }MANY\underline{ }BLANK\underline{ }LINES & 3.7.1 & yes & no \\ -WRONG\underline{ }WHITESPACE & 3.8.1 & yes & no \\ -TOO\underline{ }MANY\underline{ }CONSECUTIVE\underline{ }SPACES & 3.8.1 & yes & maxSpaces saveInitialFormattingForEnums \\ -ENUMS\underline{ }SEPARATED & 3.9.1 & yes & no \\ -LOCAL\underline{ }VARIABLE\underline{ }EARLY\underline{ }DECLARATION & 3.10.2 & no & no \\ -WHEN\underline{ }WITHOUT\underline{ }ELSE & 3.11.1 & yes & no \\ -ANNOTATION\underline{ }NEW\underline{ }LINE & 3.12.1 & yes & no \\ -WRONG\underline{ }MULTIPLE\underline{ }MODIFIERS\underline{ }ORDER & 3.14.1 & yes & no \\ -LONG\underline{ }NUMERICAL\underline{ }VALUES\underline{ }SEPARATED & 3.14.2 & yes & maxLength \\ -STRING\underline{ }CONCATENATION & 3.15.1 & no & no \\ -STRING\underline{ }TEMPLATE\underline{ }CURLY\underline{ }BRACES & 3.15.2 & yes & no \\ -STRING\underline{ }TEMPLATE\underline{ }QUOTES & 3.15.2 & yes & no \\ -FLOAT\underline{ }IN\underline{ }ACCURATE\underline{ }CALCULATIONS & 4.1.1 & no & no \\ -SAY\underline{ }NO\underline{ }TO\underline{ }VAR & 4.1.3 & no & no \\ -SMART\underline{ }CAST\underline{ }NEEDED & 4.2.1 & yes & no \\ -TYPE\underline{ }ALIAS & 4.2.2 & no & typeReferenceLength \\ -NULLABLE\underline{ }PROPERTY\underline{ }TYPE & 4.3.1 & yes & no \\ -GENERIC\underline{ }VARIABLE\underline{ }WRONG\underline{ }DECLARATION & 4.3.2 & yes & no \\ -AVOID\underline{ }NULL\underline{ }CHECKS & 4.3.3 & no & no \\ -TOO\underline{ }LONG\underline{ }FUNCTION & 5.1.1 & no & maxFunctionLength isIncludeHeader\\ -NESTED\underline{ }BLOCK & 5.1.2 & no & maxNestedBlockQuantit\\ -AVOID\underline{ }NESTED\underline{ }FUNCTIONS & 5.1.3 & yes & no \\ -LAMBDA\underline{ }IS\underline{ }NOT\underline{ }LAST\underline{ }PARAMETER & 5.2.1 & no & no \\ -TOO\underline{ }MANY\underline{ }PARAMETERS & 5.2.2 & no & maxParameterListSize \\ -WRONG\underline{ }OVERLOADING\underline{ }FUNCTION\underline{ }ARGUMENTS & 5.2.3 & no & no \\ -SINGLE\underline{ }CONSTRUCTOR\underline{ }SHOULD\underline{ }BE\underline{ }PRIMARY & 6.1.1 & yes & no \\ -USE\underline{ }DATA\underline{ }CLASS & 6.1.2 & no & no \\ -EMPTY\underline{ }PRIMARY\underline{ }CONSTRUCTOR & 6.1.3 & yes & no \\ -MULTIPLE\underline{ }INIT\underline{ }BLOCKS & 6.1.4 & yes & no \\ -USELESS\underline{ }SUPERTYPE & 6.1.5 & yes & no \\ -CLASS\underline{ }SHOULD\underline{ }NOT\underline{ }BE\underline{ }ABSTRACT & 6.1.6 & yes & no \\ -NO\underline{ }CORRESPONDING\underline{ }PROPERTY & 6.1.7 & no & no \\ -CUSTOM\underline{ }GETTERS\underline{ }SETTERS & 6.1.8 & no & no \\ -WRONG\underline{ }NAME\underline{ }OF\underline{ }VARIABLE\underline{ }INSIDE\underline{ }ACCESSOR & 6.1.9 & no & no \\ -TRIVIAL\underline{ }ACCESSORS\underline{ }ARE\underline{ }NOT\underline{ }RECOMMENDED & 6.1.10 & yes & no \\ -COMPACT\underline{ }OBJECT\underline{ }INITIALIZATION & 6.1.11 & yes & no \\ -EXTENSION\underline{ }FUNCTION\underline{ }SAME\underline{ }SIGNATURE & 6.2.2 & no & no \\ -AVOID\underline{ }USING\underline{ }UTILITY\underline{ }CLASS & 6.4.1 & no & no \\ -OBJECT\underline{ }IS\underline{ }PREFERRED & 6.4.2 & yes & no \\ -\hline -\end{longtable} + + + + + \section*{\textbf{Diktat Coding Convention}} + + + \subsubsection*{\textbf{Content}} \leavevmode\newline + + \begin{center} + \begin{tabular}{ |p{7,5cm}|p{7,5cm}| } + +\hline + Chapter&Content\\ + +\hline + [0. Preface] & [Purpose], [General principles], [Terminology], [Exceptions] \\ + [1. Naming] & [Identifiers], [Package names], [Classes, enumeration and interfaces], [Functions], [Constants], [Variables] \\ + [2. Docs] & [Kdoc], [File header], [Comments on function header ], [Code comments] \\ + [3. General formatting] & [File-related rules], [Braces], [Indentation], [Empty blocks], [Line length], [Line breaks (newlines)], [Blank lines], [Horizontal space], [Enumerations], [Variable declaration], [When expression], [Annotations], [Layout of comments], [Modifiers and constant values], [Strings]\\ + [4. Variables and types] & [Variables], [Types], [Null safety and variable declarations]\\ + [5. Functions] & [Function design], [Function arguments]\\ + [6. Classes] & [Classes], [Extension functions], [Interfaces], [Objects] \\ + [7. Kotlin \& Java] & \\ + +\hline + \end{tabular} + +\end{center} + + + + + \section*{\textbf{Preface}} + \subsection*{\textbf{Purpose of this document}} + + + The purpose of this document is to provide a specification that software developers could reference to enhance their ability to write consistent, easy-to-read, and high-quality code. + Such a specification will ultimately improve software development efficiency and product competitiveness. + For the code to be considered high-quality, it must entail the following characteristics: + 1. Simplicity + 2. Maintainability + 3. Reliability + 4. Testability + 5. Efficiency + 6. Portability + 7. Reusability + + + + + \subsection*{\textbf{General principles}} + + + Like other modern programming languages, Kotlin is an advanced programming language that complies with the following general principles: + 1. Clarity — a necessary feature of programs that are easy to maintain and refactor. + 2. Simplicity — a code is easy to understand and implement. -3. Consistency — enables a code to be easily modified, reviewed and understood by the team members. Unification is particularly important when the same team works on the same project, utilizing similar styles.enables code to be easily modified, reviewed and understood by the team members. + +3. Consistency — enables a code to be easily modified, reviewed, and understood by the team members. Unification is particularly important when the same team works on the same project, utilizing similar styles enabling a code to be easily modified, reviewed, and understood by the team members. + + + Also, we need to consider the following factors when programming on Kotlin: + + + 1. Writing clean and simple Kotlin code + + + Kotlin combines two of the main programming paradigms: functional and object-oriented. + Both of these paradigms are trusted and well-known software engineering practices. - As a young programming language, Kotlin is built on the top of well-established languages such as Java, C++, C\#, and Scala. - This enables Kotlin to introduce many features that help you write cleaner, more readable code, while also reducing the number of complex code structures. For example, type and null safety, extension functions, infix syntax, immutability, val/var differentiation, expression-oriented features, when statements, much easier work with collections, type auto conversion, and other syntactic sugar. + + As a young programming language, Kotlin is built on top of well-established languages such as Java, C++, C\#, and Scala. + + This enables Kotlin to introduce many features that help a developer write cleaner, more readable code while also reducing the number of complex code structures. For example, type and null safety, extension functions, infix syntax, immutability, val/var differentiation, expression-oriented features, "when" statements, much easier work with collections, type auto conversion, and other syntactic sugar. + + + 2. Following Kotlin idioms - The author of Kotlin, Andrey Breslav, mentioned that Kotlin is both pragmatic and practical, but not academic. + + + + The author of Kotlin, Andrey Breslav, mentioned that Kotlin is both pragmatic and practical, but not academic. + Its pragmatic features enable ideas to be transformed into real working software easily. Kotlin is closer to natural languages than its predecessors, and it implements the following design principles: readability, reusability, interoperability, security, and tool-friendliness (https://blog.jetbrains.com/kotlin/2018/10/kotlinconf-2018-announcements/). + + + 3. Using Kotlin efficiently + + + Some Kotlin features can help you to write higher-performance code: including rich coroutine library, sequences, inline functions/classes, arrays of basic types, tailRec, and CallsInPlace of contract. + + + \subsection*{\textbf{Terminology}} + + + \textbf{Rules} — conventions that should be followed when programming. + + + \textbf{Recommendations} — conventions that should be considered when programming. + + + \textbf{Explanation} — necessary explanations of rules and recommendations. + + + \textbf{Valid Example} — recommended examples of rules and recommendations. + + + \textbf{Invalid Example} — not recommended examples of rules and recommendations. + + + Unless otherwise stated, this specification applies to versions 1.3 and later of Kotlin. + + + \subsection*{\textbf{Exceptions}} + + + Even though exceptions may exist, it is essential to understand why rules and recommendations are needed. -Depending on your project situation or personal habits, you can break some of the rules. However, remember that one exception may lead to many and eventually can destroy code consistency. As such, there should be very few exceptions. + +Depending on a project situation or personal habits, you can break some of the rules. However, remember that one exception may lead to many and eventually can destroy code consistency. As such, there should be very few exceptions. + When modifying open-source code or third-party code, you can choose to use the code style from this open-source project (instead of using the existing specifications) to maintain consistency. + Software that is directly based on the Android native operating system interface, such as the Android Framework, remains consistent with the Android style. + \section*{\textbf{1. Naming}} -In programming, it is not always easy to meaningfully and appropriately name variables, functions, classes, etc. Using meaningful names helps you clearly express your code's main ideas and functionality and avoid misinterpretation, unnecessary coding and decoding, "magic" numbers, and inappropriate abbreviations. + +In programming, it is not always easy to meaningfully and appropriately name variables, functions, classes, etc. Using meaningful names helps to clearly express your code's main ideas and functionality and avoid misinterpretation, unnecessary coding and decoding, "magic" numbers, and inappropriate abbreviations. + + + Note: The source file encoding format (including comments) must be UTF-8 only. The ASCII horizontal space character (0x20, that is, space) is the only permitted whitespace character. Tabs should not be used for indentation. + + + \subsection*{\textbf{1.1 Identifier names}} -\subsubsection*{\textbf{1.1.1}} + +\subsubsection*{\textbf{Rule 1.1.1}} +\leavevmode\newline + + + For identifiers, use the following naming conventions: + 1. All identifiers should use only ASCII letters or digits, and the names should match regular expressions `\w{2,64}`. + Explanation: Each valid identifier name should match the regular expression `\w{2,64}`. + `{2,64}` means that the name length is 2 to 64 characters, and the length of the variable name should be proportional to its life range, functionality, and responsibility. + Name lengths of less than 31 characters are generally recommended. However, this depends on the project. Otherwise, a class declaration with generics or inheritance from a superclass can cause line breaking. -No special prefix or suffix should be used in the names. The following examples are inappropriate: name\_, mName, s\_name, and kName. + +No special prefix or suffix should be used in names. The following examples are inappropriate names: name\_, mName, s\_name, and kName. + + + 2. Choose file names that would describe the content. Use camel case (PascalCase) and `.kt` extension. + + + 3. Typical examples of naming: + + + +\begin{center} + \begin{tabular}{ |p{5,0cm}|p{5,0cm}|p{5,0cm}| } + +\hline + Meaning&Correct&Incorrect\\ + +\hline + "XML Http Request" & XmlHttpRequest & XMLHTTPRequest \\ + "new customer ID" & newCustomerId & newCustomerID \\ + "inner stopwatch" & innerStopwatch & innerStopWatch \\ + "supports IPv6 on iOS" & supportsIpv6OnIos & supportsIPv6OnIOS \\ + "YouTube importer" & YouTubeImporter & YoutubeImporter \\ + +\hline + +\end{tabular} + +\end{center} + 4. The usage of (``) and free naming for functions and identifiers are prohibited. For example, the following code is not recommended: + + + \begin{lstlisting}[language=Kotlin] -val `my dummy name-with-minus` = "value" +val `my dummy name-with-minus` = "value" \end{lstlisting} + + The only exception is function names in `Unit tests.` + + + 5. Backticks (``) should not be used for identifiers, except the names of test methods (marked with @Test annotation): + +\begin{lstlisting}[language=Kotlin] @Test fun `my test`() { /*...*/ } +\end{lstlisting} 6. The following table contains some characters that may cause confusion. Be careful when using them as identifiers. To avoid issues, use other names instead. + +\begin{center} + +\begin{tabular}{ |p{5,0cm}|p{5,0cm}|p{5,0cm}| } + +\hline + Expected&Confusing name&Suggested name\\ + +\hline + 0 (zero) & O, D & obj, dgt \\ + 1 (one) & I, l & it, ln, line \\ + 2 (two) & Z & n1, n2 \\ + 5 (five) & S & xs, str \\ + 6 (six) & e & ex, elm \\ + 8 (eight) & B & bt, nxt \\ + n,h & h,n & nr, head, height \\ + rn, m & m,rn & mbr, item \\ -\textbf{Exceptions} + +\hline + +\end{tabular} + +\end{center} + +\textbf{Exceptions:} + - The i,j,k variables used in loops are part of the industry standard. One symbol can be used for such variables. + - The `e` variable can be used to catch exceptions in catch block: `catch (e: Exception) {}` + - The Java community generally does not recommend the use of prefixes. However, when developing Android code, you can use the s and m prefixes for static and non-public non-static fields, respectively. + Note that prefixing can also negatively affect the style and the auto-generation of getters and setters. + + + +\begin{center} + +\begin{tabular}{ |p{7,5cm}|p{7,5cm}| } + +\hline + Type&Naming style\\ + +\hline + Interfaces, classes, annotations, enumerated types, and object type names & Camel case, starting with a capital letter. Test classes have a Test suffix. The filename is 'TopClassName'.kt. \\ + Class fields, local variables, methods, and method parameters & Camel case starting with a low case letter. Test methods can be underlined with '\_'; the only exception is [backing properties]\\ + Static constants and enumerated values & Only uppercase underlined with '\_' \\ + Generic type variable & Single capital letter, which can be followed by a number, for example: `E, T, U, X, T2` \\ + Exceptions & Same as class names, but with a suffix Exception, for example: `AccessException` and `NullPointerException`\\ + +\hline + +\end{tabular} + +\end{center} + \subsection*{\textbf{1.2 Packages names}} + \subsubsection*{\textbf{Rule 1.2.1}} +\leavevmode\newline + Package names are in lower case and separated by dots. Code developed within your company should start with `your.company.domain.` Numbers are permitted in package names. + Each file should have a `package` directive. -Package names are all written in lowercase, and consecutive words are concatenated together (no underscores). Package names should contain both the product and module names, and the department (or team) name to prevent conflicts with other teams. Numbers are not permitted. For example: `org.apache.commons.lang3`, `xxx.yyy.v2`. -\textbf{Exceptions:} + +Package names are all written in lowercase, and consecutive words are concatenated together (no underscores). Package names should contain both the product or module names and the department (or team) name to prevent conflicts with other teams. Numbers are not permitted. For example: `org.apache.commons.lang3`, `xxx.yyy.v2`. + + + +\textbf{Exceptions:} + + + - In certain cases, such as open-source projects or commercial cooperation, package names should not start with `your.company.domain.` -- If the package name starts with a number or other characters that cannot be used at the beginning of the Java/Kotlin package name, then underscores are allowed. For example: `com.example._123name`. + +- If the package name starts with a number or other character that cannot be used at the beginning of the Java/Kotlin package name, then underscores are allowed. For example: `com.example._123name`. + - Underscores are sometimes permitted if the package name contains reserved Java/Kotlin keywords, such as `org.example.hyphenated_name`, `int_.example`. -\textbf{Valid example}: + + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] package your.company.domain.mobilecontrol.views +\end{lstlisting} + + \subsection*{\textbf{1.3 Classes}} + \subsubsection*{\textbf{Rule 1.3.1}} +\leavevmode\newline + Classes, enumerations, and interface names use `UpperCamelCase` nomenclature. Follow the naming rules described below: + 1. A class name is usually a noun (or a noun phrase) denoted using the camel case nomenclature, such as UpperCamelCase. For example: `Character` or `ImmutableList`. + An interface name can also be a noun or noun phrase (such as `List`) or an adjective or adjective phrase (such as `Readable`). + Note that verbs are not used to name classes. However, nouns (such as `Customer`, `WikiPage`, and `Account`) can be used. Try to avoid using vague words such as `Manager` and `Process`. + + + 2. Test classes start with the name of the class they are testing and end with 'Test'. For example, `HashTest` or `HashIntegrationTest`. -\textbf{Invalid example}: -class marcoPolo {} -class XMLService {} -interface TAPromotion {} -class info {} + + + +\textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] +class marcoPolo {} +class XMLService {} +interface TAPromotion {} +class info {} +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] class MarcoPolo {} class XmlService {} interface TaPromotion {} class Order {} +\end{lstlisting} + + \subsection*{\textbf{1.4 Functions}} + \subsubsection*{\textbf{Rule 1.4.1}} +\leavevmode\newline + Function names should use `lowerCamelCase` nomenclature. Follow the naming rules described below: + 1. Function names are usually verbs or verb phrases denoted with the camel case nomenclature (`lowerCamelCase`). + For example: `sendMessage`, `stopProcess`, or `calculateValue`. -To name functions use the following formatting rules: + +To name functions, use the following formatting rules: + + + a) To get, modify, or calculate a certain value: get + non-boolean field(). Note that the Kotlin compiler automatically generates getters for some classes, applying the special syntax preferred for the 'get' fields: kotlin private val field: String get() { }. kotlin private val field: String get() { }. + +\begin{lstlisting}[language=Kotlin] private val field: String get() { } +\end{lstlisting} Note: The calling property access syntax is preferred to call getter directly. In this case, the Kotlin compiler automatically calls the corresponding getter. + + + b) `is` + boolean variable name() + + + c) `set` + field/attribute name(). However, note that the syntax and code generation for Kotlin are completely the same as those described for the getters in point a. + + + d) `has` + Noun / adjective () + + + e) verb() + Note: Note: Verb are primarily used for the action objects, such as `document.print ()` -f) verb + noun() + + + +f) verb + noun() + + + g) The Callback function allows the names that use the preposition + verb format, such as: `onCreate()`, `onDestroy()`, `toString()`. -\textbf{Invalid example}: + + + +\textbf{Invalid example}: + + + +\begin{lstlisting}[language=Kotlin] fun type(): String fun Finished(): Boolean fun visible(boolean) fun DRAW() fun KeyListener(Listener) +\end{lstlisting} + + +\textbf{Valid example}: + + + +\begin{lstlisting}[language=Kotlin] fun getType(): String fun isFinished(): Boolean fun setVisible(boolean) fun draw() fun addKeyListener(Listener) +\end{lstlisting} + + 2. An underscore (`_`) can be included in the JUnit test function name and should be used as a separator. Each logical part denoted in `lowerCamelCase`, for example, a typical pattern of using underscore: `pop_emptyStack`. + \subsection*{\textbf{1.5 Constants}} + \subsubsection*{\textbf{Rule 1.5.1 Constant names should be in UPPER case}} +\leavevmode\newline + Constant names should be in UPPER case, words separated by underscore. The jeneral constant naming conventions are listed below: + 1. Constants are attributes created with the `const` keyword, or top-level/`val` local variables of an object that holds immutable data. In most cases, constants can be identified as a `const val` property from the `object`/`companion object`/file top level. These variables contain a fixed constant values that typically should never be changed by programmers. This includes basic types, strings, immutable types, and immutable collections of immutable types. The value is not constant for the object, which state can be changed. -1. Constants are attributes created with the const keyword, or top-level/`val` local variables of an object that holds immutable data. In most cases, constants can be identified as a `const val` property from the `object`/`companion object`/file top level. These variables contain a fixed constant value that typically should never be changed by programmers. This includes basic types, strings, immutable types, and immutable collections of immutable types. If an object state can be changed, the value is not a constant. -2. Constant names should contain only uppercase letters separated by underscores. They should have a val or const val modifier to explicitly make them final. In most cases, if you need to specify a constant value, then you need to create it with the "const val" modifier. Note that not all `val` variables are constants. -3. Objects that have immutable content, such as `Logger` and `Lock`, can be in uppercase as constants or have camel case as regular variables. + + + +2. Constant names should contain only uppercase letters separated by underscores. They should have a `val` or `const val` (`const` should be used only with primitive types) modifier to make them final (immutable) explicitly. In most cases, if you need to specify a constant value, then you need to create it with the `const val` modifier. Note that not all `val` variables are constants. + + + +3. Objects with immutable content, such as `Logger` and `Lock`, can be in uppercase as constants or have camel case as regular variables. + + + 4. Use meaningful constants instead of `magic numbers`. SQL or logging strings should not be treated as magic numbers, nor should they be defined as string constants. + + + Magic constants like `NUM_FIVE = 5` or `NUM_5 = 5` should not be treated as constants. This is because mistakes will easily be made if they are changed to `NUM_5 = 50` or 55. + These constants typically represent business logic values, such as measures, capacity, scope, location, tax rate, promotional discounts, and power base multiples in algorithms. + You can avoid using magic numbers with the following method: + - Using library functions and APIs. For example, instead of checking that `size == 0`, use `isEmpty()` function. To work with `time`, use built-ins from `java.time API`. -- Enumerations can be used to name patterns. Refer to [Recommended usage scenario for enumeration in 3.9] -\textbf{Invalid example}: + +- Enumerations can be used to name patterns. Refer to [Recommended usage scenario for enumeration in 3.9]. + + + +\textbf{Invalid example}: + + + +\begin{lstlisting}[language=Kotlin] var int MAXUSERNUM = 200; val String sL = "Launcher"; +\end{lstlisting} + + +\textbf{Valid example}: + + + +\begin{lstlisting}[language=Kotlin] const val int MAX_USER_NUM = 200; const val String APPLICATION_NAME = "Launcher"; +\end{lstlisting} + + \subsection*{\textbf{1.6 Non-constant fields}} + \subsubsection*{\textbf{Rule 1.6.1}} +\leavevmode\newline + Non-constant field names should use camel case and start with a lowercase letter. -A local variable cannot be treated as a constant even if it is final and immutable. Therefore, it should not use the preceding rules. Names of collection type variables (sets, lists, etc.) should contain plural nouns. + +A local variable cannot be treated as constant even if it is final and immutable. Therefore, it should not use the preceding rules. Names of collection type variables (sets, lists, etc.) should contain plural nouns. + For example: `var namesList: List` + + + Names of non-constant variables should use `lowerCamelCase`. The name of the final immutable field used to store the singleton object can use the same camel case notation. -\textbf{Invalid example}: + + + +\textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] customername: String user: List = listof() +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] var customerName: String val users: List = listOf(); val mutableCollection: MutableSet = HashSet() +\end{lstlisting} + + \subsubsection*{\textbf{Rule 1.6.2}} -Avoid using Boolean variable names with negative meaning. When using a logical operator and name with negative meaning, the code may be difficult to understand, which is referred to as the "double negative". +\leavevmode\newline + + + +Avoid using Boolean variable names with a negative meaning. When using a logical operator and name with negative meaning, the code may be difficult to understand, which is referred to as the "double negative". + For instance, it is not easy to understand the meaning of !isNotError. + The JavaBeans specification automatically generates isXxx() getters for attributes of Boolean classes. + However, not all methods returning Boolean type have this notation. + For Boolean local variables or methods, it is highly recommended that you add non-meaningful prefixes, including is (commonly used by JavaBeans), has, can, should, and must. Modern integrated development environments (IDEs) such as Intellij are already capable of doing this for you when you generate getters in Java. For Kotlin, this process is even more straightforward as everything is on the byte-code level under the hood. -\textbf{Invalid example}: + + + +\textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] val isNoError: Boolean val isNotFound: Boolean fun empty() fun next(); +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] val isError: Boolean val isFound: Boolean val hasLicense: Boolean @@ -335,17 +611,38 @@ \subsubsection*{\textbf{Rule 1.6.2}} val shouldAbort: Boolean fun isEmpty() fun hasNext() +\end{lstlisting} \section*{\textbf{2. Comments}} + + + The best practice is to begin your code with a summary, which can be one sentence. + Try to balance between writing no comments at all and obvious commentary statements for each line of code. + Comments should be accurately and clearly expressed, without repeating the name of the class, interface, or method. + Comments are not a solution to the wrong code. Instead, you should fix the code as soon as you notice an issue or plan to fix it (by entering a TODO comment, including a Jira number). + Comments should accurately reflect the code's design ideas and logic and further describe its business logic. + As a result, other programmers will be able to save time when trying to understand the code. -Imagine that you are writing the comments to help yourself to understand the original ideas behind the code in the future. + +Imagine that you are writing the comments to help yourself to understand the original ideas behind the code in the future. + + + \subsection*{\textbf{2.1 General form of Kdoc}} + + + KDoc is a combination of JavaDoc's block tags syntax (extended to support specific constructions of Kotlin) and Markdown's inline markup. + The basic format of KDoc is shown in the following example: + + + +\begin{lstlisting}[language=Kotlin] /** * There are multiple lines of KDoc text, * Other ... @@ -353,36 +650,118 @@ \subsection*{\textbf{2.1 General form of Kdoc}} fun method(arg: String) { // … } +\end{lstlisting} + + It is also shown in the following single-line form: + + + +\begin{lstlisting}[language=Kotlin] /** Short form of KDoc. */ +\end{lstlisting} Use a single-line form when you store the entire KDoc block in one line (and there is no KDoc mark @XXX). For detailed instructions on how to use KDoc, refer to [Official Document](https://docs.oracle.com/en/Kotlin/Kotlinse/11/tools/KDoc.html). + + + \subsubsection*{\textbf{Rule 2.1.1}} -At a minimum, KDoc should be used for every public, protected, or internal decorated class, interface, enumeration, method, and member field (property). Other code blocks can also have KDocs if needed. -Instead of using comments before properties in class - use `@property` tag in a KDoc of a class. -All properties of the primary constructor should be also documented in a KDoc with a `@property` tag. -1. For setters/getters of properties, obvious comments (like `this getter returns field`) are optional. Note, that Kotlin generates simple `get/set` methods under the hood. +\leavevmode\newline + + + +At a minimum, KDoc should be used for every public, protected, or internal decorated class, interface, enumeration, method, and member field (property). + +Other code blocks can also have KDocs if needed. + +Instead of using comments or KDocs before properties in the primary constructor of a class - use `@property` tag in a KDoc of a class. + +All properties of the primary constructor should also be documented in a KDoc with a `@property` tag. + + + +\textbf{Incorrect example:} + +\begin{lstlisting}[language=Kotlin] +/** + * Class description + */ +class Example( + /** + * property description + */ + val foo: Foo, + // another property description + val bar: Bar +) +\end{lstlisting} + + +\textbf{Correct example:} + +\begin{lstlisting}[language=Kotlin] +/** + * Class description + * @property foo property description + * @property bar another property description + */ +class Example( + val foo: Foo, + val bar: Bar +) +\end{lstlisting} + + +\textbf{Exceptions:} + + + +1. For setters/getters of properties, obvious comments (like `this getter returns field`) are optional. Note that Kotlin generates simple `get/set` methods under the hood. + + + 2. It is optional to add comments for simple one-line methods, such as shown in the example below: + +\begin{lstlisting}[language=Kotlin] val isEmpty: Boolean get() = this.size == 0 +\end{lstlisting} + + or + + + +\begin{lstlisting}[language=Kotlin] fun isEmptyList(list: List) = list.size == 0 +\end{lstlisting} + + Note: You can skip KDocs for a method's override if it is almost the same as the superclass method. + + + \subsubsection*{\textbf{Rule 2.1.2}} -When the method has arguments, return value, or can throw exceptions, it must be described in the KDoc block: with @param, @return, @throws -\subsubsection*{\textbf{Rule 2.1.2}} +\leavevmode\newline + + + \textbf{Valid examples}: -/** + + + +\begin{lstlisting}[language=Kotlin] +/** * This is the short overview comment for the example interface. * / * Add a blank line between the comment text and each KDoc tag underneath * / * @since 2019-01-01 */ protected abstract class Sample { /** - * This is a long comment with whitespace that should be split in + * This is a long comment with whitespace that should be split in * comments on multiple lines in case the line comment formatting is enabled. * / * Add a blank line between the comment text and each KDoc tag underneath * / * @param fox A quick brown fox jumps over the lazy dog - * @return battle between fox and dog + * @return battle between fox and dog */ protected abstract fun foo(Fox fox) /** @@ -392,38 +771,85 @@ \subsubsection*{\textbf{Rule 2.1.2}} * @throws ProblemException if lazy dog wins */ protected fun bar() throws ProblemException { - // Some comments / * No need to add a blank line here * / + // Some comments / * No need to add a blank line here * / var aVar = ... - // Some comments / * Add a blank line before the comment * / + + // Some comments / * Add a blank line before the comment * / fun doSome() } } +\end{lstlisting} + + \subsubsection*{\textbf{Rule 2.1.3}} +\leavevmode\newline + There should be only one space between the Kdoc tag and content. Tags are arranged in the following order: @param, @return, and @throws. + + + Therefore, Kdoc should contain the following: + - Functional and technical description, explaining the principles, intentions, contracts, API, etc. + - The function description and @tags (`implSpec`, `apiNote`, and `implNote`) require an empty line after them. + - `@implSpec`: A specification related to API implementation, and it should let the implementer decide whether to override it. + - `@apiNote`: Explain the API precautions, including whether to allow null and whether the method is thread-safe, as well as the algorithm complexity, input, and output range, exceptions, etc. + - `@implNote`: A note related to API implementation, which implementers should keep in mind. + - One empty line, followed by regular `@param`, `@return`, `@throws`, and other comments. -- The conventional standard "block labels" arranged in the following order: `@param`, `@return`, `@throws`. + +- The conventional standard "block labels" are arranged in the following order: `@param`, `@return`, `@throws`. + Kdoc should not contain: + - Empty descriptions in tag blocks. It is better not to write Kdoc than waste code line space. + - There should be no empty lines between the method/class declaration and the end of Kdoc (`*/` symbols). + Important note: KDoc does not support the `@deprecated` tag. Instead, use the `@Deprecated` annotation. -If a tag block cannot be described in one line, you should indent the content of the new line by `four spaces` from the `@` position to achieve alignment (`@` counts as one + three spaces). -\textbf{Exception:} When the descriptive text in a tag block is too long to wrap, you can indent the alignment with the descriptive text in the last line. The descriptive text of multiple tags does not need to be aligned. -See [3.8 Horizontal space]. -In Kotlin, compared to Java, you are able to put several classes inside one file, so each class should have a Kdoc formatted comment (as stated in rule 2.1). + + + +If a tag block cannot be described in one line, indent the content of the new line by \textit{four spaces} from the `@` position to achieve alignment (`@` counts as one + three spaces). + + + +\textbf{Exception:} + + + +When the descriptive text in a tag block is too long to wrap, you can indent the alignment with the descriptive text in the last line. The descriptive text of multiple tags does not need to be aligned. + +See [3.8 Horizontal space]. + + + +In Kotlin, compared to Java, you can put several classes inside one file, so each class should have a Kdoc formatted comment (as stated in rule 2.1). + This comment should contain @since tag. The right style is to write the application version when its functionality is released. It should be entered after the `@since` tag. + + + \textbf{Examples:} + + + +\begin{lstlisting}[language=Kotlin] /** * Description of functionality * * @since 1.6 */ -Other KDoc tags (such as @param type parameters and @see.) can be added as follow: +\end{lstlisting} + + +Other KDoc tags (such as @param type parameters and @see.) can be added as follows: + +\begin{lstlisting}[language=Kotlin] /** * Description of functionality * @@ -431,45 +857,113 @@ \subsubsection*{\textbf{Rule 2.1.3}} * * @since 1.6 */ +\end{lstlisting} \subsection*{\textbf{2.2 Comments to the file header}} + \subsubsection*{\textbf{Rule 2.2.1}} -Comments on the file header should be placed before the package name and imports. If you need to add more content to the comment, you can subsequently add it in the same format. +\leavevmode\newline + + + +Comments on the file header should be placed before the package name and imports. If you need to add more content to the comment, subsequently add it in the same format. + + + The following examples for Huawei describe the format of the \textbf{copyright license}: \ + Chinese version: `版权所有 (c) 华为技术有限公司 2012-2020` \ + English version: `Copyright (c) Huawei Technologies Co., Ltd. 2012-2020. All rights reserved.` + + + Regarding the \textbf{release notes}, see examples below: + + + - `2012-2020` can be modified according to your actual situation. `2012` and `2020` are the years the file was first created and last modified, respectively. + These two years can be the same (for example, `2020–2020`). When the file is substantially changed (for example, through feature extensions and major refactorings), the subsequent years must be updated. -- The \textbf{copyright statement} can use your company's subsidiaries. For example: \ + + + +- The \textbf{copyright statement} can use your company's subsidiaries, as shown in the below examples: \ + Chinese version: `版权所有 (c) 海思半导体 2012-2020` \ -English version: `Copyright (c) Hisilicon Technologies Co., Ltd. 2012-2020. All rights reserved.` + +English version: `Copyright (c) Hisilicon Technologies Co., Ltd. 2012-2020. All rights reserved.` + + + - The copyright information should not be written in KDoc style or use single-line comments. It must start from the beginning of the file. + The following example is a copyright statement for Huawei, without other functional comments: + + + +\begin{lstlisting}[language=Kotlin] /* * Copyright (c) Huawei Technologies Co., Ltd. 2012-2020. All rights reserved. */ +\end{lstlisting} + + The following factors should be considered when writing the file header or comments for top-level classes: + - File header comments must start from the top of the file. If it is a top-level file comment, there should be a blank line after the last Kdoc `*/` symbol. If it is a comment for a top-level class, the class declaration should start immediately without using a newline. -- Maintain a unified format. The specific format can be formulated by the project (for example, if you use existing opensource project), and you need to follow it. + +- Maintain a unified format. The specific format can be formulated by the project (for example, if you use an existing opensource project), and you need to follow it. + - A top-level file-Kdoc must include a copyright and functional description, especially if there is more than one top-level class. -- Do not include empty comment blocks.If there is no content after the option `@apiNote`, the entire tag block should be deleted. + +- Do not include empty comment blocks. If there is no content after the option `@apiNote`, the entire tag block should be deleted. + - The industry practice is not to include historical information in comments. The corresponding history can be found in VCS (git, svn, etc.). Therefore, it is not recommended to include historical data in the comments of the Kotlin source code. + + + + + \subsection*{\textbf{2.3 Comments on the function header}} + \subsubsection*{\textbf{Rule 2.3.1}} +\leavevmode\newline + Comments on the function header are placed above function declarations or definitions. A newline should not exist between a function declaration and its Kdoc. Use the preceding [KDoc] style rules. + + + As stated in Chapter 1, the function name should reflect its functionality as much as possible. Therefore, in the Kdoc, try to describe the functionality that is not mentioned in the function name. + Avoid unnecessary comments on dummy coding. + + + The function header comment's content is optional, but not limited to function description, return value, performance constraints, usage, memory conventions, algorithm implementation, reentrant requirements, etc. + + + \subsection*{\textbf{2.4 Code comments}} + \subsubsection*{\textbf{Rule 2.4.1}} +\leavevmode\newline + It is a good practice to add a blank line between the body of the comment and Kdoc tag-blocks. Also, consider the following rules: + - There must be one space between the comment character and the content of the comment -- There must be a newline between a Kdoc and the pressiding code -- An empty line should not exist between a Kdoc and the code it is describing. You do not need to add a blank line before the first comment in a particular name space (code block) (for example, between the function declaration and first comment in a function body). + +- There must be a newline between a Kdoc and presiding code + +- An empty line should not exist between a Kdoc and the code it is describing. You do not need to add a blank line before the first comment in a particular namespace (code block) (for example, between the function declaration and first comment in a function body). + + + \textbf{Valid Examples:} -/** + +\begin{lstlisting}[language=Kotlin] +/** * This is the short overview comment for the example interface. - * + * * @since 1.6 */ public interface Example { @@ -480,34 +974,49 @@ \subsubsection*{\textbf{Rule 2.4.1}} val bField: String = ... /* Add a blank line above the comment */ /** - * This is a long comment with whitespace that should be split in + * This is a long comment with whitespace that should be split in * multiple line comments in case the line comment formatting is enabled. * /* blank line between description and Kdoc tag */ * @param fox A quick brown fox jumps over the lazy dog - * @return the rounds of battle of fox and dog + * @return the rounds of battle of fox and dog */ fun foo(Fox fox) /* Add a blank line above the comment */ /** * These possibilities include: Formatting of header comments - * + * * @return the rounds of battle of fox and dog * @throws ProblemException if lazy dog wins */ fun bar() throws ProblemException { // Some comments /* Since it is the first member definition in this range, there is no need to add a blank line here */ var aVar = ... - // Some comments /* Add a blank line above the comment */ + + // Some comments /* Add a blank line above the comment */ fun doSome() } } -- Leave one single space between the comment on the right side of the code and the code. -If you use conditional comments in the `if-else-if` scenario, put the comments inside the `else-if` branch or in the conditional block, but not before the `else-if`. This makes your code more understandable. +\end{lstlisting} + + +- Leave one single space between the comment on the right side of the code and the code. + +If you use conditional comments in the `if-else-if` scenario, put the comments inside the `else-if` branch or in the conditional block, but not before the `else-if`. This makes the code more understandable. + When the if-block is used with curly braces, the comment should be placed on the next line after opening the curly braces. + Compared to Java, the `if` statement in Kotlin statements returns a value. For this reason, a comment block can describe a whole `if-statement`. + + + \textbf{Valid examples:} + + + +\begin{lstlisting}[language=Kotlin] val foo = 100 // right-side comment val bar = 200 /* right-side comment */ + // general comment for the value and whole if-else condition val someVal = if (nr % 15 == 0) { // when nr is a multiple of both 3 and 5 @@ -524,84 +1033,217 @@ \subsubsection*{\textbf{Rule 2.4.1}} // otherwise, we print the number. println(x) } -- Start all comments (including KDoc) with a space after the first symbol (`//`, `/*`, `/**` and `*`) +\end{lstlisting} + + +- Start all comments (including KDoc) with space after the first symbol (`//`, `/*`, `/**` and `*`) + + + \textbf{Valid example:} + +\begin{lstlisting}[language=Kotlin] val x = 0 // this is a comment +\end{lstlisting} + + \subsubsection*{\textbf{Rule 2.4.2}} +\leavevmode\newline + Do not comment on unused code blocks, including imports. Delete these code blocks immediately. + A code is not used to store history. Git, svn, or other VCS tools should be used for this purpose. -Unused imports increase the coupling of the code and are not conducive to maintenance. The commented out code cannot be properly maintained. -When you attempt to reuse the code, there is a high probability that you will introduce defects that are easily missed. -The correct approach is to delete the unnecessary code directly and immediately when it is not used. -If you need the code again, consider porting or rewriting it as changes could have occurred since you first commented on the code. + +Unused imports increase the coupling of the code and are not conducive to maintenance. The commented out code cannot be appropriately maintained. + +In an attempt to reuse the code, there is a high probability that you will introduce defects that are easily missed. + +The correct approach is to delete the unnecessary code directly and immediately when it is not used anymore. + +If you need the code again, consider porting or rewriting it as changes could have occurred since you first commented on the code. + + + \subsubsection*{\textbf{Recommendation 2.4.3}} +\leavevmode\newline + The code officially delivered to the client typically should not contain TODO/FIXME comments. + `TODO` comments are typically used to describe modification points that need to be improved and added. For example, refactoring FIXME comments are typically used to describe known defects and bugs that will be subsequently fixed and are not critical for an application. + They should all have a unified style to facilitate the unified text search processing. -\textbf{For example}: + + + +\textbf{Example}: + +\begin{lstlisting}[language=Kotlin] // TODO(): Jira-XXX - support new json format // FIXME: Jira-XXX - fix NPE in this code block +\end{lstlisting} + + At a version development stage, these annotations can be used to highlight the issues in the code, but all of them should be fixed before a new product version is released. + \section*{\textbf{3. General formatting}} + \subsection*{\textbf{3.1 File-related rules}} + \subsubsection*{\textbf{Rule 3.1.1}} +\leavevmode\newline + + + If the file is too long and complex, it should be split into smaller files, functions, or modules. + It is recommended to horizontally or vertically split the file according to responsibilities or hierarchy of its parts. + The only exception to this rule is code generation - the auto-generated files that are not manually modified can be longer. + + + \subsubsection*{\textbf{Rule 3.1.2}} +\leavevmode\newline + A source file contains code blocks in the following order: copyright, package name, imports, and top-level classes. They should be separated by one blank line. + + + a) Code blocks should be in the following order: + 1. Kdoc for licensed or copyrighted files + 2. `@file` annotation + 3. Package name + 4. Import statements + 5. Top-class header and top-function header comments + 6. Top-level classes or functions -b) Each of the preceding code blocks should be separated by a blank line. -c) Import statements are alphabetically arranged, without using line breaks and wildcards ( wildcard imports - `*`). -d) \textbf{Recommendation}: One `.kt` source file should contain only one class declaration, and its name should match the filename + + + +b) Each of the preceding code blocks should be separated by a blank line. + + + +c) Import statements are alphabetically arranged, without using line breaks and wildcards ( wildcard imports - `*`). + + + +d) \textbf{Recommendation}. One `.kt` source file should contain only one class declaration, and its name should match the filename + + + e) Avoid empty files that do not contain the code or contain only imports/comments/package name + + + \subsubsection*{\textbf{Recommendation 3.1.3}} +\leavevmode\newline + + + From top to bottom, the order is the following: + 1. Android + 2. Imports of packages used internally in your organization + 3. Imports from other non-core dependencies + 4. Java core packages + 5. kotlin stdlib + + + Each category should be alphabetically arranged. Each group should be separated by a blank line. This style is compatible with [Android import order](https://source.android.com/setup/contribute/code-style\#order-import-statements). + + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] import android.* // android import androidx.* // android import com.android.* // android + import com.your.company.* // your company's libs import your.company.* // your company's libs + import com.fasterxml.jackson.databind.ObjectMapper // other third-party dependencies import org.junit.jupiter.api.Assertions + import java.io.IOException // java core packages import java.net.URL + import kotlin.system.exitProcess // kotlin standard library import kotlinx.coroutines.* // official kotlin extension library +\end{lstlisting} + + \subsubsection*{\textbf{Recommendation 3.1.4}} +\leavevmode\newline + The declaration parts of class-like code structures (class, interface, etc.) should be in the following order: compile-time constants (for objects), class properties, late-init class properties, init-blocks, constructors, public methods, internal methods, protected methods, private methods, and companion object. Blank lines should separate their declaration. + + + Notes: -1. There should be no blank lines between properties. -\textbf{Exceptions}: When there is a comment before a property on a separate line or annotations on a separate line. + +1. There should be no blank lines between properties with the following \textbf{exceptions}: when there is a comment before a property on a separate line or annotations on a separate line. + 2. Properties with comments/Kdoc should be separated by a newline before the comment/Kdoc. + 3. Enum entries and constant properties (`const val`) in companion objects should be alphabetically arranged. + + + The declaration part of a class or interface should be in the following order: + - Compile-time constants (for objects) + - Properties + - Late-init class properties + - Init-blocks + - Constructors + - Methods or nested classes. Put nested classes next to the code they are used by. + If the classes are meant to be used externally and are not referenced inside the class, put them after the companion object. + - Companion object + + + \textbf{Exception:} + All variants of a `(private) val` logger should be placed in the beginning of the class (`(private) val log`, `LOG`, `logger`, etc.). + + + \subsection*{\textbf{3.2 Braces}} + \subsubsection*{\textbf{Rule 3.2.1}} -Braces should always be used in `if`, `else`, `for`, `do`, and `while` statements, even if the program body is empty or contains only one statement. In special Kotlin `when` statements, you do not need to use braces for single-line statements. +\leavevmode\newline + + + +Braces should always be used in `if`, `else`, `for`, `do`, and `while` statements, even if the program body is empty or contains only one statement. In special Kotlin `when` statements, you do not need to use braces for single-line statements. + + + \textbf{Valid example:} + + + +\begin{lstlisting}[language=Kotlin] when (node.elementType) { FILE -> { checkTopLevelDoc(node) @@ -609,44 +1251,98 @@ \subsubsection*{\textbf{Rule 3.2.1}} } CLASS -> checkClassElements(node) } -\textbf{Exception:} The only exception is ternary operator in Kotlin (a single line `if () <> else <>` ) +\end{lstlisting} +\textbf{Exception:} The only exception is ternary operator in Kotlin (a single line `if () <> else <>` ) + + + \textbf{Invalid example:} + + + +\begin{lstlisting}[language=Kotlin] val value = if (string.isEmpty()) // WRONG! 0 else 1 -val value = if (string.isEmpty()) 0 else 1 // Okay -if (condition) { - println("test") -} else { +\end{lstlisting} + + +\textbf{Valid example}: + + + +\begin{lstlisting}[language=Kotlin] +val value = if (string.isEmpty()) 0 else 1 // Okay +\end{lstlisting} + + +\begin{lstlisting}[language=Kotlin] +if (condition) { + println("test") +} else { println(0) } +\end{lstlisting} + + \subsubsection*{\textbf{Rule 3.2.2 For}} +\leavevmode\newline + + + Follow the K\&R style (1TBS or OTBS) for *non-empty* code blocks with braces: + - The opening brace and first line of the code block are on the same line. + - The closing brace is on its own new line. -- The closing brace can be followed by a newline. The only exceptions are `else`, `finally`, and `while` (from `do-while` statement), or `catch` keywords. -These keywords should not be split from the closing brace by a newline. -\textbf{Exception cases}: -1) For lambdas, there is no need to put a newline after the first (function-related) opening brace. A newline should appear only after an arrow (`->`) (see [point 5 of Rule 3.6.2]. + +- The closing brace can be followed by a newline character. The only exceptions are `else`, `finally`, and `while` (from `do-while` statement), or `catch` keywords. + +These keywords should not be split from the closing brace by a newline character. + + + +\textbf{Exception cases}: + + + +1) For lambdas, there is no need to put a newline character after the first (function-related) opening brace. A newline character should appear only after an arrow (`->`) (see [point 5 of Rule 3.6.2]). + + + +\begin{lstlisting}[language=Kotlin] arg.map { value -> foo(value) } +\end{lstlisting} + + 2) for `else`/`catch`/`finally`/`while` (from `do-while` statement) keywords closing brace should stay on the same line: + +\begin{lstlisting}[language=Kotlin] do { if (true) { x++ } else { x-- } -} while (x > 0) +} while (x > 0) +\end{lstlisting} + + \textbf{Valid example:} + + + +\begin{lstlisting}[language=Kotlin] return arg.map { value -> while (condition()) { method() } - value + value } + return MyClass() { @Override fun method() { @@ -663,300 +1359,798 @@ \subsubsection*{\textbf{Rule 3.2.2 For}} } } } +\end{lstlisting} + + \subsection*{\textbf{3.3 Indentation}} + \subsubsection*{\textbf{Rule 3.3.1}} +\leavevmode\newline + + + Only spaces are permitted for indentation, and each indentation should equal `four spaces` (tabs are not permitted). -If you prefer using tabs, simply configure them to automatically change to spaces in your IDE. + +If you prefer using tabs, simply configure them to change to spaces in your IDE automatically. + These code blocks should be indented if they are placed on the new line, and the following conditions are met: + - The code block is placed immediately after an opening brace + - The code block is placed after each operator, including the assignment operator (`+`/`-`/`\&\&`/`=`/etc.) + - The code block is a call chain of methods: + +\begin{lstlisting}[language=Kotlin] someObject .map() .filter() +\end{lstlisting} - The code block is placed immediately after the opening parenthesis. + - The code block is placed immediately after an arrow in lambda: + + + +\begin{lstlisting}[language=Kotlin] arg.map { value -> foo(value) } +\end{lstlisting} + + \textbf{Exceptions}: + 1. Argument lists: \ + a) Eight spaces are used to indent argument lists (both in declarations and at call sites). \ -b) Arguments in argument lists can be aligned if they are on different lines. + +b) Arguments in argument lists can be aligned if they are on different lines. + + + 2. Eight spaces are used if there is a newline after any binary operator. + + + 3. Eight spaces are used for functional-like styles when the newline is placed before the dot. + + + 4. Super type lists: \ + a) Four spaces are used if the colon before the supertype list is on a new line. \ -b) Four spaces are used before each supertype, and eight spaces are used if the colon is on a new line. -\textbf{Note:} there should be an indentation after all statements such as `if`, `for`, etc. However, according to this code style, such statements require braces. + +b) Four spaces are used before each supertype, and eight spaces are used if the colon is on a new line. + + + +\textbf{Note:} there should be an indentation after all statements such as `if`, `for`, etc. However, according to this code style, such statements require braces. + + + +\begin{lstlisting}[language=Kotlin] if (condition) foo() -\textbf{Exceptions}: -- When breaking parameter list of a method/class constructor it can be aligned with `8 spaces`. A parameter that was moved to a new line can be on the same level as the previous argument: +\end{lstlisting} + + +\textbf{Exceptions}: + +- When breaking the parameter list of a method/class constructor, it can be aligned with `8 spaces`. A parameter that was moved to a new line can be on the same level as the previous argument: + + + +\begin{lstlisting}[language=Kotlin] fun visit( node: ASTNode, autoCorrect: Boolean, params: KtLint.Params, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit -) { +) { } +\end{lstlisting} + + - Such operators as `+`/`-`/`*` can be indented with `8 spaces`: + + + +\begin{lstlisting}[language=Kotlin] val abcdef = "my splitted" + " string" -- A list of supertypes should be indented with `4 spaces` if they are on different lines, or with `8 spaces` if the leading colon is also on a separate line +\end{lstlisting} + + +- A list of supertypes should be indented with `4 spaces` if they are on different lines or with `8 spaces` if the leading colon is also on a separate line + + + +\begin{lstlisting}[language=Kotlin] class A : B() + class A : B() +\end{lstlisting} + + \subsection*{\textbf{3.4 Empty blocks}} + \subsubsection*{\textbf{Recommendation 3.4.1}} +\leavevmode\newline + + + An empty code block can be closed immediately on the same line and the next line. However, a newline is recommended between opening and closing braces `{}` (see the examples below.) + + + Generally, empty code blocks are prohibited; using them is considered a bad practice (especially for catch block). + They are only appropriate for overridden functions when the base class's functionality is not needed in the class-inheritor. -override fun foo() { + +\begin{lstlisting}[language=Kotlin] +override fun foo() { } -\textbf{Valid examples} (but note once again, that generally empty blocks are prohibited): -fun doNothing() {} +\end{lstlisting} + + +\textbf{Valid examples} (note once again that generally empty blocks are prohibited): + + + +\begin{lstlisting}[language=Kotlin] +fun doNothing() {} + fun doNothingElse() { } +\end{lstlisting} + + \textbf{Invalid examples:} + +\begin{lstlisting}[language=Kotlin] try { doSomething() } catch (e: Some) {} +\end{lstlisting} + + Use the following valid code instead: + +\begin{lstlisting}[language=Kotlin] try { doSomething() } catch (e: Some) { } +\end{lstlisting} + + \subsection*{\textbf{3.5 Line length}} + \subsubsection*{\textbf{Recommendation 3.5.1}} +\leavevmode\newline + + + The international code style prohibits `non-Latin` (`non-ASCII`) symbols. -(See [Rule 1.1.1: Identifiers] However, if you still intend on using them, follow the following convention: + +(See [Rule 1.1.1: Identifiers]) However, if you still intend on using them, follow the following convention: + + + - One wide character occupies the width of two narrow characters. + The "wide" and "narrow" parts of a character are defined by its [east Asian width Unicode attribute](https://unicode.org/reports/tr11/). + Typically, narrow characters are also called "half-width" characters. + All characters in the ASCII character set include letters (such as `a, A`), numbers (such as `0, 3`), and punctuation spaces (such as `,` , `{`), all of which are narrow characters. + Wide characters are also called "full-width" characters. Chinese characters (such as `中, 文`), Chinese punctuation (`,` , `;` ), full-width letters and numbers (such as `A、3`) are "full-width" characters. + Each one of these characters represents two narrow characters. -- Any line that exceeds this limit (`120 narrow symbols`) should be wrapped, as described in the [Newline section]. + + + +- Any line that exceeds this limit (`120 narrow symbols`) should be wrapped, as described in the [Newline section]. + + + +\textbf{Exceptions:} + + + 1. The long URL or long JSON method reference in KDoc. + 2. The `package` and `import` statements. + 3. The command line in the comment, enabling it to be cut and pasted into the shell for use. + + + \subsection*{\textbf{3.6 Line breaks}} + \subsubsection*{\textbf{Recommendation 3.6.1}} +\leavevmode\newline + Each line can have a maximum of one code statement. This recommendation prohibits the use of code with `;` because it decreases code visibility. + + + \textbf{Invalid example:} + +\begin{lstlisting}[language=Kotlin] val a = ""; val b = "" +\end{lstlisting} + + \textbf{Valid example:} + +\begin{lstlisting}[language=Kotlin] val a = "" val b = "" +\end{lstlisting} + + \subsubsection*{\textbf{Rule 3.6.2}} -1) Unlike Java, Kotlin allows you not to put a semicolon (`;`) after each statement separated by a newline. +\leavevmode\newline + + + +1) Unlike Java, Kotlin allows you not to put a semicolon (`;`) after each statement separated by a newline character. + There should be no redundant semicolon at the end of the lines. -When a newline is needed to split the line, it should be placed after operators like `\&\&`/`||`/`+`/etc. and all infix functions (for example, `xor`). -However, the newline should be placed before operators such as `.`, `?.`, `?:`, and `::`. + + + +When a newline character is needed to split the line, it should be placed after such operators as `\&\&`/`||`/`+`/etc. and all infix functions (for example, `xor`). + +However, the newline character should be placed before operators such as `.`, `?.`, `?:`, and `::`. + + + Note that all comparison operators, such as `==`, `>`, `<`, should not be split. -\textbf{Invalid example}: + + + +\textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] if (node != null && test != null) {} - if (node != null && +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] + if (node != null && test != null) { } +\end{lstlisting} + + \textbf{Note:} You need to follow the functional style, meaning each function call in a chain with `.` should start at a new line if the chain of functions contains more than one call: + +\begin{lstlisting}[language=Kotlin] val value = otherValue!! .map { x -> x } .filter { val a = true true } - .size + .size +\end{lstlisting} \textbf{Note:} The parser prohibits the separation of the `!!` operator from the value it is checking. + + + \textbf{Exception}: If a functional chain is used inside the branches of a ternary operator, it does not need to be split with newlines. + + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] if (condition) list.map { foo(it) }.filter { bar(it) } else list.drop(1) +\end{lstlisting} + + 2) Newlines should be placed after the assignment operator (`=`). + 3) In function or class declarations, the name of a function or constructor should not be split by a newline from the opening brace `(`. + A brace should be placed immediately after the name without any spaces in declarations or at call sites. + 4) Newlines should be placed right after the comma (`,`). + 5) If a lambda statement contains more than one line in its body, a newline should be placed after an arrow if the lambda statement has explicit parameters. - If it uses an implicit parameter (`it`), the newline should be placed after the opening brace (`{`). + + If it uses an implicit parameter (`it`), the newline character should be placed after the opening brace (`{`). + The following examples illustrate this rule: + + + + + \textbf{Invalid example:} + +\begin{lstlisting}[language=Kotlin] value.map { name -> foo() bar() } -\textbf{Valid example:} +\end{lstlisting} + + +\textbf{Valid example:} + +\begin{lstlisting}[language=Kotlin] value.map { name -> foo() bar() } + val someValue = { node:String -> node } -6) When the function contains only a single expression, it can be written as [expression function](https://kotlinlang.org/docs/reference/functions.html\#single-expression-functions). +\end{lstlisting} + + +6) When the function contains only a single expression, it can be written as [expression function](https://kotlinlang.org/docs/reference/functions.html\#single-expression-functions). + The below example shows the style that should not be used. -Instead of: + + + +Instead of: + +\begin{lstlisting}[language=Kotlin] override fun toString(): String { return "hi" } +\end{lstlisting} use: + +\begin{lstlisting}[language=Kotlin] override fun toString() = "hi" +\end{lstlisting} + + 7) If an argument list in a function declaration (including constructors) or function call contains more than two arguments, these arguments should be split by newlines in the following style. -\textbf{Valid example:} + + + +\textbf{Valid example:} + +\begin{lstlisting}[language=Kotlin] class Foo(val a: String, b: String, val c: String) { } + fun foo( a: String, b: String, c: String ) { + } +\end{lstlisting} + + If and only if the first parameter is on the same line as an opening parenthesis, all parameters can be horizontally aligned by the first parameter. + Otherwise, there should be a line break after an opening parenthesis. + + + Kotlin 1.4 introduced a trailing comma as an optional feature, so it is generally recommended to place all parameters on a separate line + and append [trailing comma](https://kotlinlang.org/docs/reference/whatsnew14.html\#trailing-comma). + It makes the resolving of merge conflicts easier. -\textbf{Valid example:} + + + +\textbf{Valid example:} + +\begin{lstlisting}[language=Kotlin] fun foo( a: String, b: String, ) { + } +\end{lstlisting} + + 8) If the supertype list has more than two elements, they should be separated by newlines -\textbf{Valid example:} + + + +\textbf{Valid example:} + +\begin{lstlisting}[language=Kotlin] class MyFavouriteVeryLongClassHolder : MyLongHolder(), SomeOtherInterface, AndAnotherOne { } +\end{lstlisting} + + \subsection*{\textbf{3.7 Blank lines}} + \subsubsection*{\textbf{Recommendation 3.7.1}} +\leavevmode\newline + + + By reducing unnecessary blank lines, you can display more code on one screen, which improves code readability. -- Blank lines should separate content based on relevance and should be placed between groups of fields, constructors, methods, nested classes, `init` blocks, and objects (see [Rule 3.1.2]. + +- Blank lines should separate content based on relevance and should be placed between groups of fields, constructors, methods, nested classes, `init` blocks, and objects (see [Rule 3.1.2]). + - Do not use more than one line inside methods, type definitions, and initialization expressions. + - Generally, do not use more than two consecutive blank lines in a row. + - Do not put newlines in the beginning or end of code blocks with curly braces. + + + \textbf{Valid example:} + +\begin{lstlisting}[language=Kotlin] fun baz() { + doSomething() // No need to add blank lines at the beginning and end of the code block // ... + } +\end{lstlisting} + + \subsection*{\textbf{3.8 Horizontal space}} + \subsubsection*{\textbf{Rule 3.8.1}} +\leavevmode\newline + + + \textbf{Note:} This recommendation is for the cases where symbols are located on the same line. However, in some cases, a line break could be used instead of a space (described in another rule.) + + + 1. Separate keywords like `if`, `when`, `for`, e.t.c. from the opening parenthesis with single whitespace. + The only exception is the `constructor` keyword, which should not be separated from the opening parenthesis. + + + 2. Separate keywords like `else` or `try` from the opening brace (`{`) with a single whitespace. + If `else` is used in a ternary-style statement without braces, there should be a single space between `else` and the statement after: `if (condition) foo() else bar()` + + + 3. Use a \textbf{single} whitespace before all opening braces (`{`). The only exception is the passing of a lambda as a parameter inside parentheses: + +\begin{lstlisting}[language=Kotlin] private fun foo(a: (Int) -> Int, b: Int) {} foo({x: Int -> x}, 5) // no space before '{' +\end{lstlisting} + + 4. A single whitespace should be placed on both sides of binary operators. This also applies to operator-like symbols. - For example: + + For example: + + + - A colon in generic structures with the `where` keyword: `where T : Type` + - Arrow in lambdas: `(str: String) -> str.length()` + + + +\textbf{Exceptions:} + + + - Two colons (`::`) are written without spaces:\ + `Object::toString` + - The dot separator (`.`) that stays on the same line with an object name:\ + `object.toString()` + - Safe access modifiers `?.` and `!!` that stay on the same line with an object name:\ + `object?.toString()` + - Operator `..` for creating ranges:\ + `1..100` + + + 5. Use spaces after (`,`), (`:`), and (`;`), except when the symbol is at the end of the line. - However, note that this code style prohibits the use of (`;`) in the middle of a line ([Rule 3.2.2]. + + However, note that this code style prohibits the use of (`;`) in the middle of a line ([Rule 3.2.2]). + There should be no whitespaces at the end of a line. + The only scenario where there should be no space after a colon is when the colon is used in the annotation to specify a use-site target (for example, `@param:JsonProperty`). - There should be no spaces before `,` , `:` and `;`. + + There should be no spaces before `,` , `:` and `;`. + \textbf{Exceptions} for spaces and colons are the following: - - when `:` is used to separate a type and a super type, including an anonymous object (after object keyword) + + + + - when `:` is used to separate a type and a supertype, including an anonymous object (after object keyword) + - when delegating to a superclass constructor or different constructor of the same class + + + \textbf{Valid example:} + +\begin{lstlisting}[language=Kotlin] abstract class Foo : IFoo { } + class FooImpl : Foo() { constructor(x: String) : this(x) { /*...*/ } - val x = object : IFoo { /*...*/ } + + val x = object : IFoo { /*...*/ } } -6. There should be \textit{only one space} between the identifier and it's type: `list: List` +\end{lstlisting} + + +6. There should be \textit{only one space} between the identifier and its type: `list: List` + If the type is nullable, there should be no space before `?`. + + + 7. When using `[]` operator (`get/set`) there should be \textbf{no} spaces between identifier and `[` : `someList[0]`. + + + 8. There should be no space between a method or constructor name (both at declaration and at call site) and a parenthesis: + `foo() {}`. Note that this sub-rule is related only to spaces; the rules for whitespaces are described in [Rule 3.6.2]. + This rule does not prohibit, for example, the following code: + +\begin{lstlisting}[language=Kotlin] fun foo ( a: String ) +\end{lstlisting} + + 9. Never put a space after `(`, `[`, `<` (when used as a bracket in templates) or before `)`, `]`, `>` (when used as a bracket in templates). -10. There should be no spaces between prefix/postfix operator (like `!!` or `++`), and it's an operand. + + + +10. There should be no spaces between a prefix/postfix operator (like `!!` or `++`) and its operand. + + + \subsubsection*{\textbf{Recommendation 3.8.2}} +\leavevmode\newline + + + \textit{Horizontal alignment} refers to aligning code blocks by adding space to the code. Horizontal alignment should not be used because: + + + - When modifying code, it takes much time for new developers to format, support, and fix alignment issues. + - Long identifier names will break the alignment and lead to less presentable code. -- Alignment possesses more disadvantages than advantages. To reduce maintenance costs, misalignment is the best choice. + +- There are more disadvantages than advantages in alignment. To reduce maintenance costs, the best choice is not to use horizontal alignment. + + + Recommendation: Alignment only looks suitable for `enum class`, where it can be used in table format to improve code readability: + +\begin{lstlisting}[language=Kotlin] enum class Warnings(private val id: Int, private val canBeAutoCorrected: Boolean, private val warn: String) : Rule { PACKAGE_NAME_MISSING (1, true, "no package name declared in a file"), PACKAGE_NAME_INCORRECT_CASE (2, true, "package name should be completely in a lower case"), PACKAGE_NAME_INCORRECT_PREFIX(3, false, "package name should start from company's domain") ; } +\end{lstlisting} + + \textbf{Valid example:} + +\begin{lstlisting}[language=Kotlin] private val nr: Int // no alignment, but looks fine private var color: Color // no alignment +\end{lstlisting} + + \textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] private val nr: Int // aligned comment with extra spaces private val color: Color // alignment for a comment and alignment for identifier name +\end{lstlisting} + + \subsection*{\textbf{3.9 Enumerations}} + \subsubsection*{\textbf{Recommendation 3.9.1}} +\leavevmode\newline + 1) Enum values are separated by a comma and a line break. `;` is put on the new line: + +\begin{lstlisting}[language=Kotlin] enum class Warnings { A, B, C, ; } +\end{lstlisting} + + This will help to resolve conflicts and reduce the number of conflicts during merging pull requests. + Also use [trailing comma](https://kotlinlang.org/docs/reference/whatsnew14.html\#trailing-comma). + + + 2) If the enum is simple (no properties, methods, and comments inside), you can declare it in a single line: + +\begin{lstlisting}[language=Kotlin] enum class Suit { CLUBS, HEARTS, SPADES, DIAMONDS } +\end{lstlisting} + + 3) Enum classes take preference (if it is possible to use it). For example, instead of two boolean properties: + + + +\begin{lstlisting}[language=Kotlin] val isCelsius = true val isFahrenheit = false +\end{lstlisting} + + use enum class: + + + +\begin{lstlisting}[language=Kotlin] enum class TemperatureScale { CELSIUS, FAHRENHEIT } -- The variable value only changes within a fixed range and is defined with the enum type. +\end{lstlisting} + + +- The variable value only changes within a fixed range and is defined with the enum type. + - Avoid comparison with magic numbers of `-1, 0, and 1`; use enums instead. + + + +\begin{lstlisting}[language=Kotlin] enum class ComparisonResult { ORDERED_ASCENDING, ORDERED_SAME, ORDERED_DESCENDING, ; } +\end{lstlisting} + + \subsection*{\textbf{3.10 Variable declaration}} + \subsubsection*{\textbf{Rule 3.10.1}} -Each property or variable must be declared on a separate line. +\leavevmode\newline + + + +Each property or variable must be declared on a separate line. + + + \textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] val n1: Int; val n2: Int +\end{lstlisting} + + \subsubsection*{\textbf{Recommendation 3.10.2}} +\leavevmode\newline + Declare local variables close to the point where they are first used to minimize their scope. This will also increase the readability of the code. + Local variables are usually initialized during their declaration or immediately after. -The member fields of the class should be declared collectively (see [Rule 3.1.2]. + +The member fields of the class should be declared collectively (see [Rule 3.1.2] for details on the class structure). + + + \subsection*{\textbf{3.11 When expression}} + \subsubsection*{\textbf{Rule 3.11.1}} +\leavevmode\newline + Each `when` statement should contain an `else` statement group, even if it does not contain any code. + + + \textbf{Exception:} If 'when' statement of the `enum or sealed` type contains all enum values, there is no need to have an "else" branch. + The compiler can issue a warning when it is missing. + + + \subsection*{\textbf{3.12 Annotations}} + \subsubsection*{\textbf{Recommendation 3.12.1}} -1. Annotations applied to the class, method or constructor are placed on separate lines (one annotation per line). +\leavevmode\newline + + + +1. Annotations applied to the class, method, or constructor are placed on separate lines (one annotation per line). + + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] @MustBeDocumented @CustomAnnotation fun getNameIfPresent() { /* ... */ } +\end{lstlisting} + + 2. A single annotation should be on the same line as the code it is annotating. + + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] @CustomAnnotation class Foo {} -3. Multiple annotations applied to a field or property can appear on the same line as the corresponding field. -@MustBeDocumented @CustomAnnotation val loader: DataLoader +\end{lstlisting} + + +3. Multiple annotations applied to a field or property can appear on the same line as the corresponding field. + + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] +@MustBeDocumented @CustomAnnotation val loader: DataLoader +\end{lstlisting} + + \subsection*{\textbf{3.13 Layout of comments}} + \subsubsection*{\textbf{Recommendation 3.13.1}} +\leavevmode\newline + + + Block comments should be placed at the same indentation level as the surrounding code. See examples below. + + + +\textbf{Valid example}: + + + +\begin{lstlisting}[language=Kotlin] class SomeClass { /* * This is @@ -964,10 +2158,23 @@ \subsubsection*{\textbf{Recommendation 3.13.1}} */ fun foo() {} } +\end{lstlisting} + + \textbf{Suggestion}: Use `/*...*/` block comments to enable automatic formatting by IDEs. + + + \subsection*{\textbf{3.14 Modifiers and constant values}} + \subsubsection*{\textbf{Recommendation 3.14.1}} +\leavevmode\newline + \textbf{Valid sequence:} + + + +\begin{lstlisting}[language=Kotlin] public / internal / protected / private expect / actual final / open / abstract / sealed / const @@ -987,55 +2194,154 @@ \subsubsection*{\textbf{Recommendation 3.14.1}} infix operator data +\end{lstlisting} + + \subsubsection*{\textbf{Recommendation 3.14.2}} +\leavevmode\newline + \textbf{Note:} Using underscores simplifies reading and helps to find errors in numeric constants. + +\begin{lstlisting}[language=Kotlin] val oneMillion = 1_000_000 val creditCardNumber = 1234_5678_9012_3456L val socialSecurityNumber = 999_99_9999L val hexBytes = 0xFF_EC_DE_5E val bytes = 0b11010010_01101001_10010100_10010010 +\end{lstlisting} + + \subsection*{\textbf{3.15 Strings}} + \subsubsection*{\textbf{Rule 3.15.1}} -String concatenation is prohibited if the string can fit on one line. Use raw strings and string templates instead. Kotlin has significantly improved the use of Strings: +\leavevmode\newline + +String concatenation is prohibited if the string can fit on one line. Use raw strings and string templates instead. Kotlin has significantly improved the use of Strings: + [String templates](https://kotlinlang.org/docs/reference/basic-types.html\#string-templates), [Raw strings](https://kotlinlang.org/docs/reference/basic-types.html\#string-literals) -As such, compared to using explicit concatenation, code looks much better when proper Kotlin strings are used for short lines and you do not need to split them with newlines. + +Therefore, compared to using explicit concatenation, code looks much better when proper Kotlin strings are used for short lines, and you do not need to split them with newline characters. + + + \textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] val myStr = "Super string" val value = myStr + " concatenated" +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] val myStr = "Super string" val value = "$myStr concatenated" +\end{lstlisting} + + \subsubsection*{\textbf{Rule 3.15.2}} +\leavevmode\newline + \textbf{Redundant curly braces in string templates} + + + If there is only one variable in a string template, there is no need to use such a template. Use this variable directly. + \textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] val someString = "${myArgument} ${myArgument.foo()}" +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] val someString = "$myArgument ${myArgument.foo()}" +\end{lstlisting} + + \textbf{Redundant string template} -In case string template contains only one variable - there is no need to use string template. Use this variable directly. + + + +In case a string template contains only one variable - there is no need to use the string template. Use this variable directly. + + + \textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] val someString = "$myArgument" +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] val someString = myArgument +\end{lstlisting} \section*{\textbf{4. Variables and types}} + \subsection*{\textbf{4.1 Variables}} + \subsubsection*{\textbf{Rule 4.1.1}} +\leavevmode\newline + Floating-point numbers provide a good approximation over a wide range of values, but they cannot produce accurate results in some cases. + Binary floating-point numbers are unsuitable for precise calculations because it is impossible to represent 0.1 or any other negative power of 10 in a `binary representation` with a finite length. -The following code example seems to be obvious: + + + +The following code example seems to be obvious: + +\begin{lstlisting}[language=Kotlin] val myValue = 2.0 - 1.1 println(myValue) +\end{lstlisting} + + However, it will print the following value: `0.8999999999999999` + + + Therefore, for precise calculations (for example, in finance or exact sciences), using such types as `Int`, `Long`, `BigDecimal`are recommended. + The `BigDecimal` type should serve as a good choice. -\textbf{Invalid example:} \ + + + +\textbf{Invalid example}: \ + Float values containing more than six or seven decimal numbers will be rounded. + +\begin{lstlisting}[language=Kotlin] val eFloat = 2.7182818284f // Float, will be rounded to 2.7182817 -\textbf{Valid example} (when precise calculations are needed): +\end{lstlisting} + + +\textbf{Valid example}: (when precise calculations are needed): + +\begin{lstlisting}[language=Kotlin] val income = BigDecimal("2.0") val expense = BigDecimal("1.1") println(income.subtract(expense)) // you will obtain 0.9 here +\end{lstlisting} + + \subsubsection*{\textbf{Rule 4.1.2}} +\leavevmode\newline + Since floating-point numbers involve precision problems in computer representation, it is better to use `BigDecimal` as recommended in [Rule 4.1.1] to make accurate computations and comparisons. The following code describes these problems. + + + \textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] val f1 = 1.0f - 0.9f val f2 = 0.9f - 0.8f if (f1 == f2) { @@ -1043,13 +2349,22 @@ \subsubsection*{\textbf{Rule 4.1.2}} } else { println("But this block will be reached") } + val flt1 = f1; val flt2 = f2; if (flt1.equals(flt2)) { println("Expected to enter here") } else { println("But this block will be reached") -} +} +\end{lstlisting} + + +\textbf{Valid example}: + + + +\begin{lstlisting}[language=Kotlin] val foo = 1.03f val bar = 0.42f if (abs(foo - bar) > 1e-6f) { @@ -1057,291 +2372,801 @@ \subsubsection*{\textbf{Rule 4.1.2}} } else { println("Not") } +\end{lstlisting} + + \subsubsection*{\textbf{Rule 4.1.3 Try to use}} +\leavevmode\newline + + + Variables with the `val` modifier are immutable (read-only). + Code robustness and readability increase when using `val` variables instead of `var` variables. + This is because `var` variables can be reassigned several times in the business logic. + However, in some scenarios with loops or accumulators, only `var`s are permitted. + + + \subsection*{\textbf{4.2 Types}} + \subsubsection*{\textbf{Recommendation 4.2.1}} +\leavevmode\newline + + + The Kotlin compiler has introduced [Smart Casts](https://kotlinlang.org/docs/reference/typecasts.html\#smart-casts) that help reduce the size of code. + + + \textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] if (x is String) { print((x as String).length) // x was already automatically cast to String - no need to use 'as' keyword here } +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] if (x is String) { print(x.length) // x was already automatically cast to String - no need to use 'as' keyword here } -Also Kotlin 1.3 introduced [Contracts](https://kotlinlang.org/docs/reference/whatsnew13.html\#contracts) that provide enhanced logic for smart-cast. -Contracts are used and are very stable in `stdlib`. -For example: +\end{lstlisting} + + +Also, Kotlin 1.3 introduced [Contracts](https://kotlinlang.org/docs/reference/whatsnew13.html\#contracts) that provide enhanced logic for smart-cast. + +Contracts are used and are very stable in `stdlib`, for example: + + + + + +\begin{lstlisting}[language=Kotlin] fun bar(x: String?) { if (!x.isNullOrEmpty()) { println("length of '$x' is ${x.length}") // smartcasted to not-null } -} +} +\end{lstlisting} + + Smart cast and contracts are a better choice because they reduce boilerplate code and features forced type conversion. + + + \textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] fun String?.isNotNull(): Boolean = this != null + fun foo(s: String?) { if (s.isNotNull()) s!!.length // No smartcast here and !! operator is used } +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] fun foo(s: String?) { if (s.isNotNull()) s.length // We have used a method with contract from stdlib that helped compiler to execute smart cast } +\end{lstlisting} + + \subsubsection*{\textbf{Recommendation 4.2.2}} +\leavevmode\newline + + + Type aliases provide alternative names for existing types. + If the type name is too long, you can replace it with a shorter name, which helps to shorten long generic types. + For example, code looks much more readable if you introduce a `typealias` instead of a long chain of nested generic types. + We recommend using a `typealias` if the type contains \textbf{more than two} nested generic types and is longer than \textbf{25 chars}. + + + \textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] val b: MutableMap> +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] typealias FileTable = MutableMap> val b: FileTable +\end{lstlisting} + + You can also provide additional aliases for function (lambda-like) types: + +\begin{lstlisting}[language=Kotlin] typealias MyHandler = (Int, String, Any) -> Unit + typealias Predicate = (T) -> Boolean +\end{lstlisting} + + \subsection*{\textbf{4.3 Null safety and variable declarations}} + Kotlin is declared as a null-safe programming language. However, to achieve compatibility with Java, it still supports nullable types. + + + \subsubsection*{\textbf{Recommendation 4.3.1}} -To avoid `NullPointerException` and help compiler to prevent Null Poniter Exceptions, avoid using nullable types (with `?` symbol). +\leavevmode\newline + +To avoid `NullPointerException` and help the compiler prevent Null Pointer Exceptions, avoid using nullable types (with `?` symbol). + + + \textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] val a: Int? = 0 +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] val a: Int = 0 -Nevertheless, if you use Java libraries extensively, you will have to use nullable types and enrich your code with `!!` and `?` symbols. -Avoid using nullable types for Kotlin stdlib (declared in [official documentation](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/)). -Try to use initializers for empty collections. For example, if you want to initialize a list instead of `null` use `emptyList()`. +\end{lstlisting} + + +Nevertheless, when using Java libraries extensively, you have to use nullable types and enrich the code with `!!` and `?` symbols. + +Avoid using nullable types for Kotlin stdlib (declared in [official documentation](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/)). + +Try to use initializers for empty collections. For example, if you want to initialize a list instead of `null`, use `emptyList()`. + + + \textbf{Invalid example}: -val a: List? = null + +\begin{lstlisting}[language=Kotlin] +val a: List? = null +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] val a: List = emptyList() +\end{lstlisting} + + \subsubsection*{\textbf{Recommendation 4.3.2}} +\leavevmode\newline + Like in Java, classes in Kotlin may have type parameters. To create an instance of such a class, we typically need to provide type arguments: -val myVariable: Map = emptyMap() + + + +\begin{lstlisting}[language=Kotlin] +val myVariable: Map = emptyMap() +\end{lstlisting} + + However, the compiler can inherit type parameters from the r-value (value assigned to a variable). Therefore, it will not force users to declare the type explicitly. + These declarations are not recommended because programmers would need to find the return value and understand the variable type by looking at the method. + + + \textbf{Invalid example}: -val myVariable = emptyMap() -val myVariable: Map = emptyMap() + +\begin{lstlisting}[language=Kotlin] +val myVariable = emptyMap() +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] +val myVariable: Map = emptyMap() +\end{lstlisting} + + +\subsubsection*{\textbf{Null-safety}} +\leavevmode\newline + +\subsubsection*{\textbf{4.3.3 Explicit null checks}} +\leavevmode\newline + + + +Try to avoid explicit null checks (explicit comparison with `null`) + +Kotlin is declared as [Null-safe](https://kotlinlang.org/docs/reference/null-safety.html) language. + +However, Kotlin architects wanted Kotlin to be fully compatible with Java; that's why the `null` keyword was also introduced in Kotlin. + + + +There are several code-structures that can be used in Kotlin to avoid null-checks. For example: `?:`, `.let {}`, `.also {}`, e.t.c + + + +\textbf{Invalid example:} + +\begin{lstlisting}[language=Kotlin] +// example 1 +var myVar: Int? = null +if (myVar == null) { + println("null") + return +} + +// example 2 +if (myVar != null) { + println("not null") + return +} + +// example 3 +val anotherVal = if (myVar != null) { + println("not null") + 1 + } else { + 2 + } +// example 4 +if (myVar == null) { + println("null") +} else { + println("not null") +} +\end{lstlisting} + + +\textbf{Valid example:} + +\begin{lstlisting}[language=Kotlin] +// example 1 +var myVar: Int? = null +myVar?: run { + println("null") + return +} + +// example 2 +myVar?.let { + println("not null") + return +} + +// example 3 +val anotherVal = myVar?.also { + println("not null") + 1 + } ?: 2 + +// example 4 +myVar?.let { + println("null") +} ?: run { println("not null") } +\end{lstlisting} + + +\textbf{Exceptions:} + + + +In the case of complex expressions, such as multiple `else-if` structures or long conditional statements, there is common sense to use explicit comparison with `null`. + + + +\textbf{Valid examples:} + + + +\begin{lstlisting}[language=Kotlin] +if (myVar != null) { + println("not null") +} else if (anotherCondition) { + println("Other condition") +} +\end{lstlisting} + + +\begin{lstlisting}[language=Kotlin] +if (myVar == null || otherValue == 5 && isValid) {} +\end{lstlisting} + + +Please also note, that instead of using `require(a != null)` with a not null check - you should use a special Kotlin function called `requireNotNull(a)`. + + + \section*{\textbf{5. Functions}} + \subsection*{\textbf{5.1 Function design}} -You can write clean code by gaining knowledge of how to build design patterns and avoid code smells. -You should utilize this approach, along with functional style, when you write Kotlin code. -The concepts behind functional style are as follows: + +Developers can write clean code by gaining knowledge of how to build design patterns and avoid code smells. + +You should utilize this approach, along with functional style, when writing Kotlin code. + +The concepts behind functional style are as follows: + Functions are the smallest unit of combinable and reusable code. + They should have clean logic, \textbf{high cohesion}, and \textbf{low coupling} to effectively organize the code. + The code in functions should be simple and not conceal the author's original intentions. -Additionally, it should have a clean abstraction, and control statements should be used in a straightforward manner. -The side effects (code that does not affect a function's return value, but affects global/object instance variables) should not be used for state changes of an object. + +Additionally, it should have a clean abstraction, and control statements should be used straightforwardly. + +The side effects (code that does not affect a function's return value but affects global/object instance variables) should not be used for state changes of an object. + The only exceptions to this are state machines. + + + Kotlin is [designed](https://www.slideshare.net/abreslav/whos-more-functional-kotlin-groovy-scala-or-java) to support and encourage functional programming, featuring the corresponding built-in mechanisms. -In addition, standard collections and sequences feature methods that enable functional programming (for example, `apply`, `with`, `let`, and `run`), Kotlin Higher-Order functions, function types, lambdas, and default function arguments. -As [previously discussed], Kotlin supports and encourages the use of immutable types, which in turn motivates programmers to write pure functions that avoid side effects and have a corresponding output for specific input. -The pipeline data flow for the pure function comprises a functional paradigm. It is easy to implement concurrent programming when you have chains of function calls, and each step features the following characteristics: + +Also, it supports standard collections and sequences feature methods that enable functional programming (for example, `apply`, `with`, `let`, and `run`), Kotlin Higher-Order functions, function types, lambdas, and default function arguments (???). + +As [previously discussed], Kotlin supports and encourages the use of immutable types, which in turn motivates programmers to write pure functions that avoid side effects and have a corresponding output for specific input. + +The pipeline data flow for the pure function comprises a functional paradigm. It is easy to implement concurrent programming when you have chains of function calls, where each step features the following characteristics: + +1. Simplicity + 2. Verifiability + 3. Testability + 4. Replaceability + 5. Pluggability + 6. Extensibility + 7. Immutable results + + + There can be only one side effect in this data stream, which can be placed only at the end of the execution queue. + + + \subsubsection*{\textbf{Rule 5.1.1}} +\leavevmode\newline + + + The function should be displayable on one screen and only implement one certain logic. -If a function is too long, it often means that it is complex and be split or made more primitive. Functions should consist of 30 lines (non-empty and non-comment) in total. + +If a function is too long, it often means complex and could be split or simplified. Functions should consist of 30 lines (non-empty and non-comment) in total. + + + \textbf{Exception:} Some functions that implement complex algorithms may exceed 30 lines due to aggregation and comprehensiveness. -Linter warnings for such functions \textbf{can be suppressed}. + +Linter warnings for such functions \textbf{can be suppressed}. + + + Even if a long function works well, new problems or bugs may appear due to the function's complex logic once it is modified by someone else. -Therefore, it is recommended that you split such functions into several separate and shorter functions that are easier to manage. + +Therefore, it is recommended to split such functions into several separate and shorter functions that are easier to manage. + This approach will enable other programmers to read and modify the code properly. + \subsubsection*{\textbf{Rule 5.1.2}} +\leavevmode\newline + + + The nesting depth of a function's code block is the depth of mutual inclusion between the code control blocks in the function (for example: if, for, while, and when). -Each nesting level will increase the amount of effort needed to read the code because you need to remember the current "stack" (for example, entering conditional statements and loops). -\textbf{Exception:} The nesting levels of the lambda expressions, local classes, and anonymous classes in functions are calculated based on the innermost function wheres the nesting levels of enclosing methods are not accumulated. + +Each nesting level will increase the amount of effort needed to read the code because you need to remember the current "stack" (for example, entering conditional statements and loops). + +\textbf{Exception:} The nesting levels of the lambda expressions, local classes, and anonymous classes in functions are calculated based on the innermost function. The nesting levels of enclosing methods are not accumulated. + Functional decomposition should be implemented to avoid confusion for the developer who reads the code. -This will help the reader switch between context. + +This will help the reader switch between contexts. + + + \subsubsection*{\textbf{Rule 5.1.3}} +\leavevmode\newline + Nested functions create a more complex function context, thereby confusing readers. -With nested functions the visibility context may not be evident to the code reader. + +With nested functions, the visibility context may not be evident to the code reader. + + + \textbf{Invalid example}: -fun foo() { - fun nested():String { - return "String from nested function" - } - println("Nested Output: ${nested()}") -} + +\begin{lstlisting}[language=Kotlin] +fun foo() { + fun nested():String { + return "String from nested function" + } + println("Nested Output: ${nested()}") +} +\end{lstlisting} + + \subsection*{\textbf{5.2 Function arguments}} + \subsubsection*{\textbf{Rule 5.2.1}} -With such notation, it is easier to use curly brackets, which in turn leads to better code readability. +\leavevmode\newline + + + +With such notation, it is easier to use curly brackets, leading to better code readability. + + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] // declaration fun myFoo(someArg: Int, myLambda: () -> Unit) { // ... } + // usage -myFoo(1) { +myFoo(1) { println("hey") } +\end{lstlisting} + + \subsubsection*{\textbf{Rule 5.2.2}} +\leavevmode\newline + + + A long argument list is a [code smell](https://en.wikipedia.org/wiki/Code\_smell) that leads to less reliable code. -It is recommended that you reduce the number of parameters. Having \textbf{more than five} parameters leads to difficulties in maintenance and conflicts merging. + +It is recommended to reduce the number of parameters. Having \textbf{more than five} parameters leads to difficulties in maintenance and conflicts merging. + If parameter groups appear in different functions multiple times, these parameters are closely related and can be encapsulated into a single Data Class. + It is recommended that you use Data Classes and Maps to unify these function arguments. + + + \subsubsection*{\textbf{Rule 5.2.3 Use default values for function arguments instead of overloading them}} -In Java, default values for function arguments are prohibited. That is why when you need to create a function with fewer arguments, the function should be overloaded. +\leavevmode\newline + +In Java, default values for function arguments are prohibited. That is why the function should be overloaded when you need to create a function with fewer arguments. + In Kotlin, you can use default arguments instead. + + + \textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] private fun foo(arg: Int) { // ... } + private fun foo() { // ... } +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] private fun foo(arg: Int = 0) { // ... } +\end{lstlisting} \section*{\textbf{6. Classes}} + \subsection*{\textbf{6.1 Classes}} + \subsubsection*{\textbf{Rule 6.1.1}} -In case class contains only one explicit constructor - it should be converted to a primary constructor. +\leavevmode\newline + +In case the class contains only one explicit constructor - it should be converted to a primary constructor. + + + \textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] class Test { var a: Int constructor(a: Int) { this.a = a } } -class Test(var a: Int) { +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] +class Test(var a: Int) { // ... } -// in case of any annotations or modifiers used on constructor: -class Test private constructor(var a: Int) { + +// in case of any annotations or modifiers used on a constructor: +class Test private constructor(var a: Int) { // ... } +\end{lstlisting} + + \subsubsection*{\textbf{Rule 6.1.2}} -Some people say that the data class is a code smell. But if you need to use it, and as a result, your code is becoming more simple, you can use Kotlin `data class`. The main purpose of this class is to hold data, +\leavevmode\newline + +Some people say that the data class is a code smell. However, if you need to use it (which makes your code more simple), you can utilize the Kotlin `data class`. The main purpose of this class is to hold data, + but also `data class` will automatically generate several useful methods: + - equals()/hashCode() pair; + - toString() + - componentN() functions corresponding to the properties in their order of declaration; + - copy() function + + + Therefore, instead of using `normal` classes: + + + +\begin{lstlisting}[language=Kotlin] class Test { var a: Int = 0 get() = field set(value: Int) { field = value} } + class Test { var a: Int = 0 var b: Int = 0 + constructor(a:Int, b: Int) { this.a = a this.b = b } } + // or class Test(var a: Int = 0, var b: Int = 0) + // or class Test() { var a: Int = 0 var b: Int = 0 } +\end{lstlisting} + + \textbf{prefer data classes:} + +\begin{lstlisting}[language=Kotlin] data class Test1(var a: Int = 0, var b: Int = 0) -\textbf{Exception \#1}: Note, that data classes cannot be abstract, open, sealed or inner, that's why these types of classes cannot be changed to a data class. -\textbf{Exception \#2}: No need to convert a class to data class if this class extends some other class or implements an interface. +\end{lstlisting} + + +\textbf{Exception 1}: Note that data classes cannot be abstract, open, sealed, or inner; that is why these types of classes cannot be changed to a data class. + + + +\textbf{Exception 2}: No need to convert a class to a data class if this class extends some other class or implements an interface. + + + \subsubsection*{\textbf{Rule 6.1.3}} -The primary constructor is a part of the class header; it goes after the class name and (optional) type parameters but can be omitted if it is useless. +\leavevmode\newline + +The primary constructor is a part of the class header; it is placed after the class name and type parameters (optional) but can be omitted if it is not used. + + + \textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] // simple case that does not need a primary constructor class Test() { var a: Int = 0 var b: Int = 0 } -// empty primary constructor is not needed here also + +// empty primary constructor is not needed here // it can be replaced with a primary contructor with one argument or removed class Test() { var a = "Property" + init { println("some init") } + constructor(a: String): this() { this.a = a } } -// the good example here is a data class, but this example shows that you should get rid of braces for primary constructor +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] +// the good example here is a data class; this example also shows that you should get rid of braces for the primary constructor class Test { var a: Int = 0 var b: Int = 0 } +\end{lstlisting} + + \subsubsection*{\textbf{Rule 6.1.4}} -The primary constructor cannot contain any code. That's why Kotlin has introduced `init` blocks. -These blocks are used to store the code that should be run during the initialization of the class. -Kotlin allows writing multiple initialization blocks that are executed in the same order as they appear in the class body. +\leavevmode\newline + +The primary constructor cannot contain any code. That is why Kotlin has introduced `init` blocks. + +These blocks store the code to be run during the class initialization. + +Kotlin allows writing multiple initialization blocks executed in the same order as they appear in the class body. + Even when you follow (rule 3.2)[\#r3.2], this makes your code less readable as the programmer needs to keep in mind all init blocks and trace the execution of the code. -So in your code, you should try to use a single `init` block to reduce the complexity. In case you need to do some logging or make some calculations before the assignment -of some class property, you can use powerful functional programming. This will reduce the possibility of the error if your `init` blocks' order is accidentally changed and + +Therefore, you should try to use a single `init` block to reduce the code's complexity. . If you need to do some logging or make some calculations before the class property assignment, you can use powerful functional programming. This will reduce the possibility of the error if your `init` blocks' order is accidentally changed and + make the code logic more coupled. It is always enough to use one `init` block to implement your idea in Kotlin. + + + \textbf{Invalid example}: -class YourClass(var name: String) { + +\begin{lstlisting}[language=Kotlin] +class YourClass(var name: String) { init { println("First initializer block that prints ${name}") } + val property = "Property: ${name.length}".also(::println) + init { println("Second initializer block that prints ${name.length}") } } +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] class YourClass(var name: String) { init { println("First initializer block that prints ${name}") } + val property = "Property: ${name.length}".also { prop -> println(prop) println("Second initializer block that prints ${name.length}") } } -The `init` block was not added to Kotlin to help you initialize your properties; it is needed for more complex tasks. -Therefore if the `init` block contains only assignments of variables - move it directly to properties, so that they will be correctly initialized near the declaration. +\end{lstlisting} + + +The `init` block was not added to Kotlin to help you initialize your properties; it is needed for more complex tasks. + +Therefore if the `init` block contains only assignments of variables - move it directly to properties to be correctly initialized near the declaration. + In some cases, this rule can be in clash with [6.1.1], but that should not stop you. + + + \textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] class A(baseUrl: String) { private val customUrl: String init { customUrl = "$baseUrl/myUrl" } } +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] class A(baseUrl: String) { private val customUrl = "$baseUrl/myUrl" } +\end{lstlisting} + + \subsubsection*{\textbf{Rule 6.1.5}} -This rule is applicable for both interfaces and classes. +\leavevmode\newline + +This rule is applicable to both interfaces and classes. + + + \textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] open class Rectangle { open fun draw() { /* ... */ } } + class Square() : Rectangle() { override fun draw() { super.draw() // no need in super here } } +\end{lstlisting} + + \subsubsection*{\textbf{Rule 6.1.6}} +\leavevmode\newline + Abstract classes are used to force a developer to implement some of its parts in their inheritors. + When the abstract class has no abstract methods, it was set `abstract` incorrectly and can be converted to a regular class. + + + \textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] abstract class NotAbstract { fun foo() {} + fun test() {} } +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] abstract class NotAbstract { abstract fun foo() + fun test() {} } + // OR class NotAbstract { fun foo() {} + fun test() {} } +\end{lstlisting} + + + + \subsubsection*{\textbf{Rule 6.1.7}} +\leavevmode\newline + Kotlin has a mechanism of [backing properties](https://kotlinlang.org/docs/reference/properties.html\#backing-properties). + In some cases, implicit backing is not enough and it should be done explicitly: + +\begin{lstlisting}[language=Kotlin] private var _table: Map? = null val table: Map get() { @@ -1350,85 +3175,177 @@ \subsubsection*{\textbf{Rule 6.1.7}} } return _table ?: throw AssertionError("Set to null by another thread") } -In this case the name of the backing property (`_table`) should be the same as the name of the real property (`table`) but should have an underscore (`_`) prefix. +\end{lstlisting} + + +In this case, the name of the backing property (`_table`) should be the same as the name of the real property (`table`) but should have an underscore (`_`) prefix. + It is one of the exceptions from the [identifier names rule] + + + \subsubsection*{\textbf{Recommendation 6.1.8}} +\leavevmode\newline + Kotlin has a perfect mechanism of [properties](https://kotlinlang.org/docs/reference/properties.html\#properties-and-fields). -Kotlin compiler automatically generates `get` and `set` methods for properties and also provides the possibility to override it. + +Kotlin compiler automatically generates `get` and `set` methods for properties and can override them. + + + \textbf{Invalid example:} + +\begin{lstlisting}[language=Kotlin] class A { var size: Int = 0 set(value) { println("Side effect") field = value } - // user of this class does not expect calling A.size receive size * 2 + // user of this class does not expect calling A.size receive size * 2 get() = field * 2 } +\end{lstlisting} + + From the callee code these methods look like an access to this property: `A().isEmpty = true` for setter and `A().isEmpty` for getter. -However, when `get` and `set` are overridden, it is very confusing for a developer who uses this particular class. -The developer expects to get the property value but receives some unknown value and some extra side-effect hidden by the custom getter/setter. + + + +However, when `get` and `set` are overridden, it is very confusing for a developer who uses this particular class. + +The developer expects to get the property value but receives some unknown value and some extra side-effect hidden by the custom getter/setter. + Use extra functions instead to avoid confusion. + + + + + + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] class A { var size: Int = 0 fun initSize(value: Int) { // some custom logic } - // this will not confuse developer and he will get exactly what he expects + + // this will not confuse developer and he will get exactly what he expects fun goodNameThatDescribesThisGetter() = this.size * 2 } +\end{lstlisting} + + \textbf{Exception:} `Private setters` are only exceptions that are not prohibited by this rule. + + + \subsubsection*{\textbf{Rule 6.1.9}} -If you have ignored [recommendation 6.1.8] you should be careful with using the name of the property in your custom getter/setter +\leavevmode\newline + +If you ignored [recommendation 6.1.8], be careful with using the name of the property in your custom getter/setter + as it can accidentally cause a recursive call and a `StackOverflow Error`. Use the `field` keyword instead. + + + \textbf{Invalid example (very bad)}: + +\begin{lstlisting}[language=Kotlin] var isEmpty: Boolean set(value) { println("Side effect") isEmpty = value } get() = isEmpty +\end{lstlisting} + + \subsubsection*{\textbf{Recommendation 6.1.10 no trivial getters and setters are allowed in the code.}} +\leavevmode\newline + In Java, trivial getters - are the getters that are just returning the field value. + Trivial setters - are merely setting the field with a value without any transformation. -However, in Kotlin, trivial getters/setters are generated by the default. There is no need to use it explicitly for all types of data structures in Kotlin. + +However, in Kotlin, trivial getters/setters are generated by default. There is no need to use it explicitly for all types of data structures in Kotlin. + + + \textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] class A { - var a: Int = 0 + var a: Int = 0 get() = field set(value: Int) { field = value } + // } +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] class A { - var a: Int = 0 + var a: Int = 0 get() = field set(value: Int) { field = value } + // } +\end{lstlisting} + + \subsubsection*{\textbf{Rule 6.1.11}} -In Java, before functional programming became popular, many classes from common libraries used configuration paradigm. +\leavevmode\newline + +In Java, before functional programming became popular, many classes from common libraries used the configuration paradigm. + To use these classes, you had to create an object with the constructor with 0-2 arguments and set the fields needed to run the object. -In Kotlin, to reduce the number of dummy code line and to group objects [`apply` extension](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/apply.html) was added: + +In Kotlin, to reduce the number of dummy code line and to group objects [`apply` extension](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/apply.html) was added: + + + \textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] class HttpClient(var name: String) { var url: String = "" var port: String = "" var timeout = 0 + fun doRequest() {} } + fun main() { val httpClient = HttpClient("myConnection") httpClient.url = "http://example.com" httpClient.port = "8080" httpClient.timeout = 100 + httpCLient.doRequest() -} +} + +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] class HttpClient(var name: String) { var url: String = "" var port: String = "" var timeout = 0 + fun doRequest() {} } + fun main() { val httpClient = HttpClient("myConnection") .apply { @@ -1438,53 +3355,122 @@ \subsubsection*{\textbf{Rule 6.1.11}} } httpClient.doRequest() } +\end{lstlisting} + + \subsection*{\textbf{6.2 Extension functions}} -[Extension functions](https://kotlinlang.org/docs/reference/extensions.html) is a killer-feature in Kotlin. + +[Extension functions](https://kotlinlang.org/docs/reference/extensions.html) is a killer-feature in Kotlin. + It gives you a chance to extend classes that were already implemented in external libraries and help you to make classes less heavy. + Extension functions are resolved statically. + + + \subsubsection*{\textbf{Recommendation 6.2.1}} +\leavevmode\newline + It is recommended that for classes, the non-tightly coupled functions, which are rarely used in the class, should be implemented as extension functions where possible. + They should be implemented in the same class/file where they are used. This is a non-deterministic rule, so the code cannot be checked or fixed automatically by a static analyzer. + + + \subsubsection*{\textbf{Rule 6.2.2}} +\leavevmode\newline + As extension functions are resolved statically. In this case, there could be a situation when a developer implements two extension functions: one is for the base class and another for the inheritor. + This can lead to an issue when an incorrect method is used. -And that can lead to an issue when incorrect method is used. + +And that can lead to an issue when incorrect method is used. + + + \textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] open class A class B: A() + // two extension functions with the same signature fun A.foo() = "A" fun B.foo() = "B" + fun printClassName(s: A) { println(s.foo()) } + // this call will run foo() method from the base class A, but // programmer can expect to run foo() from the class inheritor B fun main() { printClassName(B()) } +\end{lstlisting} + + \subsection*{\textbf{6.3 Interfaces}} + An `Interface` in Kotlin can contain declarations of abstract methods, as well as method implementations. What makes them different from abstract classes is that interfaces cannot store state. + They can have properties, but these need to be abstract or to provide accessor implementations. + + + Kotlin's interfaces can define attributes and functions. + In Kotlin and Java, the interface is the main presentation means of application programming interface (API) design and should take precedence over the use of (abstract) classes. + + + \subsection*{\textbf{6.4 Objects}} + \subsubsection*{\textbf{Rule 6.4.1}} +\leavevmode\newline + As described in [6.2 Extension functions], extension functions are a powerful. Instead of using utility classes/objects, use it extention functions. -This allows you to avoid unnecessary complexity and class/object wrapping and use top-level functions instead. + +This enables you to avoid unnecessary complexity and class/object wrapping and use top-level functions instead. + + + \textbf{Invalid example}: + +\begin{lstlisting}[language=Kotlin] object StringUtil { fun stringInfo(myString: String): Int { return myString.count{ "something".contains(it) } } } StringUtil.stringInfo("myStr") +\end{lstlisting} + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] fun String.stringInfo(): Int { return this.count{ "something".contains(it) } } + "myStr".stringInfo() +\end{lstlisting} + + \subsubsection*{\textbf{Recommendation 6.4.2}} -Kotlin’s objects are extremely useful when you need to implement some interface from an external library that doesn’t have any state. +\leavevmode\newline + +Kotlin’s objects are extremely useful when you need to implement some interface from an external library that does not have any state. + There is no need to use classes for such structures. + + + +\textbf{Valid example}: + +\begin{lstlisting}[language=Kotlin] interface I { fun foo() } + object O: I { override fun foo() {} -} \ No newline at end of file +} +\end{lstlisting} \ No newline at end of file From 3b5fe5cd06936f217cac9d3e374b8b6a380570c7 Mon Sep 17 00:00:00 2001 From: soWhoAmI Date: Wed, 16 Dec 2020 16:28:52 +0300 Subject: [PATCH 3/5] feature/wp-update ### What's done: * Fixed bugs --- .../kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt b/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt index 17ed549f66..93eaa0146c 100644 --- a/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt +++ b/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt @@ -130,6 +130,7 @@ private fun generateCodeStyle() { appendixFileLines.removeAll(appendixFileLines.subList(appendixFileLines.indexOf("\\lstMakeShortInline[basicstyle=\\ttfamily\\bfseries]`"), appendixFileLines.lastIndex + 1)) appendixFileLines.addAll(tempFile.readLines()) File("wp/sections/appendix.tex").writeText(appendixFileLines.joinToString(separator = "\n")) + tempFile.delete() } /** From 0e57c3675bf5b8e5be56e2b78b191a00eb9debfa Mon Sep 17 00:00:00 2001 From: aktsay6 Date: Wed, 16 Dec 2020 18:28:10 +0300 Subject: [PATCH 4/5] feature/wp-update ### What's done: * Fixed bug --- .../ruleset/generation/GenerationDocs.kt | 6 +- info/guide/diktat-coding-convention.md | 346 +++++++------- wp/sections/appendix.tex | 447 +++++++++--------- 3 files changed, 415 insertions(+), 384 deletions(-) diff --git a/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt b/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt index 93eaa0146c..c7050a3540 100644 --- a/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt +++ b/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt @@ -54,9 +54,9 @@ private fun generateCodeStyle() { if (name.isNullOrEmpty() || number.isNullOrEmpty()) { if (number.isNullOrEmpty() && name.isNullOrEmpty()) { when (line.takeWhile { it == '#' }.count()) { - 1 -> writer.writeln("""\section*{\textbf{${line.removePrefix("#").trim()}}}""") - 2 -> writer.writeln("""\subsection*{\textbf{${line.removePrefix("##").trim()}}}""") - 3 -> writer.writeln("""\subsubsection*{\textbf{${line.removePrefix("###").trim()}}}${"\n"}\leavevmode\newline""") + 2 -> writer.writeln("""\section*{\textbf{${line.removePrefix("##").trim()}}}""") + 3 -> writer.writeln("""\subsection*{\textbf{${line.removePrefix("###").trim()}}}""") + 4 -> writer.writeln("""\subsubsection*{\textbf{${line.removePrefix("####").trim()}}}${"\n"}\leavevmode\newline""") else -> {} } continue diff --git a/info/guide/diktat-coding-convention.md b/info/guide/diktat-coding-convention.md index 49a71cc5ec..c1ccc17968 100644 --- a/info/guide/diktat-coding-convention.md +++ b/info/guide/diktat-coding-convention.md @@ -1,22 +1,3 @@ - - -# Diktat Coding Convention - -### Content - -| Chapter | Content | -| ------------------- | ------------------------------------------------------------ | -| [0. Preface](#c0.1) | [Purpose](#c0.1), [General principles](#c0.2), [Terminology](#c0.3), [Exceptions](#c0.4) | -| [1. Naming](#c1) | [Identifiers](#c1.1), [Package names](#c1.2), [Classes, enumeration and interfaces](#c1.3), [Functions](#c1.4), [Constants](#c1.5), [Variables](#c1.6) | -| [2. Docs](#c2) | [Kdoc](#c2.1), [File header](#c2.2), [Comments on function header ](#c2.3), [Code comments](#c2.4) | -| [3. General formatting](#c3) | [File-related rules](#c3.1), [Braces](#c3.2), [Indentation](#c3.3), [Empty blocks](#c3.4), [Line length](#c3.5), [Line breaks (newlines)](#c3.6), [Blank lines](#c3.7), [Horizontal space](#c3.8), [Enumerations](#c3.9), [Variable declaration](#c3.10), [When expression](#c3.11), [Annotations](#c3.12), [Layout of comments](#c3.13), [Modifiers and constant values](#c3.14), [Strings](#c3.15)| -| [4. Variables and types](#c4) | [Variables](#c4.1), [Types](#c4.2), [Null safety and variable declarations](#4.3)| -| [5. Functions](#c5) | [Function design](#c5.1), [Function arguments](#c5.2)| -| [6. Classes](#c6) | [Classes](#c6.1), [Extension functions](#c6.2), [Interfaces](#c6.3), [Objects](#c6.4) | -| [7. Kotlin & Java](#c7) | | - - - ## Preface ### Purpose of this document @@ -88,7 +69,8 @@ Note: The source file encoding format (including comments) must be UTF-8 only. T ### 1.1 Identifier names -### Rule 1.1.1: Identifiers naming conventions +This section describes the general rules for naming identifiers. +#### 1.1.1 Identifiers naming conventions For identifiers, use the following naming conventions: 1. All identifiers should use only ASCII letters or digits, and the names should match regular expressions `\w{2,64}`. @@ -149,7 +131,8 @@ Note that prefixing can also negatively affect the style and the auto-generation ### 1.2 Packages names -### Rule 1.2.1: Package names dots + +#### Rule 1.2.1 Package names dots Package names are in lower case and separated by dots. Code developed within your company should start with `your.company.domain.` Numbers are permitted in package names. Each file should have a `package` directive. Package names are all written in lowercase, and consecutive words are concatenated together (no underscores). Package names should contain both the product or module names and the department (or team) name to prevent conflicts with other teams. Numbers are not permitted. For example: `org.apache.commons.lang3`, `xxx.yyy.v2`. @@ -167,7 +150,8 @@ package your.company.domain.mobilecontrol.views ### 1.3 Classes, enumerations, interfaces -### Rule 1.3.1: Classes, enumerations, interface names use Camel case +This section describes the general rules for naming classes, enumerations, and interfaces. +### 1.3.1 Classes, enumerations, interface names use Camel case Classes, enumerations, and interface names use `UpperCamelCase` nomenclature. Follow the naming rules described below: 1. A class name is usually a noun (or a noun phrase) denoted using the camel case nomenclature, such as UpperCamelCase. For example: `Character` or `ImmutableList`. An interface name can also be a noun or noun phrase (such as `List`) or an adjective or adjective phrase (such as `Readable`). @@ -193,7 +177,8 @@ class Order {} ### 1.4 Functions -### Rule 1.4.1: Function names should be in camel case +This section describes the general rules for naming functions. +### 1.4.1 Function names should be in camel case Function names should use `lowerCamelCase` nomenclature. Follow the naming rules described below: 1. Function names are usually verbs or verb phrases denoted with the camel case nomenclature (`lowerCamelCase`). For example: `sendMessage`, `stopProcess`, or `calculateValue`. @@ -240,20 +225,17 @@ fun draw() fun addKeyListener(Listener) ``` -2. An underscore (`_`) can be included in the JUnit test function name and should be used as a separator. Each logical part denoted in `lowerCamelCase`, for example, a typical pattern of using underscore: `pop_emptyStack`. +2. An underscore (`_`) can be included in the JUnit test function name and should be used as a separator. Each logical part is denoted in `lowerCamelCase`, for example, a typical pattern of using underscore: `pop_emptyStack`. ### 1.5 Constants -### Rule 1.5.1 Constant names should be in UPPER case, words in the name are separated by underscore -Constant names should be in UPPER case, words separated by underscore. The jeneral constant naming conventions are listed below: -1. Constants are attributes created with the `const` keyword, or top-level/`val` local variables of an object that holds immutable data. In most cases, constants can be identified as a `const val` property from the `object`/`companion object`/file top level. These variables contain a fixed constant values that typically should never be changed by programmers. This includes basic types, strings, immutable types, and immutable collections of immutable types. The value is not constant for the object, which state can be changed. - -2. Constant names should contain only uppercase letters separated by underscores. They should have a `val` or `const val` (`const` should be used only with primitive types) modifier to make them final (immutable) explicitly. In most cases, if you need to specify a constant value, then you need to create it with the `const val` modifier. Note that not all `val` variables are constants. - +This section describes the general rules for naming constraints. +### 1.5.1 Using UPPER case and underscore characters in a constraint name +Constant names should be in UPPER case, words separated by underscore. The general constant naming conventions are listed below: +1. Constants are attributes created with the `const` keyword or top-level/`val` local variables of an object that holds immutable data. In most cases, constants can be identified as a `const val` property from the `object`/`companion object`/file top level. These variables contain fixed constant values that typically should never be changed by programmers. This includes basic types, strings, immutable types, and immutable collections of immutable types. The value is not constant for the object, which state can be changed. +2. Constant names should contain only uppercase letters separated by an underscores. They should have a val or const val modifier to make them final explicitly. In most cases, if you need to specify a constant value, then you need to create it with the "const val" modifier. Note that not all `val` variables are constants. 3. Objects with immutable content, such as `Logger` and `Lock`, can be in uppercase as constants or have camel case as regular variables. - 4. Use meaningful constants instead of `magic numbers`. SQL or logging strings should not be treated as magic numbers, nor should they be defined as string constants. - -Magic constants like `NUM_FIVE = 5` or `NUM_5 = 5` should not be treated as constants. This is because mistakes will easily be made if they are changed to `NUM_5 = 50` or 55. +Magic constants, such as `NUM_FIVE = 5` or `NUM_5 = 5` should not be treated as constants. This is because mistakes will easily be made if they are changed to `NUM_5 = 50` or 55. These constants typically represent business logic values, such as measures, capacity, scope, location, tax rate, promotional discounts, and power base multiples in algorithms. You can avoid using magic numbers with the following method: - Using library functions and APIs. For example, instead of checking that `size == 0`, use `isEmpty()` function. To work with `time`, use built-ins from `java.time API`. @@ -275,7 +257,8 @@ const val String APPLICATION_NAME = "Launcher"; ### 1.6 Non-constant fields (variables) -### Rule 1.6.1: Non-constant field name +This section describes the general rules for naming variables. +### 1.6.1 Non-constant field name Non-constant field names should use camel case and start with a lowercase letter. A local variable cannot be treated as constant even if it is final and immutable. Therefore, it should not use the preceding rules. Names of collection type variables (sets, lists, etc.) should contain plural nouns. For example: `var namesList: List` @@ -295,9 +278,9 @@ val users: List = listOf(); val mutableCollection: MutableSet = HashSet() ``` -### Rule 1.6.2: Boolean variable names with negative meaning +### 1.6.2 Boolean variable names with negative meaning -Avoid using Boolean variable names with a negative meaning. When using a logical operator and name with negative meaning, the code may be difficult to understand, which is referred to as the "double negative". +Avoid using Boolean variable names with a negative meaning. When using a logical operator and name with a negative meaning, the code may be difficult to understand, which is referred to as the "double negative". For instance, it is not easy to understand the meaning of !isNotError. The JavaBeans specification automatically generates isXxx() getters for attributes of Boolean classes. However, not all methods returning Boolean type have this notation. @@ -331,8 +314,8 @@ Comments should accurately reflect the code's design ideas and logic and further As a result, other programmers will be able to save time when trying to understand the code. Imagine that you are writing the comments to help yourself to understand the original ideas behind the code in the future. -### 2.1 General form of Kdoc - +### 2.1 General form of Kdoc + KDoc is a combination of JavaDoc's block tags syntax (extended to support specific constructions of Kotlin) and Markdown's inline markup. The basic format of KDoc is shown in the following example: @@ -353,13 +336,14 @@ It is also shown in the following single-line form: ``` Use a single-line form when you store the entire KDoc block in one line (and there is no KDoc mark @XXX). For detailed instructions on how to use KDoc, refer to [Official Document](https://docs.oracle.com/en/Kotlin/Kotlinse/11/tools/KDoc.html). -### Rule 2.1.1: KDoc is used for each public, protected or internal code element +#### 2.1.1 Using KDoc for the public, protected, or internal code elements At a minimum, KDoc should be used for every public, protected, or internal decorated class, interface, enumeration, method, and member field (property). Other code blocks can also have KDocs if needed. Instead of using comments or KDocs before properties in the primary constructor of a class - use `@property` tag in a KDoc of a class. All properties of the primary constructor should also be documented in a KDoc with a `@property` tag. + **Incorrect example:** ```kotlin /** @@ -390,9 +374,9 @@ class Example( **Exceptions:** -1. For setters/getters of properties, obvious comments (like `this getter returns field`) are optional. Note that Kotlin generates simple `get/set` methods under the hood. +* For setters/getters of properties, obvious comments (like `this getter returns field`) are optional. Note that Kotlin generates simple `get/set` methods under the hood. -2. It is optional to add comments for simple one-line methods, such as shown in the example below: +* It is optional to add comments for simple one-line methods, such as shown in the example below: ```kotlin val isEmpty: Boolean get() = this.size == 0 @@ -404,11 +388,13 @@ or fun isEmptyList(list: List) = list.size == 0 ``` -Note: You can skip KDocs for a method's override if it is almost the same as the superclass method. +**Note:** You can skip KDocs for a method's override if it is almost the same as the superclass method. -### Rule 2.1.2: When the method has arguments, return value, can throw exceptions, etc., it must be described in the KDoc block: with @param, @return, @throws, etc. +#### 2.1.2 Describing methods that have arguments, a return value, or can throw an exception in the KDoc block -**Valid examples**: +When the method has such details as arguments, return value, or can throw exceptions, it must be described in the KDoc block (with @param, @return, @throws, etc.). + +**Valid examples:** ```kotlin /** @@ -419,7 +405,7 @@ Note: You can skip KDocs for a method's override if it is almost the same as the protected abstract class Sample { /** * This is a long comment with whitespace that should be split in - * comments on multiple lines in case the line comment formatting is enabled. + * comments on multiple lines if the line comment formatting is enabled. * / * Add a blank line between the comment text and each KDoc tag underneath * / * @param fox A quick brown fox jumps over the lazy dog * @return battle between fox and dog @@ -441,7 +427,8 @@ Note: You can skip KDocs for a method's override if it is almost the same as the } ``` -### Rule 2.1.3: Only one space between the Kdoc tag and content. Tags are arranged in the order. +#### 2.1.3 Only one space between the Kdoc tag and content. Tags are arranged in the order. + There should be only one space between the Kdoc tag and content. Tags are arranged in the following order: @param, @return, and @throws. Therefore, Kdoc should contain the following: @@ -487,12 +474,17 @@ Other KDoc tags (such as @param type parameters and @see.) can be added as follo * @since 1.6 */ ``` -### 2.2 Comments to the file header -### Rule 2.2.1: Comments on the file header must include copyright information, without the creation date and author's name (use VCS for history management instead). The content inside files that contain multiple or no classes should also be described. +### 2.2 Adding comments on the file header + +This section describes the general rules of adding comments on the file header. Comments on the file header should be placed before the package name and imports. If you need to add more content to the comment, subsequently add it in the same format. -The following examples for Huawei describe the format of the **copyright license**: \ +Comments on the file header must include copyright information, without the creation date and author's name (use VCS for history management). Also, describe the content inside files that contain multiple or no classes. + +Place comments on the file header before the package name and imports. If you need to add more content to the comment, subsequently add it in the same format. + +The following examples for Huawei describe the format of the *copyright license*: \ Chinese version: `版权所有 (c) 华为技术有限公司 2012-2020` \ English version: `Copyright (c) Huawei Technologies Co., Ltd. 2012-2020. All rights reserved.` @@ -519,12 +511,11 @@ The following factors should be considered when writing the file header or comme - Maintain a unified format. The specific format can be formulated by the project (for example, if you use an existing opensource project), and you need to follow it. - A top-level file-Kdoc must include a copyright and functional description, especially if there is more than one top-level class. - Do not include empty comment blocks. If there is no content after the option `@apiNote`, the entire tag block should be deleted. -- The industry practice is not to include historical information in comments. The corresponding history can be found in VCS (git, svn, etc.). Therefore, it is not recommended to include historical data in the comments of the Kotlin source code. - +- The industry practice is not to include historical information in the comments. The corresponding history can be found in VCS (git, svn, etc.). Therefore, it is not recommended to include historical data in the comments of the Kotlin source code. ### 2.3 Comments on the function header -### Rule 2.3.1: Do not make unnecessary and useless comments. -Comments on the function header are placed above function declarations or definitions. A newline should not exist between a function declaration and its Kdoc. Use the preceding [KDoc](#c2.1) style rules. + +Comments on the function header are placed above function declarations or definitions. A newline should not exist between a function declaration and its Kdoc. Use the preceding <> style rules. As stated in Chapter 1, the function name should reflect its functionality as much as possible. Therefore, in the Kdoc, try to describe the functionality that is not mentioned in the function name. Avoid unnecessary comments on dummy coding. @@ -532,13 +523,18 @@ Avoid unnecessary comments on dummy coding. The function header comment's content is optional, but not limited to function description, return value, performance constraints, usage, memory conventions, algorithm implementation, reentrant requirements, etc. ### 2.4 Code comments -### Rule 2.4.1: Add a blank line between the body of the comment and Kdoc tag-blocks. + +This section describes the general rules of adding code comments. + +#### 2.4.1 Add a blank line between the body of the comment and Kdoc tag-blocks. + It is a good practice to add a blank line between the body of the comment and Kdoc tag-blocks. Also, consider the following rules: -- There must be one space between the comment character and the content of the comment -- There must be a newline between a Kdoc and presiding code +- There must be one space between the comment character and the content of the comment. +- There must be a newline between a Kdoc and the presiding code. - An empty line should not exist between a Kdoc and the code it is describing. You do not need to add a blank line before the first comment in a particular namespace (code block) (for example, between the function declaration and first comment in a function body). **Valid Examples:** + ```kotlin /** * This is the short overview comment for the example interface. @@ -585,6 +581,7 @@ Compared to Java, the `if` statement in Kotlin statements returns a value. For t **Valid examples:** ```kotlin + val foo = 100 // right-side comment val bar = 200 /* right-side comment */ @@ -606,14 +603,16 @@ val someVal = if (nr % 15 == 0) { } ``` -- Start all comments (including KDoc) with space after the first symbol (`//`, `/*`, `/**` and `*`) +- Start all comments (including KDoc) with a space after the first symbol (`//`, `/*`, `/**` and `*`) **Valid example:** + ```kotlin val x = 0 // this is a comment ``` -### Rule 2.4.2: Do not comment on unused code blocks +#### 2.4.2 Do not comment on unused code blocks + Do not comment on unused code blocks, including imports. Delete these code blocks immediately. A code is not used to store history. Git, svn, or other VCS tools should be used for this purpose. Unused imports increase the coupling of the code and are not conducive to maintenance. The commented out code cannot be appropriately maintained. @@ -621,12 +620,14 @@ In an attempt to reuse the code, there is a high probability that you will intro The correct approach is to delete the unnecessary code directly and immediately when it is not used anymore. If you need the code again, consider porting or rewriting it as changes could have occurred since you first commented on the code. -### Recommendation 2.4.3: Code delivered to the client should not contain TODO/FIXME comments. +#### 2.4.3 Code delivered to the client should not contain TODO/FIXME comments + The code officially delivered to the client typically should not contain TODO/FIXME comments. `TODO` comments are typically used to describe modification points that need to be improved and added. For example, refactoring FIXME comments are typically used to describe known defects and bugs that will be subsequently fixed and are not critical for an application. -They should all have a unified style to facilitate the unified text search processing. +They should all have a unified style to facilitate unified text search processing. + +**Example:** -**Example**: ```kotlin // TODO(): Jira-XXX - support new json format // FIXME: Jira-XXX - fix NPE in this code block @@ -636,13 +637,14 @@ At a version development stage, these annotations can be used to highlight the i # 3. General formatting (typesetting) ### 3.1 File-related rules -### Rule 3.1.1: Avoid files that are too long. Files should not exceed 2000 lines (non-empty and non-commented lines). +This section describes the rules related to using files in your code. +#### 3.1.1 Avoid files that are too long -If the file is too long and complex, it should be split into smaller files, functions, or modules. +If the file is too long and complicated, it should be split into smaller files, functions, or modules. Files should not exceed 2000 lines (non-empty and non-commented lines). It is recommended to horizontally or vertically split the file according to responsibilities or hierarchy of its parts. The only exception to this rule is code generation - the auto-generated files that are not manually modified can be longer. -### Rule 3.1.2: Code blocks in the source file should be separated by one blank line and should be in the proper order. +#### 3.1.2 Code blocks in the source file should be separated by one blank line A source file contains code blocks in the following order: copyright, package name, imports, and top-level classes. They should be separated by one blank line. a) Code blocks should be in the following order: @@ -657,11 +659,11 @@ b) Each of the preceding code blocks should be separated by a blank line. c) Import statements are alphabetically arranged, without using line breaks and wildcards ( wildcard imports - `*`). -d) **Recommendation**. One `.kt` source file should contain only one class declaration, and its name should match the filename +d) **Recommendation**: One `.kt` source file should contain only one class declaration, and its name should match the filename e) Avoid empty files that do not contain the code or contain only imports/comments/package name -### Recommendation 3.1.3: Import statements order. +#### 3.1.3 Import statements order From top to bottom, the order is the following: 1. Android @@ -691,9 +693,8 @@ import kotlin.system.exitProcess // kotlin standard library import kotlinx.coroutines.* // official kotlin extension library ``` -### Recommendation 3.1.4: The declaration parts of class-like code structures (class, interface, etc.) should be placed in the order. +#### 3.1.4 Order of declaration parts of class-like code structures The declaration parts of class-like code structures (class, interface, etc.) should be in the following order: compile-time constants (for objects), class properties, late-init class properties, init-blocks, constructors, public methods, internal methods, protected methods, private methods, and companion object. Blank lines should separate their declaration. - Notes: 1. There should be no blank lines between properties with the following **exceptions**: when there is a comment before a property on a separate line or annotations on a separate line. 2. Properties with comments/Kdoc should be separated by a newline before the comment/Kdoc. @@ -706,15 +707,16 @@ The declaration part of a class or interface should be in the following order: - Init-blocks - Constructors - Methods or nested classes. Put nested classes next to the code they are used by. -If the classes are meant to be used externally and are not referenced inside the class, put them after the companion object. +If the classes are meant to be used externally, and are not referenced inside the class, put them after the companion object. - Companion object **Exception:** -All variants of a `(private) val` logger should be placed in the beginning of the class (`(private) val log`, `LOG`, `logger`, etc.). +All variants of a `(private) val` logger should be placed at the beginning of the class (`(private) val log`, `LOG`, `logger`, etc.). ### 3.2 Braces -### Rule 3.2.1: Braces must be used in conditional statements and loop blocks. +This section describes the general rules of using braces in your code. +#### 3.2.1 Using braces in conditional statements and loop blocks Braces should always be used in `if`, `else`, `for`, `do`, and `while` statements, even if the program body is empty or contains only one statement. In special Kotlin `when` statements, you do not need to use braces for single-line statements. @@ -754,8 +756,8 @@ if (condition) { } ``` -### Rule 3.2.2 For *non-empty* blocks and block structures, the opening brace is placed at the end of the line - +#### 3.2.2 Opening braces are placed at the end of the line in *non-empty* blocks and block structures +For *non-empty* blocks and block structures, the opening brace is placed at the end of the line. Follow the K&R style (1TBS or OTBS) for *non-empty* code blocks with braces: - The opening brace and first line of the code block are on the same line. - The closing brace is on its own new line. @@ -813,12 +815,11 @@ do { ### 3.3 Indentation -### Rule 3.3.1: Use spaces for indentation. Each indentation equals four spaces. Only spaces are permitted for indentation, and each indentation should equal `four spaces` (tabs are not permitted). If you prefer using tabs, simply configure them to change to spaces in your IDE automatically. These code blocks should be indented if they are placed on the new line, and the following conditions are met: -- The code block is placed immediately after an opening brace +- The code block is placed immediately after an opening brace. - The code block is placed after each operator, including the assignment operator (`+`/`-`/`&&`/`=`/etc.) - The code block is a call chain of methods: ```kotlin @@ -844,7 +845,7 @@ b) Arguments in argument lists can be aligned if they are on different lines. 3. Eight spaces are used for functional-like styles when the newline is placed before the dot. -4. Super type lists: \ +4. Supertype lists: \ a) Four spaces are used if the colon before the supertype list is on a new line. \ b) Four spaces are used before each supertype, and eight spaces are used if the colon is on a new line. @@ -888,9 +889,8 @@ class A ### 3.4 Empty blocks -### Recommendation 3.4.1: Avoid empty blocks, and ensure braces start on a new line. -An empty code block can be closed immediately on the same line and the next line. However, a newline is recommended between opening and closing braces `{}` (see the examples below.) +Avoid empty blocks, and ensure braces start on a new line. An empty code block can be closed immediately on the same line and the next line. However, a newline is recommended between opening and closing braces `{}` (see the examples below.) Generally, empty code blocks are prohibited; using them is considered a bad practice (especially for catch block). They are only appropriate for overridden functions when the base class's functionality is not needed in the class-inheritor. @@ -925,10 +925,9 @@ try { ### 3.5 Line length -### Recommendation 3.5.1: Line length should be less than 120 symbols. -The international code style prohibits `non-Latin` (`non-ASCII`) symbols. -(See [Rule 1.1.1: Identifiers](#r1.1.1)) However, if you still intend on using them, follow the following convention: +Line length should be less than 120 symbols. The international code style prohibits `non-Latin` (`non-ASCII`) symbols. +(See [Identifiers](#r1.1.1)) However, if you still intend on using them, follow the following convention: - One wide character occupies the width of two narrow characters. The "wide" and "narrow" parts of a character are defined by its [east Asian width Unicode attribute](https://unicode.org/reports/tr11/). @@ -947,7 +946,8 @@ Each one of these characters represents two narrow characters. ### 3.6 Line breaks (newlines) -### Recommendation 3.6.1: Each line can have a maximum of one statement. +This section contains the rules and recommendations on using line breaks. +#### 3.6.1 Each line can have a maximum of one statement. Each line can have a maximum of one code statement. This recommendation prohibits the use of code with `;` because it decreases code visibility. **Invalid example:** @@ -961,7 +961,7 @@ val a = "" val b = "" ``` -### Rule 3.6.2: Rules for line-breaking +#### 3.6.2 Rules for line-breaking 1) Unlike Java, Kotlin allows you not to put a semicolon (`;`) after each statement separated by a newline character. There should be no redundant semicolon at the end of the lines. @@ -1076,7 +1076,7 @@ fun foo( } ``` -8) If the supertype list has more than two elements, they should be separated by newlines +8) If the supertype list has more than two elements, they should be separated by newlines. **Valid example:** ```kotlin @@ -1087,11 +1087,10 @@ class MyFavouriteVeryLongClassHolder : ``` -### 3.7 Blank lines -### Recommendation 3.7.1: Reduce unnecessary blank lines and maintain a compact code size +### 3.7 Using blank lines -By reducing unnecessary blank lines, you can display more code on one screen, which improves code readability. -- Blank lines should separate content based on relevance and should be placed between groups of fields, constructors, methods, nested classes, `init` blocks, and objects (see [Rule 3.1.2](#r3.1.2)). +Reduce unnecessary blank lines and maintain a compact code size. By reducing unnecessary blank lines, you can display more code on one screen, which improves code readability. +- Blank lines should separate content based on relevance and should be placed between groups of fields, constructors, methods, nested classes, `init` blocks, and objects (see [3.1.2](#r3.1.2)). - Do not use more than one line inside methods, type definitions, and initialization expressions. - Generally, do not use more than two consecutive blank lines in a row. - Do not put newlines in the beginning or end of code blocks with curly braces. @@ -1108,14 +1107,17 @@ fun baz() { ### 3.8 Horizontal space -### Rule 3.8.1: Usage of whitespace for code separation +This section describes general rules and recommendations for using spaces in the code. +#### 3.8.1: Usage of whitespace for code separation + +Follow the recommendations below for using space to separate keywords: -**Note:** This recommendation is for the cases where symbols are located on the same line. However, in some cases, a line break could be used instead of a space (described in another rule.) +**Note:** These recommendations are for cases where symbols are located on the same line. However, in some cases, a line break could be used instead of a space. -1. Separate keywords like `if`, `when`, `for`, e.t.c. from the opening parenthesis with single whitespace. +1. Separate keywords (such as `if`, `when`, `for`) from the opening parenthesis with single whitespace. The only exception is the `constructor` keyword, which should not be separated from the opening parenthesis. -2. Separate keywords like `else` or `try` from the opening brace (`{`) with a single whitespace. +2. Separate keywords like `else` or `try` from the opening brace (`{`) with single whitespace. If `else` is used in a ternary-style statement without braces, there should be a single space between `else` and the statement after: `if (condition) foo() else bar()` 3. Use a **single** whitespace before all opening braces (`{`). The only exception is the passing of a lambda as a parameter inside parentheses: @@ -1124,7 +1126,7 @@ fun baz() { foo({x: Int -> x}, 5) // no space before '{' ``` -4. A single whitespace should be placed on both sides of binary operators. This also applies to operator-like symbols. +4. Single whitespace should be placed on both sides of binary operators. This also applies to operator-like symbols. For example: - A colon in generic structures with the `where` keyword: `where T : Type` @@ -1142,14 +1144,15 @@ fun baz() { `1..100` 5. Use spaces after (`,`), (`:`), and (`;`), except when the symbol is at the end of the line. - However, note that this code style prohibits the use of (`;`) in the middle of a line ([Rule 3.2.2](#r3.2.2)). + However, note that this code style prohibits the use of (`;`) in the middle of a line ([see 3.3.2](#r3.2.2)). There should be no whitespaces at the end of a line. The only scenario where there should be no space after a colon is when the colon is used in the annotation to specify a use-site target (for example, `@param:JsonProperty`). There should be no spaces before `,` , `:` and `;`. - **Exceptions** for spaces and colons are the following: - - when `:` is used to separate a type and a supertype, including an anonymous object (after object keyword) - - when delegating to a superclass constructor or different constructor of the same class + **Exceptions** for spaces and colons: + + - When `:` is used to separate a type and a supertype, including an anonymous object (after object keyword) + - When delegating to a superclass constructor or different constructor of the same class **Valid example:** ```kotlin @@ -1168,7 +1171,7 @@ If the type is nullable, there should be no space before `?`. 7. When using `[]` operator (`get/set`) there should be **no** spaces between identifier and `[` : `someList[0]`. 8. There should be no space between a method or constructor name (both at declaration and at call site) and a parenthesis: - `foo() {}`. Note that this sub-rule is related only to spaces; the rules for whitespaces are described in [Rule 3.6.2](#r3.6.2). + `foo() {}`. Note that this sub-rule is related only to spaces; the rules for whitespaces are described in [see 3.6.2](#r3.6.2). This rule does not prohibit, for example, the following code: ```kotlin fun foo @@ -1181,20 +1184,20 @@ fun foo 10. There should be no spaces between a prefix/postfix operator (like `!!` or `++`) and its operand. -### Recommendation 3.8.2: No spaces should be inserted for horizontal alignment. +#### 3.8.2: No spaces for horizontal alignment *Horizontal alignment* refers to aligning code blocks by adding space to the code. Horizontal alignment should not be used because: - When modifying code, it takes much time for new developers to format, support, and fix alignment issues. - Long identifier names will break the alignment and lead to less presentable code. -- There are more disadvantages than advantages in alignment. To reduce maintenance costs, the best choice is not to use horizontal alignment. +- There are more disadvantages than advantages in alignment. To reduce maintenance costs, misalignment (???) is the best choice. Recommendation: Alignment only looks suitable for `enum class`, where it can be used in table format to improve code readability: ```kotlin enum class Warnings(private val id: Int, private val canBeAutoCorrected: Boolean, private val warn: String) : Rule { PACKAGE_NAME_MISSING (1, true, "no package name declared in a file"), PACKAGE_NAME_INCORRECT_CASE (2, true, "package name should be completely in a lower case"), - PACKAGE_NAME_INCORRECT_PREFIX(3, false, "package name should start from company's domain") + PACKAGE_NAME_INCORRECT_PREFIX(3, false, "package name should start from the company's domain") ; } ``` @@ -1213,8 +1216,9 @@ enum class Warnings(private val id: Int, private val canBeAutoCorrected: Boolean ### 3.9 Enumerations -### Recommendation 3.9.1: Enum values are separated by a comma and line break, with ';' placed on the new line. -1) Enum values are separated by a comma and a line break. `;` is put on the new line: +Enum values are separated by a comma and line break, with ';' placed on the new line. + +1) The comma and line break characters separate enum values. Put `;` on the new line: ```kotlin enum class Warnings { A, @@ -1225,7 +1229,7 @@ enum class Warnings { ``` This will help to resolve conflicts and reduce the number of conflicts during merging pull requests. -Also use [trailing comma](https://kotlinlang.org/docs/reference/whatsnew14.html#trailing-comma). +Also, use [trailing comma](https://kotlinlang.org/docs/reference/whatsnew14.html#trailing-comma). 2) If the enum is simple (no properties, methods, and comments inside), you can declare it in a single line: ```kotlin @@ -1259,7 +1263,8 @@ enum class ComparisonResult { ### 3.10 Variable declaration -### Rule 3.10.1: Declare one variable per line. +This section describes rules for the declaration of variables. +#### 3.10.1 Declare one variable per line. Each property or variable must be declared on a separate line. @@ -1268,14 +1273,15 @@ Each property or variable must be declared on a separate line. val n1: Int; val n2: Int ``` -### Recommendation 3.10.2: Variables should be declared near the line where they are first used. +#### 3.10.2 Variables should be declared near the line where they are first used. Declare local variables close to the point where they are first used to minimize their scope. This will also increase the readability of the code. Local variables are usually initialized during their declaration or immediately after. The member fields of the class should be declared collectively (see [Rule 3.1.2](#r3.1.2) for details on the class structure). -### 3.11 When expression -### Rule 3.11.1: The 'when' statement must have an 'else' branch unless the condition variable is enumerated or a sealed type. +### 3.11 'When' expression + +The `when` statement must have an 'else' branch unless the condition variable is enumerated or a sealed type. Each `when` statement should contain an `else` statement group, even if it does not contain any code. **Exception:** If 'when' statement of the `enum or sealed` type contains all enum values, there is no need to have an "else" branch. @@ -1283,9 +1289,9 @@ The compiler can issue a warning when it is missing. ### 3.12 Annotations -### Recommendation 3.12.1: Each annotation applied to a class, method, or constructor should be placed on its own line. -1. Annotations applied to the class, method, or constructor are placed on separate lines (one annotation per line). +Each annotation applied to a class, method or constructor should be placed on its own line. Consider the following examples: +1. Annotations applied to the class, method or constructor are placed on separate lines (one annotation per line). **Valid example**: ```kotlin @@ -1309,8 +1315,7 @@ fun getNameIfPresent() { /* ... */ } ``` -### 3.13 Layout of comments -### Recommendation 3.13.1: Block comments location. +### 3.13 Block comments Block comments should be placed at the same indentation level as the surrounding code. See examples below. @@ -1326,11 +1331,13 @@ class SomeClass { } ``` -**Suggestion**: Use `/*...*/` block comments to enable automatic formatting by IDEs. +**Note**: Use `/*...*/` block comments to enable automatic formatting by IDEs. ### 3.14 Modifiers and constant values -### Recommendation 3.14.1: If a declaration has multiple modifiers, always follow the proper sequence. +This section contains recommendations regarding modifiers and constant values. +#### 3.14.1 Declaration with multiple modifiers +If a declaration has multiple modifiers, always follow the proper sequence. **Valid sequence:** ```kotlin @@ -1355,7 +1362,8 @@ operator data ``` -### Recommendation 3.14.2: An underscore should separate long numerical values. +#### 3.14.2: Separate long numerical values with an underscore +An underscore character should separate long numerical values. **Note:** Using underscores simplifies reading and helps to find errors in numeric constants. ```kotlin val oneMillion = 1_000_000 @@ -1367,9 +1375,11 @@ val bytes = 0b11010010_01101001_10010100_10010010 ### 3.15 Strings -### Rule 3.15.1: Concatenation of Strings is prohibited if the string can fit on one line. +This section describes the general rules of using strings. + +#### 3.15.1 Concatenation of Strings String concatenation is prohibited if the string can fit on one line. Use raw strings and string templates instead. Kotlin has significantly improved the use of Strings: -[String templates](https://kotlinlang.org/docs/reference/basic-types.html#string-templates), [Raw strings](https://kotlinlang.org/docs/reference/basic-types.html#string-literals) +[String templates](https://kotlinlang.org/docs/reference/basic-types.html#string-templates), [Raw strings](https://kotlinlang.org/docs/reference/basic-types.html#string-literals). Therefore, compared to using explicit concatenation, code looks much better when proper Kotlin strings are used for short lines, and you do not need to split them with newline characters. **Invalid example**: @@ -1384,7 +1394,7 @@ val myStr = "Super string" val value = "$myStr concatenated" ``` -### Rule 3.15.2: String template format +#### 3.15.2 String template format **Redundant curly braces in string templates** If there is only one variable in a string template, there is no need to use such a template. Use this variable directly. @@ -1412,9 +1422,11 @@ val someString = "$myArgument" val someString = myArgument ``` # 4. Variables and types +This section is dedicated to the rules and recommendations for using variables and types in your code. ### 4.1 Variables -### Rule 4.1.1: Do not use Float and Double types when accurate calculations are needed. +The rules of using variables are explained in the below topics. +#### 4.1.1 Do not use Float and Double types when accurate calculations are needed Floating-point numbers provide a good approximation over a wide range of values, but they cannot produce accurate results in some cases. Binary floating-point numbers are unsuitable for precise calculations because it is impossible to represent 0.1 or any other negative power of 10 in a `binary representation` with a finite length. @@ -1429,7 +1441,7 @@ However, it will print the following value: `0.8999999999999999` Therefore, for precise calculations (for example, in finance or exact sciences), using such types as `Int`, `Long`, `BigDecimal`are recommended. The `BigDecimal` type should serve as a good choice. -**Invalid example**: \ +**Invalid example**: Float values containing more than six or seven decimal numbers will be rounded. ```kotlin val eFloat = 2.7182818284f // Float, will be rounded to 2.7182817 @@ -1442,8 +1454,8 @@ Float values containing more than six or seven decimal numbers will be rounded. println(income.subtract(expense)) // you will obtain 0.9 here ``` -### Rule 4.1.2: Numeric float type values should not be directly compared with the equality operator (==) or other methods like `compareTo()` and `equals()`. -Since floating-point numbers involve precision problems in computer representation, it is better to use `BigDecimal` as recommended in [Rule 4.1.1](#r4.1.1) to make accurate computations and comparisons. The following code describes these problems. +#### 4.1.2: Comparing numeric float type values +Numeric float type values should not be directly compared with the equality operator (==) or other methods, such as `compareTo()` and `equals()`. Since floating-point numbers involve precision problems in computer representation, it is better to use `BigDecimal` as recommended in [Rule 4.1.1](#r4.1.1) to make accurate computations and comparisons. The following code describes these problems. **Invalid example**: ```kotlin @@ -1476,16 +1488,17 @@ if (abs(foo - bar) > 1e-6f) { } ``` -### Rule 4.1.3 Try to use 'val' instead of 'var' for variable declaration [SAY_NO_TO_VAR]. +#### 4.1.3 Try to use 'val' instead of 'var' for variable declaration [SAY_NO_TO_VAR]. Variables with the `val` modifier are immutable (read-only). -Code robustness and readability increase when using `val` variables instead of `var` variables. +Using `val` variables instead of `var` variables increases code robustness and readability. This is because `var` variables can be reassigned several times in the business logic. However, in some scenarios with loops or accumulators, only `var`s are permitted. ### 4.2 Types -### Recommendation 4.2.1: Use Contracts and smart cast as much as possible. +This section provides recommendations for using types. +#### 4.2.1: Use Contracts and smart cast as much as possible. The Kotlin compiler has introduced [Smart Casts](https://kotlinlang.org/docs/reference/typecasts.html#smart-casts) that help reduce the size of code. @@ -1533,7 +1546,7 @@ fun foo(s: String?) { } ``` -### Recommendation 4.2.2: Try to use type alias to represent types making code more readable. +#### 4.2.2: Try to use type alias to represent types making code more readable. Type aliases provide alternative names for existing types. If the type name is too long, you can replace it with a shorter name, which helps to shorten long generic types. @@ -1562,7 +1575,7 @@ typealias Predicate = (T) -> Boolean ### 4.3 Null safety and variable declarations Kotlin is declared as a null-safe programming language. However, to achieve compatibility with Java, it still supports nullable types. -### Recommendation 4.3.1: Avoid declaring variables with nullable types, especially from Kotlin stdlib. +#### Recommendation 4.3.1: Avoid declaring variables with nullable types, especially from Kotlin stdlib. To avoid `NullPointerException` and help the compiler prevent Null Pointer Exceptions, avoid using nullable types (with `?` symbol). **Invalid example**: @@ -1589,7 +1602,7 @@ val a: List? = null val a: List = emptyList() ``` -### Recommendation 4.3.2: Variables of generic types should have an explicit type declaration. +#### 4.3.2: Variables of generic types should have an explicit type declaration Like in Java, classes in Kotlin may have type parameters. To create an instance of such a class, we typically need to provide type arguments: ```kotlin @@ -1609,8 +1622,7 @@ val myVariable = emptyMap() val myVariable: Map = emptyMap() ``` -### Null-safety -### 4.3.3 Explicit null checks +#### Null-safety Try to avoid explicit null checks (explicit comparison with `null`) Kotlin is declared as [Null-safe](https://kotlinlang.org/docs/reference/null-safety.html) language. @@ -1696,20 +1708,22 @@ if (myVar == null || otherValue == 5 && isValid) {} Please also note, that instead of using `require(a != null)` with a not null check - you should use a special Kotlin function called `requireNotNull(a)`. # 5. Functions +This section describes the rules of using functions in your code. ### 5.1 Function design Developers can write clean code by gaining knowledge of how to build design patterns and avoid code smells. You should utilize this approach, along with functional style, when writing Kotlin code. The concepts behind functional style are as follows: Functions are the smallest unit of combinable and reusable code. -They should have clean logic, **high cohesion**, and **low coupling** to effectively organize the code. +They should have clean logic, **high cohesion**, and **low coupling** to organize the code effectively. The code in functions should be simple and not conceal the author's original intentions. + Additionally, it should have a clean abstraction, and control statements should be used straightforwardly. The side effects (code that does not affect a function's return value but affects global/object instance variables) should not be used for state changes of an object. The only exceptions to this are state machines. Kotlin is [designed](https://www.slideshare.net/abreslav/whos-more-functional-kotlin-groovy-scala-or-java) to support and encourage functional programming, featuring the corresponding built-in mechanisms. -Also, it supports standard collections and sequences feature methods that enable functional programming (for example, `apply`, `with`, `let`, and `run`), Kotlin Higher-Order functions, function types, lambdas, and default function arguments (???). +Also, it supports standard collections and sequences feature methods that enable functional programming (for example, `apply`, `with`, `let`, and `run`), Kotlin Higher-Order functions, function types, lambdas, and default function arguments. As [previously discussed](#r4.1.3), Kotlin supports and encourages the use of immutable types, which in turn motivates programmers to write pure functions that avoid side effects and have a corresponding output for specific input. The pipeline data flow for the pure function comprises a functional paradigm. It is easy to implement concurrent programming when you have chains of function calls, where each step features the following characteristics: 1. Simplicity @@ -1722,7 +1736,7 @@ The pipeline data flow for the pure function comprises a functional paradigm. It There can be only one side effect in this data stream, which can be placed only at the end of the execution queue. -### Rule 5.1.1: Avoid functions that are too long. +#### 5.1.1 Avoid functions that are too long The function should be displayable on one screen and only implement one certain logic. If a function is too long, it often means complex and could be split or simplified. Functions should consist of 30 lines (non-empty and non-comment) in total. @@ -1733,7 +1747,7 @@ Linter warnings for such functions **can be suppressed**. Even if a long function works well, new problems or bugs may appear due to the function's complex logic once it is modified by someone else. Therefore, it is recommended to split such functions into several separate and shorter functions that are easier to manage. This approach will enable other programmers to read and modify the code properly. -### Rule 5.1.2: Avoid deep nesting of function code blocks, limiting to four levels. +#### 5.1.2 Avoid deep nesting of function code blocks, limiting to four levels The nesting depth of a function's code block is the depth of mutual inclusion between the code control blocks in the function (for example: if, for, while, and when). Each nesting level will increase the amount of effort needed to read the code because you need to remember the current "stack" (for example, entering conditional statements and loops). @@ -1741,7 +1755,7 @@ Each nesting level will increase the amount of effort needed to read the code be Functional decomposition should be implemented to avoid confusion for the developer who reads the code. This will help the reader switch between contexts. -### Rule 5.1.3: Avoid using nested functions. +#### Rule 5.1.3 Avoid using nested functions Nested functions create a more complex function context, thereby confusing readers. With nested functions, the visibility context may not be evident to the code reader. @@ -1757,7 +1771,8 @@ fun foo() { ### 5.2 Function arguments -### Rule 5.2.1: The lambda parameter of the function should be placed at the end of the argument list. +The rules for using function arguments are described in the below topics. +#### 5.2.1 The lambda parameter of the function should be placed at the end of the argument list With such notation, it is easier to use curly brackets, leading to better code readability. @@ -1774,14 +1789,14 @@ println("hey") } ``` -### Rule 5.2.2: Number of function parameters should be limited to 5 +#### 5.2.2 Number of function parameters should be limited to five A long argument list is a [code smell](https://en.wikipedia.org/wiki/Code_smell) that leads to less reliable code. It is recommended to reduce the number of parameters. Having **more than five** parameters leads to difficulties in maintenance and conflicts merging. If parameter groups appear in different functions multiple times, these parameters are closely related and can be encapsulated into a single Data Class. It is recommended that you use Data Classes and Maps to unify these function arguments. -### Rule 5.2.3 Use default values for function arguments instead of overloading them +#### 5.2.3 Use default values for function arguments instead of overloading them In Java, default values for function arguments are prohibited. That is why the function should be overloaded when you need to create a function with fewer arguments. In Kotlin, you can use default arguments instead. @@ -1802,11 +1817,12 @@ private fun foo() { // ... } ``` -# 6. Classes, interfaces and extension functions +# 6. Classes, interfaces, and extension functions ### 6.1 Classes -### Rule 6.1.1: When a class has a single constructor, it should be defined as a primary constructor in the declaration of the class. -In case the class contains only one explicit constructor - it should be converted to a primary constructor. +This section describes the rules of denoting classes in your code. +#### 6.1.1 Denoting a class with a single constructor +When a class has a single constructor, it should be defined as a primary constructor in the declaration of the class. If the class contains only one explicit constructor, it should be converted to a primary constructor. **Invalid example**: ```kotlin @@ -1830,7 +1846,7 @@ class Test private constructor(var a: Int) { } ``` -### Rule 6.1.2: Prefer data classes instead of classes without any functional logic. +#### 6.1.2 Prefer data classes instead of classes without any functional logic Some people say that the data class is a code smell. However, if you need to use it (which makes your code more simple), you can utilize the Kotlin `data class`. The main purpose of this class is to hold data, but also `data class` will automatically generate several useful methods: - equals()/hashCode() pair; @@ -1876,7 +1892,7 @@ data class Test1(var a: Int = 0, var b: Int = 0) **Exception 2**: No need to convert a class to a data class if this class extends some other class or implements an interface. -### Rule 6.1.3: Do not use the primary constructor if it is empty or useless. +#### 6.1.3 Do not use the primary constructor if it is empty or useless The primary constructor is a part of the class header; it is placed after the class name and type parameters (optional) but can be omitted if it is not used. **Invalid example**: @@ -1911,12 +1927,12 @@ class Test { } ``` -### Rule 6.1.4: several init blocks are redundant and generally should not be used in your class. -The primary constructor cannot contain any code. That is why Kotlin has introduced `init` blocks. +#### 6.1.4 Do not use redundant init blocks in your class +Several init blocks are redundant and generally should not be used in your class. The primary constructor cannot contain any code. That is why Kotlin has introduced `init` blocks. These blocks store the code to be run during the class initialization. Kotlin allows writing multiple initialization blocks executed in the same order as they appear in the class body. Even when you follow (rule 3.2)[#r3.2], this makes your code less readable as the programmer needs to keep in mind all init blocks and trace the execution of the code. -Therefore, you should try to use a single `init` block to reduce the code's complexity. . If you need to do some logging or make some calculations before the class property assignment, you can use powerful functional programming. This will reduce the possibility of the error if your `init` blocks' order is accidentally changed and +Therefore, you should try to use a single `init` block to reduce the code's complexity. If you need to do some logging or make some calculations before the class property assignment, you can use powerful functional programming. This will reduce the possibility of the error if your `init` blocks' order is accidentally changed and make the code logic more coupled. It is always enough to use one `init` block to implement your idea in Kotlin. **Invalid example**: @@ -1969,8 +1985,8 @@ class A(baseUrl: String) { } ``` -### Rule 6.1.5: Explicit supertype qualification should not be used if there is not clash between called methods. -This rule is applicable to both interfaces and classes. +#### 6.1.5 Explicit supertype qualification +The explicit supertype qualification should not be used if there is no clash between called methods. This rule is applicable to both interfaces and classes. **Invalid example**: ```kotlin @@ -1985,7 +2001,7 @@ class Square() : Rectangle() { } ``` -### Rule 6.1.6: Abstract class should have at least one abstract method. +#### 6.1.6 Abstract class should have at least one abstract method Abstract classes are used to force a developer to implement some of its parts in their inheritors. When the abstract class has no abstract methods, it was set `abstract` incorrectly and can be converted to a regular class. @@ -2015,7 +2031,7 @@ class NotAbstract { ``` -### Rule 6.1.7: in case of using "implicit backing property" scheme, the name of real and back property should be the same. +#### 6.1.7 When using the "implicit backing property" scheme, the name of real and back property should be the same Kotlin has a mechanism of [backing properties](https://kotlinlang.org/docs/reference/properties.html#backing-properties). In some cases, implicit backing is not enough and it should be done explicitly: ```kotlin @@ -2032,7 +2048,7 @@ val table: Map In this case, the name of the backing property (`_table`) should be the same as the name of the real property (`table`) but should have an underscore (`_`) prefix. It is one of the exceptions from the [identifier names rule](#r1.2) -### Recommendation 6.1.8: avoid using custom getters and setters. +#### 6.1.8 Avoid using custom getters and setters Kotlin has a perfect mechanism of [properties](https://kotlinlang.org/docs/reference/properties.html#properties-and-fields). Kotlin compiler automatically generates `get` and `set` methods for properties and can override them. @@ -2049,9 +2065,9 @@ class A { } ``` -From the callee code these methods look like an access to this property: `A().isEmpty = true` for setter and `A().isEmpty` for getter. +From the callee code, these methods look like access to this property: `A().isEmpty = true` for setter and `A().isEmpty` for getter. -However, when `get` and `set` are overridden, it is very confusing for a developer who uses this particular class. +However, when `get` and `set` are overridden, it isn't very clear for a developer who uses this particular class. The developer expects to get the property value but receives some unknown value and some extra side-effect hidden by the custom getter/setter. Use extra functions instead to avoid confusion. @@ -2072,7 +2088,7 @@ class A { **Exception:** `Private setters` are only exceptions that are not prohibited by this rule. -### Rule 6.1.9: never use the name of a variable in the custom getter or setter (possible_bug). +#### 6.1.9 Never use the name of a variable in the custom getter or setter (possible_bug) If you ignored [recommendation 6.1.8](#r6.1.8), be careful with using the name of the property in your custom getter/setter as it can accidentally cause a recursive call and a `StackOverflow Error`. Use the `field` keyword instead. @@ -2086,7 +2102,7 @@ var isEmpty: Boolean get() = isEmpty ``` -### Recommendation 6.1.10 no trivial getters and setters are allowed in the code. +#### 6.1.10 No trivial getters and setters are allowed in the code In Java, trivial getters - are the getters that are just returning the field value. Trivial setters - are merely setting the field with a value without any transformation. However, in Kotlin, trivial getters/setters are generated by default. There is no need to use it explicitly for all types of data structures in Kotlin. @@ -2113,7 +2129,7 @@ class A { } ``` -### Rule 6.1.11: use apply for grouping object initialization. +#### Use 'apply' for grouping object initialization In Java, before functional programming became popular, many classes from common libraries used the configuration paradigm. To use these classes, you had to create an object with the constructor with 0-2 arguments and set the fields needed to run the object. In Kotlin, to reduce the number of dummy code line and to group objects [`apply` extension](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/apply.html) was added: @@ -2162,18 +2178,19 @@ fun main() { ### 6.2 Extension functions +This section describes the rules of using extension functions in your code. + [Extension functions](https://kotlinlang.org/docs/reference/extensions.html) is a killer-feature in Kotlin. -It gives you a chance to extend classes that were already implemented in external libraries and help you to make classes less heavy. +It gives you a chance to extend classes that were already implemented in external libraries and helps you to make classes less heavy. Extension functions are resolved statically. -### Recommendation 6.2.1: use extension functions for making logic of classes less coupled. +#### 6.2.1 Use extension functions for making logic of classes less coupled It is recommended that for classes, the non-tightly coupled functions, which are rarely used in the class, should be implemented as extension functions where possible. They should be implemented in the same class/file where they are used. This is a non-deterministic rule, so the code cannot be checked or fixed automatically by a static analyzer. -### Rule 6.2.2: No extension functions with the same name and signature if they extend base and inheritor classes (possible_bug). -As extension functions are resolved statically. In this case, there could be a situation when a developer implements two extension functions: one is for the base class and another for the inheritor. +#### 6.2.2 No extension functions with the same name and signature if they extend base and inheritor classes (possible_bug) +You should have ho extension functions with the same name and signature if they extend base and inheritor classes (possible_bug).esolved statically. There could be a situation when a developer implements two extension functions: one is for the base class and another for the inheritor. This can lead to an issue when an incorrect method is used. -And that can lead to an issue when incorrect method is used. **Invalid example**: ```kotlin @@ -2201,8 +2218,9 @@ In Kotlin and Java, the interface is the main presentation means of application ### 6.4 Objects -### Rule 6.4.1: Avoid using utility classes/objects, use extensions instead. -As described in [6.2 Extension functions](#c6.2), extension functions are a powerful. Instead of using utility classes/objects, use it extention functions. +This section describes the rules of using objects in code. +#### 6.4.1 Instead of using utility classes/objects, use extensions. +Avoid using utility classes/objects; use extensions instead. As described in [6.2 Extension functions](#c6.2), using extension functions is a powerful method. This enables you to avoid unnecessary complexity and class/object wrapping and use top-level functions instead. **Invalid example**: @@ -2224,7 +2242,7 @@ fun String.stringInfo(): Int { "myStr".stringInfo() ``` -### Recommendation 6.4.2: Objects should be used for Stateless Interfaces. +#### 6.4.2 Objects should be used for Stateless Interfaces. Kotlin’s objects are extremely useful when you need to implement some interface from an external library that does not have any state. There is no need to use classes for such structures. diff --git a/wp/sections/appendix.tex b/wp/sections/appendix.tex index d3e4b35937..384b3c372c 100644 --- a/wp/sections/appendix.tex +++ b/wp/sections/appendix.tex @@ -10,55 +10,6 @@ \subsection{Package diagram} \includegraphics[scale=0.65]{pictures/package.png} \lstMakeShortInline[basicstyle=\ttfamily\bfseries]` - - - - -\section*{\textbf{Diktat Coding Convention}} - - - -\subsubsection*{\textbf{Content}} -\leavevmode\newline - - - -\begin{center} - -\begin{tabular}{ |p{7,5cm}|p{7,5cm}| } - -\hline - -Chapter&Content\\ - -\hline - - [0. Preface] & [Purpose], [General principles], [Terminology], [Exceptions] \\ - - [1. Naming] & [Identifiers], [Package names], [Classes, enumeration and interfaces], [Functions], [Constants], [Variables] \\ - - [2. Docs] & [Kdoc], [File header], [Comments on function header ], [Code comments] \\ - - [3. General formatting] & [File-related rules], [Braces], [Indentation], [Empty blocks], [Line length], [Line breaks (newlines)], [Blank lines], [Horizontal space], [Enumerations], [Variable declaration], [When expression], [Annotations], [Layout of comments], [Modifiers and constant values], [Strings]\\ - - [4. Variables and types] & [Variables], [Types], [Null safety and variable declarations]\\ - - [5. Functions] & [Function design], [Function arguments]\\ - - [6. Classes] & [Classes], [Extension functions], [Interfaces], [Objects] \\ - - [7. Kotlin \& Java] & \\ - -\hline - -\end{tabular} - -\end{center} - - - - - \section*{\textbf{Preface}} \subsection*{\textbf{Purpose of this document}} @@ -191,7 +142,9 @@ \section*{\textbf{1. Naming}} \subsection*{\textbf{1.1 Identifier names}} -\subsubsection*{\textbf{Rule 1.1.1}} +This section describes the general rules for naming identifiers. + +\subsubsection*{\textbf{1.1.1 Identifiers naming conventions}} \leavevmode\newline @@ -220,7 +173,7 @@ \subsubsection*{\textbf{Rule 1.1.1}} \begin{center} -\begin{tabular}{ |p{5,0cm}|p{5,0cm}|p{5,0cm}| } +\begin{tabular}{ |p{5.0cm}|p{5.0cm}|p{5.0cm}| } \hline @@ -266,7 +219,7 @@ \subsubsection*{\textbf{Rule 1.1.1}} \begin{center} -\begin{tabular}{ |p{5,0cm}|p{5,0cm}|p{5,0cm}| } +\begin{tabular}{ |p{5.0cm}|p{5.0cm}|p{5.0cm}| } \hline @@ -310,7 +263,7 @@ \subsubsection*{\textbf{Rule 1.1.1}} \begin{center} -\begin{tabular}{ |p{7,5cm}|p{7,5cm}| } +\begin{tabular}{ |p{7.5cm}|p{7.5cm}| } \hline @@ -336,7 +289,9 @@ \subsubsection*{\textbf{Rule 1.1.1}} \subsection*{\textbf{1.2 Packages names}} -\subsubsection*{\textbf{Rule 1.2.1}} + + +\subsubsection*{\textbf{Rule 1.2.1 Package names dots}} \leavevmode\newline Package names are in lower case and separated by dots. Code developed within your company should start with `your.company.domain.` Numbers are permitted in package names. @@ -368,7 +323,9 @@ \subsubsection*{\textbf{Rule 1.2.1}} \subsection*{\textbf{1.3 Classes}} -\subsubsection*{\textbf{Rule 1.3.1}} +This section describes the general rules for naming classes, enumerations, and interfaces. + +\subsubsection*{\textbf{1.3.1 Classes}} \leavevmode\newline Classes, enumerations, and interface names use `UpperCamelCase` nomenclature. Follow the naming rules described below: @@ -407,7 +364,9 @@ \subsubsection*{\textbf{Rule 1.3.1}} \subsection*{\textbf{1.4 Functions}} -\subsubsection*{\textbf{Rule 1.4.1}} +This section describes the general rules for naming functions. + +\subsubsection*{\textbf{1.4.1 Function names should be in camel case}} \leavevmode\newline Function names should use `lowerCamelCase` nomenclature. Follow the naming rules described below: @@ -483,32 +442,26 @@ \subsubsection*{\textbf{Rule 1.4.1}} \end{lstlisting} -2. An underscore (`_`) can be included in the JUnit test function name and should be used as a separator. Each logical part denoted in `lowerCamelCase`, for example, a typical pattern of using underscore: `pop_emptyStack`. +2. An underscore (`_`) can be included in the JUnit test function name and should be used as a separator. Each logical part is denoted in `lowerCamelCase`, for example, a typical pattern of using underscore: `pop_emptyStack`. \subsection*{\textbf{1.5 Constants}} -\subsubsection*{\textbf{Rule 1.5.1 Constant names should be in UPPER case}} -\leavevmode\newline - -Constant names should be in UPPER case, words separated by underscore. The jeneral constant naming conventions are listed below: - -1. Constants are attributes created with the `const` keyword, or top-level/`val` local variables of an object that holds immutable data. In most cases, constants can be identified as a `const val` property from the `object`/`companion object`/file top level. These variables contain a fixed constant values that typically should never be changed by programmers. This includes basic types, strings, immutable types, and immutable collections of immutable types. The value is not constant for the object, which state can be changed. - +This section describes the general rules for naming constraints. +\subsubsection*{\textbf{1.5.1 Using UPPER case and underscore characters in a constraint name}} +\leavevmode\newline -2. Constant names should contain only uppercase letters separated by underscores. They should have a `val` or `const val` (`const` should be used only with primitive types) modifier to make them final (immutable) explicitly. In most cases, if you need to specify a constant value, then you need to create it with the `const val` modifier. Note that not all `val` variables are constants. +Constant names should be in UPPER case, words separated by underscore. The general constant naming conventions are listed below: +1. Constants are attributes created with the `const` keyword or top-level/`val` local variables of an object that holds immutable data. In most cases, constants can be identified as a `const val` property from the `object`/`companion object`/file top level. These variables contain fixed constant values that typically should never be changed by programmers. This includes basic types, strings, immutable types, and immutable collections of immutable types. The value is not constant for the object, which state can be changed. +2. Constant names should contain only uppercase letters separated by an underscores. They should have a val or const val modifier to make them final explicitly. In most cases, if you need to specify a constant value, then you need to create it with the "const val" modifier. Note that not all `val` variables are constants. 3. Objects with immutable content, such as `Logger` and `Lock`, can be in uppercase as constants or have camel case as regular variables. - - 4. Use meaningful constants instead of `magic numbers`. SQL or logging strings should not be treated as magic numbers, nor should they be defined as string constants. - - -Magic constants like `NUM_FIVE = 5` or `NUM_5 = 5` should not be treated as constants. This is because mistakes will easily be made if they are changed to `NUM_5 = 50` or 55. +Magic constants, such as `NUM_FIVE = 5` or `NUM_5 = 5` should not be treated as constants. This is because mistakes will easily be made if they are changed to `NUM_5 = 50` or 55. These constants typically represent business logic values, such as measures, capacity, scope, location, tax rate, promotional discounts, and power base multiples in algorithms. @@ -542,7 +495,9 @@ \subsubsection*{\textbf{Rule 1.5.1 Constant names should be in UPPER case}} \subsection*{\textbf{1.6 Non-constant fields}} -\subsubsection*{\textbf{Rule 1.6.1}} +This section describes the general rules for naming variables. + +\subsubsection*{\textbf{1.6.1 Non-constant field name}} \leavevmode\newline Non-constant field names should use camel case and start with a lowercase letter. @@ -574,12 +529,12 @@ \subsubsection*{\textbf{Rule 1.6.1}} \end{lstlisting} -\subsubsection*{\textbf{Rule 1.6.2}} +\subsubsection*{\textbf{1.6.2 Boolean variable names with negative meaning}} \leavevmode\newline -Avoid using Boolean variable names with a negative meaning. When using a logical operator and name with negative meaning, the code may be difficult to understand, which is referred to as the "double negative". +Avoid using Boolean variable names with a negative meaning. When using a logical operator and name with a negative meaning, the code may be difficult to understand, which is referred to as the "double negative". For instance, it is not easy to understand the meaning of !isNotError. @@ -634,7 +589,7 @@ \section*{\textbf{2. Comments}} \subsection*{\textbf{2.1 General form of Kdoc}} - + KDoc is a combination of JavaDoc's block tags syntax (extended to support specific constructions of Kotlin) and Markdown's inline markup. @@ -664,7 +619,7 @@ \subsection*{\textbf{2.1 General form of Kdoc}} -\subsubsection*{\textbf{Rule 2.1.1}} +\subsubsection*{\textbf{2.1.1 Using KDoc for the public}} \leavevmode\newline @@ -679,6 +634,8 @@ \subsubsection*{\textbf{Rule 2.1.1}} + + \textbf{Incorrect example:} \begin{lstlisting}[language=Kotlin] @@ -715,11 +672,11 @@ \subsubsection*{\textbf{Rule 2.1.1}} -1. For setters/getters of properties, obvious comments (like `this getter returns field`) are optional. Note that Kotlin generates simple `get/set` methods under the hood. +* For setters/getters of properties, obvious comments (like `this getter returns field`) are optional. Note that Kotlin generates simple `get/set` methods under the hood. -2. It is optional to add comments for simple one-line methods, such as shown in the example below: +* It is optional to add comments for simple one-line methods, such as shown in the example below: \begin{lstlisting}[language=Kotlin] val isEmpty: Boolean @@ -736,16 +693,20 @@ \subsubsection*{\textbf{Rule 2.1.1}} \end{lstlisting} -Note: You can skip KDocs for a method's override if it is almost the same as the superclass method. +\textbf{Note:} You can skip KDocs for a method's override if it is almost the same as the superclass method. -\subsubsection*{\textbf{Rule 2.1.2}} +\subsubsection*{\textbf{2.1.2 Describing methods that have arguments}} \leavevmode\newline -\textbf{Valid examples}: +When the method has such details as arguments, return value, or can throw exceptions, it must be described in the KDoc block (with @param, @return, @throws, etc.). + + + +\textbf{Valid examples:} @@ -758,7 +719,7 @@ \subsubsection*{\textbf{Rule 2.1.2}} protected abstract class Sample { /** * This is a long comment with whitespace that should be split in - * comments on multiple lines in case the line comment formatting is enabled. + * comments on multiple lines if the line comment formatting is enabled. * / * Add a blank line between the comment text and each KDoc tag underneath * / * @param fox A quick brown fox jumps over the lazy dog * @return battle between fox and dog @@ -781,9 +742,11 @@ \subsubsection*{\textbf{Rule 2.1.2}} \end{lstlisting} -\subsubsection*{\textbf{Rule 2.1.3}} +\subsubsection*{\textbf{2.1.3 Only one space between the Kdoc tag and content. Tags are arranged in the order.}} \leavevmode\newline + + There should be only one space between the Kdoc tag and content. Tags are arranged in the following order: @param, @return, and @throws. @@ -858,18 +821,27 @@ \subsubsection*{\textbf{Rule 2.1.3}} * @since 1.6 */ \end{lstlisting} -\subsection*{\textbf{2.2 Comments to the file header}} -\subsubsection*{\textbf{Rule 2.2.1}} -\leavevmode\newline + +\subsection*{\textbf{2.2 Adding comments on the file header}} +This section describes the general rules of adding comments on the file header. + Comments on the file header should be placed before the package name and imports. If you need to add more content to the comment, subsequently add it in the same format. -The following examples for Huawei describe the format of the \textbf{copyright license}: \ +Comments on the file header must include copyright information, without the creation date and author's name (use VCS for history management). Also, describe the content inside files that contain multiple or no classes. + + + +Place comments on the file header before the package name and imports. If you need to add more content to the comment, subsequently add it in the same format. + + + +The following examples for Huawei describe the format of the \textit{copyright license}: \ Chinese version: `版权所有 (c) 华为技术有限公司 2012-2020` \ @@ -918,18 +890,15 @@ \subsubsection*{\textbf{Rule 2.2.1}} - Do not include empty comment blocks. If there is no content after the option `@apiNote`, the entire tag block should be deleted. -- The industry practice is not to include historical information in comments. The corresponding history can be found in VCS (git, svn, etc.). Therefore, it is not recommended to include historical data in the comments of the Kotlin source code. - - +- The industry practice is not to include historical information in the comments. The corresponding history can be found in VCS (git, svn, etc.). Therefore, it is not recommended to include historical data in the comments of the Kotlin source code. \subsection*{\textbf{2.3 Comments on the function header}} -\subsubsection*{\textbf{Rule 2.3.1}} -\leavevmode\newline -Comments on the function header are placed above function declarations or definitions. A newline should not exist between a function declaration and its Kdoc. Use the preceding [KDoc] style rules. + +Comments on the function header are placed above function declarations or definitions. A newline should not exist between a function declaration and its Kdoc. Use the preceding <> style rules. @@ -945,14 +914,22 @@ \subsubsection*{\textbf{Rule 2.3.1}} \subsection*{\textbf{2.4 Code comments}} -\subsubsection*{\textbf{Rule 2.4.1}} + + +This section describes the general rules of adding code comments. + + + +\subsubsection*{\textbf{2.4.1 Add a blank line between the body of the comment and Kdoc tag-blocks.}} \leavevmode\newline + + It is a good practice to add a blank line between the body of the comment and Kdoc tag-blocks. Also, consider the following rules: -- There must be one space between the comment character and the content of the comment +- There must be one space between the comment character and the content of the comment. -- There must be a newline between a Kdoc and presiding code +- There must be a newline between a Kdoc and the presiding code. - An empty line should not exist between a Kdoc and the code it is describing. You do not need to add a blank line before the first comment in a particular namespace (code block) (for example, between the function declaration and first comment in a function body). @@ -960,6 +937,8 @@ \subsubsection*{\textbf{Rule 2.4.1}} \textbf{Valid Examples:} + + \begin{lstlisting}[language=Kotlin] /** * This is the short overview comment for the example interface. @@ -1014,6 +993,7 @@ \subsubsection*{\textbf{Rule 2.4.1}} \begin{lstlisting}[language=Kotlin] + val foo = 100 // right-side comment val bar = 200 /* right-side comment */ @@ -1036,20 +1016,24 @@ \subsubsection*{\textbf{Rule 2.4.1}} \end{lstlisting} -- Start all comments (including KDoc) with space after the first symbol (`//`, `/*`, `/**` and `*`) +- Start all comments (including KDoc) with a space after the first symbol (`//`, `/*`, `/**` and `*`) \textbf{Valid example:} + + \begin{lstlisting}[language=Kotlin] val x = 0 // this is a comment \end{lstlisting} -\subsubsection*{\textbf{Rule 2.4.2}} +\subsubsection*{\textbf{2.4.2 Do not comment on unused code blocks}} \leavevmode\newline + + Do not comment on unused code blocks, including imports. Delete these code blocks immediately. A code is not used to store history. Git, svn, or other VCS tools should be used for this purpose. @@ -1064,18 +1048,22 @@ \subsubsection*{\textbf{Rule 2.4.2}} -\subsubsection*{\textbf{Recommendation 2.4.3}} +\subsubsection*{\textbf{2.4.3 Code delivered to the client should not contain TODO}} \leavevmode\newline + + The code officially delivered to the client typically should not contain TODO/FIXME comments. `TODO` comments are typically used to describe modification points that need to be improved and added. For example, refactoring FIXME comments are typically used to describe known defects and bugs that will be subsequently fixed and are not critical for an application. -They should all have a unified style to facilitate the unified text search processing. +They should all have a unified style to facilitate unified text search processing. -\textbf{Example}: +\textbf{Example:} + + \begin{lstlisting}[language=Kotlin] // TODO(): Jira-XXX - support new json format @@ -1089,12 +1077,14 @@ \section*{\textbf{3. General formatting}} \subsection*{\textbf{3.1 File-related rules}} -\subsubsection*{\textbf{Rule 3.1.1}} +This section describes the rules related to using files in your code. + +\subsubsection*{\textbf{3.1.1 Avoid files that are too long}} \leavevmode\newline -If the file is too long and complex, it should be split into smaller files, functions, or modules. +If the file is too long and complicated, it should be split into smaller files, functions, or modules. Files should not exceed 2000 lines (non-empty and non-commented lines). It is recommended to horizontally or vertically split the file according to responsibilities or hierarchy of its parts. @@ -1102,7 +1092,7 @@ \subsubsection*{\textbf{Rule 3.1.1}} -\subsubsection*{\textbf{Rule 3.1.2}} +\subsubsection*{\textbf{3.1.2 Code blocks in the source file should be separated by one blank line}} \leavevmode\newline A source file contains code blocks in the following order: copyright, package name, imports, and top-level classes. They should be separated by one blank line. @@ -1133,7 +1123,7 @@ \subsubsection*{\textbf{Rule 3.1.2}} -d) \textbf{Recommendation}. One `.kt` source file should contain only one class declaration, and its name should match the filename +d) \textbf{Recommendation}: One `.kt` source file should contain only one class declaration, and its name should match the filename @@ -1141,7 +1131,7 @@ \subsubsection*{\textbf{Rule 3.1.2}} -\subsubsection*{\textbf{Recommendation 3.1.3}} +\subsubsection*{\textbf{3.1.3 Import statements order}} \leavevmode\newline @@ -1185,13 +1175,11 @@ \subsubsection*{\textbf{Recommendation 3.1.3}} \end{lstlisting} -\subsubsection*{\textbf{Recommendation 3.1.4}} +\subsubsection*{\textbf{3.1.4 Order of declaration parts of class-like code structures}} \leavevmode\newline The declaration parts of class-like code structures (class, interface, etc.) should be in the following order: compile-time constants (for objects), class properties, late-init class properties, init-blocks, constructors, public methods, internal methods, protected methods, private methods, and companion object. Blank lines should separate their declaration. - - Notes: 1. There should be no blank lines between properties with the following \textbf{exceptions}: when there is a comment before a property on a separate line or annotations on a separate line. @@ -1216,7 +1204,7 @@ \subsubsection*{\textbf{Recommendation 3.1.4}} - Methods or nested classes. Put nested classes next to the code they are used by. -If the classes are meant to be used externally and are not referenced inside the class, put them after the companion object. +If the classes are meant to be used externally, and are not referenced inside the class, put them after the companion object. - Companion object @@ -1224,13 +1212,15 @@ \subsubsection*{\textbf{Recommendation 3.1.4}} \textbf{Exception:} -All variants of a `(private) val` logger should be placed in the beginning of the class (`(private) val log`, `LOG`, `logger`, etc.). +All variants of a `(private) val` logger should be placed at the beginning of the class (`(private) val log`, `LOG`, `logger`, etc.). \subsection*{\textbf{3.2 Braces}} -\subsubsection*{\textbf{Rule 3.2.1}} +This section describes the general rules of using braces in your code. + +\subsubsection*{\textbf{3.2.1 Using braces in conditional statements and loop blocks}} \leavevmode\newline @@ -1286,10 +1276,10 @@ \subsubsection*{\textbf{Rule 3.2.1}} \end{lstlisting} -\subsubsection*{\textbf{Rule 3.2.2 For}} +\subsubsection*{\textbf{3.2.2 Opening braces are placed at the end of the line in}} \leavevmode\newline - +For *non-empty* blocks and block structures, the opening brace is placed at the end of the line. Follow the K\&R style (1TBS or OTBS) for *non-empty* code blocks with braces: @@ -1364,9 +1354,6 @@ \subsubsection*{\textbf{Rule 3.2.2 For}} \subsection*{\textbf{3.3 Indentation}} -\subsubsection*{\textbf{Rule 3.3.1}} -\leavevmode\newline - Only spaces are permitted for indentation, and each indentation should equal `four spaces` (tabs are not permitted). @@ -1375,7 +1362,7 @@ \subsubsection*{\textbf{Rule 3.3.1}} These code blocks should be indented if they are placed on the new line, and the following conditions are met: -- The code block is placed immediately after an opening brace +- The code block is placed immediately after an opening brace. - The code block is placed after each operator, including the assignment operator (`+`/`-`/`\&\&`/`=`/etc.) @@ -1417,7 +1404,7 @@ \subsubsection*{\textbf{Rule 3.3.1}} -4. Super type lists: \ +4. Supertype lists: \ a) Four spaces are used if the colon before the supertype list is on a new line. \ @@ -1478,12 +1465,9 @@ \subsubsection*{\textbf{Rule 3.3.1}} \subsection*{\textbf{3.4 Empty blocks}} -\subsubsection*{\textbf{Recommendation 3.4.1}} -\leavevmode\newline - -An empty code block can be closed immediately on the same line and the next line. However, a newline is recommended between opening and closing braces `{}` (see the examples below.) +Avoid empty blocks, and ensure braces start on a new line. An empty code block can be closed immediately on the same line and the next line. However, a newline is recommended between opening and closing braces `{}` (see the examples below.) @@ -1530,14 +1514,11 @@ \subsubsection*{\textbf{Recommendation 3.4.1}} \subsection*{\textbf{3.5 Line length}} -\subsubsection*{\textbf{Recommendation 3.5.1}} -\leavevmode\newline +Line length should be less than 120 symbols. The international code style prohibits `non-Latin` (`non-ASCII`) symbols. -The international code style prohibits `non-Latin` (`non-ASCII`) symbols. - -(See [Rule 1.1.1: Identifiers]) However, if you still intend on using them, follow the following convention: +(See [Identifiers]) However, if you still intend on using them, follow the following convention: @@ -1573,7 +1554,9 @@ \subsubsection*{\textbf{Recommendation 3.5.1}} \subsection*{\textbf{3.6 Line breaks}} -\subsubsection*{\textbf{Recommendation 3.6.1}} +This section contains the rules and recommendations on using line breaks. + +\subsubsection*{\textbf{3.6.1 Each line can have a maximum of one statement.}} \leavevmode\newline Each line can have a maximum of one code statement. This recommendation prohibits the use of code with `;` because it decreases code visibility. @@ -1595,7 +1578,7 @@ \subsubsection*{\textbf{Recommendation 3.6.1}} \end{lstlisting} -\subsubsection*{\textbf{Rule 3.6.2}} +\subsubsection*{\textbf{3.6.2 Rules for line-breaking}} \leavevmode\newline @@ -1764,7 +1747,7 @@ \subsubsection*{\textbf{Rule 3.6.2}} \end{lstlisting} -8) If the supertype list has more than two elements, they should be separated by newlines +8) If the supertype list has more than two elements, they should be separated by newlines. @@ -1778,16 +1761,13 @@ \subsubsection*{\textbf{Rule 3.6.2}} \end{lstlisting} -\subsection*{\textbf{3.7 Blank lines}} - -\subsubsection*{\textbf{Recommendation 3.7.1}} -\leavevmode\newline +\subsection*{\textbf{3.7 Using blank lines}} -By reducing unnecessary blank lines, you can display more code on one screen, which improves code readability. +Reduce unnecessary blank lines and maintain a compact code size. By reducing unnecessary blank lines, you can display more code on one screen, which improves code readability. -- Blank lines should separate content based on relevance and should be placed between groups of fields, constructors, methods, nested classes, `init` blocks, and objects (see [Rule 3.1.2]). +- Blank lines should separate content based on relevance and should be placed between groups of fields, constructors, methods, nested classes, `init` blocks, and objects (see [3.1.2]). - Do not use more than one line inside methods, type definitions, and initialization expressions. @@ -1811,22 +1791,28 @@ \subsubsection*{\textbf{Recommendation 3.7.1}} \subsection*{\textbf{3.8 Horizontal space}} -\subsubsection*{\textbf{Rule 3.8.1}} +This section describes general rules and recommendations for using spaces in the code. + +\subsubsection*{\textbf{3.8.1}} \leavevmode\newline -\textbf{Note:} This recommendation is for the cases where symbols are located on the same line. However, in some cases, a line break could be used instead of a space (described in another rule.) +Follow the recommendations below for using space to separate keywords: + +\textbf{Note:} These recommendations are for cases where symbols are located on the same line. However, in some cases, a line break could be used instead of a space. -1. Separate keywords like `if`, `when`, `for`, e.t.c. from the opening parenthesis with single whitespace. + + +1. Separate keywords (such as `if`, `when`, `for`) from the opening parenthesis with single whitespace. The only exception is the `constructor` keyword, which should not be separated from the opening parenthesis. -2. Separate keywords like `else` or `try` from the opening brace (`{`) with a single whitespace. +2. Separate keywords like `else` or `try` from the opening brace (`{`) with single whitespace. If `else` is used in a ternary-style statement without braces, there should be a single space between `else` and the statement after: `if (condition) foo() else bar()` @@ -1840,7 +1826,7 @@ \subsubsection*{\textbf{Rule 3.8.1}} \end{lstlisting} -4. A single whitespace should be placed on both sides of binary operators. This also applies to operator-like symbols. +4. Single whitespace should be placed on both sides of binary operators. This also applies to operator-like symbols. For example: @@ -1876,7 +1862,7 @@ \subsubsection*{\textbf{Rule 3.8.1}} 5. Use spaces after (`,`), (`:`), and (`;`), except when the symbol is at the end of the line. - However, note that this code style prohibits the use of (`;`) in the middle of a line ([Rule 3.2.2]). + However, note that this code style prohibits the use of (`;`) in the middle of a line ([see 3.3.2]). There should be no whitespaces at the end of a line. @@ -1884,13 +1870,15 @@ \subsubsection*{\textbf{Rule 3.8.1}} There should be no spaces before `,` , `:` and `;`. - \textbf{Exceptions} for spaces and colons are the following: + + + \textbf{Exceptions} for spaces and colons: - - when `:` is used to separate a type and a supertype, including an anonymous object (after object keyword) + - When `:` is used to separate a type and a supertype, including an anonymous object (after object keyword) - - when delegating to a superclass constructor or different constructor of the same class + - When delegating to a superclass constructor or different constructor of the same class @@ -1919,7 +1907,7 @@ \subsubsection*{\textbf{Rule 3.8.1}} 8. There should be no space between a method or constructor name (both at declaration and at call site) and a parenthesis: - `foo() {}`. Note that this sub-rule is related only to spaces; the rules for whitespaces are described in [Rule 3.6.2]. + `foo() {}`. Note that this sub-rule is related only to spaces; the rules for whitespaces are described in [see 3.6.2]. This rule does not prohibit, for example, the following code: @@ -1939,7 +1927,7 @@ \subsubsection*{\textbf{Rule 3.8.1}} -\subsubsection*{\textbf{Recommendation 3.8.2}} +\subsubsection*{\textbf{3.8.2}} \leavevmode\newline @@ -1952,7 +1940,7 @@ \subsubsection*{\textbf{Recommendation 3.8.2}} - Long identifier names will break the alignment and lead to less presentable code. -- There are more disadvantages than advantages in alignment. To reduce maintenance costs, the best choice is not to use horizontal alignment. +- There are more disadvantages than advantages in alignment. To reduce maintenance costs, misalignment (???) is the best choice. @@ -1962,7 +1950,7 @@ \subsubsection*{\textbf{Recommendation 3.8.2}} enum class Warnings(private val id: Int, private val canBeAutoCorrected: Boolean, private val warn: String) : Rule { PACKAGE_NAME_MISSING (1, true, "no package name declared in a file"), PACKAGE_NAME_INCORRECT_CASE (2, true, "package name should be completely in a lower case"), - PACKAGE_NAME_INCORRECT_PREFIX(3, false, "package name should start from company's domain") + PACKAGE_NAME_INCORRECT_PREFIX(3, false, "package name should start from the company's domain") ; } \end{lstlisting} @@ -1986,10 +1974,11 @@ \subsubsection*{\textbf{Recommendation 3.8.2}} \subsection*{\textbf{3.9 Enumerations}} -\subsubsection*{\textbf{Recommendation 3.9.1}} -\leavevmode\newline +Enum values are separated by a comma and line break, with ';' placed on the new line. -1) Enum values are separated by a comma and a line break. `;` is put on the new line: + + +1) The comma and line break characters separate enum values. Put `;` on the new line: \begin{lstlisting}[language=Kotlin] enum class Warnings { @@ -2003,7 +1992,7 @@ \subsubsection*{\textbf{Recommendation 3.9.1}} This will help to resolve conflicts and reduce the number of conflicts during merging pull requests. -Also use [trailing comma](https://kotlinlang.org/docs/reference/whatsnew14.html\#trailing-comma). +Also, use [trailing comma](https://kotlinlang.org/docs/reference/whatsnew14.html\#trailing-comma). @@ -2051,7 +2040,9 @@ \subsubsection*{\textbf{Recommendation 3.9.1}} \subsection*{\textbf{3.10 Variable declaration}} -\subsubsection*{\textbf{Rule 3.10.1}} +This section describes rules for the declaration of variables. + +\subsubsection*{\textbf{3.10.1 Declare one variable per line.}} \leavevmode\newline @@ -2067,7 +2058,7 @@ \subsubsection*{\textbf{Rule 3.10.1}} \end{lstlisting} -\subsubsection*{\textbf{Recommendation 3.10.2}} +\subsubsection*{\textbf{3.10.2 Variables should be declared near the line where they are first used.}} \leavevmode\newline Declare local variables close to the point where they are first used to minimize their scope. This will also increase the readability of the code. @@ -2078,10 +2069,11 @@ \subsubsection*{\textbf{Recommendation 3.10.2}} -\subsection*{\textbf{3.11 When expression}} +\subsection*{\textbf{3.11}} -\subsubsection*{\textbf{Rule 3.11.1}} -\leavevmode\newline + + +The `when` statement must have an 'else' branch unless the condition variable is enumerated or a sealed type. Each `when` statement should contain an `else` statement group, even if it does not contain any code. @@ -2095,12 +2087,11 @@ \subsubsection*{\textbf{Rule 3.11.1}} \subsection*{\textbf{3.12 Annotations}} -\subsubsection*{\textbf{Recommendation 3.12.1}} -\leavevmode\newline +Each annotation applied to a class, method or constructor should be placed on its own line. Consider the following examples: -1. Annotations applied to the class, method, or constructor are placed on separate lines (one annotation per line). +1. Annotations applied to the class, method or constructor are placed on separate lines (one annotation per line). @@ -2135,10 +2126,7 @@ \subsubsection*{\textbf{Recommendation 3.12.1}} \end{lstlisting} -\subsection*{\textbf{3.13 Layout of comments}} - -\subsubsection*{\textbf{Recommendation 3.13.1}} -\leavevmode\newline +\subsection*{\textbf{3.13 Block comments}} @@ -2161,15 +2149,19 @@ \subsubsection*{\textbf{Recommendation 3.13.1}} \end{lstlisting} -\textbf{Suggestion}: Use `/*...*/` block comments to enable automatic formatting by IDEs. +\textbf{Note}: Use `/*...*/` block comments to enable automatic formatting by IDEs. \subsection*{\textbf{3.14 Modifiers and constant values}} -\subsubsection*{\textbf{Recommendation 3.14.1}} +This section contains recommendations regarding modifiers and constant values. + +\subsubsection*{\textbf{3.14.1 Declaration with multiple modifiers}} \leavevmode\newline +If a declaration has multiple modifiers, always follow the proper sequence. + \textbf{Valid sequence:} @@ -2197,9 +2189,11 @@ \subsubsection*{\textbf{Recommendation 3.14.1}} \end{lstlisting} -\subsubsection*{\textbf{Recommendation 3.14.2}} +\subsubsection*{\textbf{3.14.2}} \leavevmode\newline +An underscore character should separate long numerical values. + \textbf{Note:} Using underscores simplifies reading and helps to find errors in numeric constants. \begin{lstlisting}[language=Kotlin] @@ -2213,12 +2207,16 @@ \subsubsection*{\textbf{Recommendation 3.14.2}} \subsection*{\textbf{3.15 Strings}} -\subsubsection*{\textbf{Rule 3.15.1}} +This section describes the general rules of using strings. + + + +\subsubsection*{\textbf{3.15.1 Concatenation of Strings}} \leavevmode\newline String concatenation is prohibited if the string can fit on one line. Use raw strings and string templates instead. Kotlin has significantly improved the use of Strings: -[String templates](https://kotlinlang.org/docs/reference/basic-types.html\#string-templates), [Raw strings](https://kotlinlang.org/docs/reference/basic-types.html\#string-literals) +[String templates](https://kotlinlang.org/docs/reference/basic-types.html\#string-templates), [Raw strings](https://kotlinlang.org/docs/reference/basic-types.html\#string-literals). Therefore, compared to using explicit concatenation, code looks much better when proper Kotlin strings are used for short lines, and you do not need to split them with newline characters. @@ -2240,7 +2238,7 @@ \subsubsection*{\textbf{Rule 3.15.1}} \end{lstlisting} -\subsubsection*{\textbf{Rule 3.15.2}} +\subsubsection*{\textbf{3.15.2 String template format}} \leavevmode\newline \textbf{Redundant curly braces in string templates} @@ -2285,9 +2283,13 @@ \subsubsection*{\textbf{Rule 3.15.2}} \end{lstlisting} \section*{\textbf{4. Variables and types}} +This section is dedicated to the rules and recommendations for using variables and types in your code. + \subsection*{\textbf{4.1 Variables}} -\subsubsection*{\textbf{Rule 4.1.1}} +The rules of using variables are explained in the below topics. + +\subsubsection*{\textbf{4.1.1 Do not use Float and Double types when accurate calculations are needed}} \leavevmode\newline Floating-point numbers provide a good approximation over a wide range of values, but they cannot produce accurate results in some cases. @@ -2314,7 +2316,7 @@ \subsubsection*{\textbf{Rule 4.1.1}} -\textbf{Invalid example}: \ +\textbf{Invalid example}: Float values containing more than six or seven decimal numbers will be rounded. @@ -2332,10 +2334,10 @@ \subsubsection*{\textbf{Rule 4.1.1}} \end{lstlisting} -\subsubsection*{\textbf{Rule 4.1.2}} +\subsubsection*{\textbf{4.1.2}} \leavevmode\newline -Since floating-point numbers involve precision problems in computer representation, it is better to use `BigDecimal` as recommended in [Rule 4.1.1] to make accurate computations and comparisons. The following code describes these problems. +Numeric float type values should not be directly compared with the equality operator (==) or other methods, such as `compareTo()` and `equals()`. Since floating-point numbers involve precision problems in computer representation, it is better to use `BigDecimal` as recommended in [Rule 4.1.1] to make accurate computations and comparisons. The following code describes these problems. @@ -2375,14 +2377,14 @@ \subsubsection*{\textbf{Rule 4.1.2}} \end{lstlisting} -\subsubsection*{\textbf{Rule 4.1.3 Try to use}} +\subsubsection*{\textbf{4.1.3 Try to use}} \leavevmode\newline Variables with the `val` modifier are immutable (read-only). -Code robustness and readability increase when using `val` variables instead of `var` variables. +Using `val` variables instead of `var` variables increases code robustness and readability. This is because `var` variables can be reassigned several times in the business logic. @@ -2392,7 +2394,9 @@ \subsubsection*{\textbf{Rule 4.1.3 Try to use}} \subsection*{\textbf{4.2 Types}} -\subsubsection*{\textbf{Recommendation 4.2.1}} +This section provides recommendations for using types. + +\subsubsection*{\textbf{4.2.1}} \leavevmode\newline @@ -2460,7 +2464,7 @@ \subsubsection*{\textbf{Recommendation 4.2.1}} \end{lstlisting} -\subsubsection*{\textbf{Recommendation 4.2.2}} +\subsubsection*{\textbf{4.2.2}} \leavevmode\newline @@ -2548,7 +2552,7 @@ \subsubsection*{\textbf{Recommendation 4.3.1}} \end{lstlisting} -\subsubsection*{\textbf{Recommendation 4.3.2}} +\subsubsection*{\textbf{4.3.2}} \leavevmode\newline Like in Java, classes in Kotlin may have type parameters. To create an instance of such a class, we typically need to provide type arguments: @@ -2583,9 +2587,6 @@ \subsubsection*{\textbf{Recommendation 4.3.2}} \subsubsection*{\textbf{Null-safety}} \leavevmode\newline -\subsubsection*{\textbf{4.3.3 Explicit null checks}} -\leavevmode\newline - Try to avoid explicit null checks (explicit comparison with `null`) @@ -2693,6 +2694,8 @@ \subsubsection*{\textbf{4.3.3 Explicit null checks}} \section*{\textbf{5. Functions}} +This section describes the rules of using functions in your code. + \subsection*{\textbf{5.1 Function design}} Developers can write clean code by gaining knowledge of how to build design patterns and avoid code smells. @@ -2703,10 +2706,12 @@ \subsection*{\textbf{5.1 Function design}} Functions are the smallest unit of combinable and reusable code. -They should have clean logic, \textbf{high cohesion}, and \textbf{low coupling} to effectively organize the code. +They should have clean logic, \textbf{high cohesion}, and \textbf{low coupling} to organize the code effectively. The code in functions should be simple and not conceal the author's original intentions. + + Additionally, it should have a clean abstraction, and control statements should be used straightforwardly. The side effects (code that does not affect a function's return value but affects global/object instance variables) should not be used for state changes of an object. @@ -2717,7 +2722,7 @@ \subsection*{\textbf{5.1 Function design}} Kotlin is [designed](https://www.slideshare.net/abreslav/whos-more-functional-kotlin-groovy-scala-or-java) to support and encourage functional programming, featuring the corresponding built-in mechanisms. -Also, it supports standard collections and sequences feature methods that enable functional programming (for example, `apply`, `with`, `let`, and `run`), Kotlin Higher-Order functions, function types, lambdas, and default function arguments (???). +Also, it supports standard collections and sequences feature methods that enable functional programming (for example, `apply`, `with`, `let`, and `run`), Kotlin Higher-Order functions, function types, lambdas, and default function arguments. As [previously discussed], Kotlin supports and encourages the use of immutable types, which in turn motivates programmers to write pure functions that avoid side effects and have a corresponding output for specific input. @@ -2743,7 +2748,7 @@ \subsection*{\textbf{5.1 Function design}} -\subsubsection*{\textbf{Rule 5.1.1}} +\subsubsection*{\textbf{5.1.1 Avoid functions that are too long}} \leavevmode\newline @@ -2766,7 +2771,7 @@ \subsubsection*{\textbf{Rule 5.1.1}} This approach will enable other programmers to read and modify the code properly. -\subsubsection*{\textbf{Rule 5.1.2}} +\subsubsection*{\textbf{5.1.2 Avoid deep nesting of function code blocks}} \leavevmode\newline @@ -2783,7 +2788,7 @@ \subsubsection*{\textbf{Rule 5.1.2}} -\subsubsection*{\textbf{Rule 5.1.3}} +\subsubsection*{\textbf{Rule 5.1.3 Avoid using nested functions}} \leavevmode\newline Nested functions create a more complex function context, thereby confusing readers. @@ -2806,7 +2811,9 @@ \subsubsection*{\textbf{Rule 5.1.3}} \subsection*{\textbf{5.2 Function arguments}} -\subsubsection*{\textbf{Rule 5.2.1}} +The rules for using function arguments are described in the below topics. + +\subsubsection*{\textbf{5.2.1 The lambda parameter of the function should be placed at the end of the argument list}} \leavevmode\newline @@ -2830,7 +2837,7 @@ \subsubsection*{\textbf{Rule 5.2.1}} \end{lstlisting} -\subsubsection*{\textbf{Rule 5.2.2}} +\subsubsection*{\textbf{5.2.2 Number of function parameters should be limited to five}} \leavevmode\newline @@ -2845,7 +2852,7 @@ \subsubsection*{\textbf{Rule 5.2.2}} -\subsubsection*{\textbf{Rule 5.2.3 Use default values for function arguments instead of overloading them}} +\subsubsection*{\textbf{5.2.3 Use default values for function arguments instead of overloading them}} \leavevmode\newline In Java, default values for function arguments are prohibited. That is why the function should be overloaded when you need to create a function with fewer arguments. @@ -2878,10 +2885,12 @@ \section*{\textbf{6. Classes}} \subsection*{\textbf{6.1 Classes}} -\subsubsection*{\textbf{Rule 6.1.1}} +This section describes the rules of denoting classes in your code. + +\subsubsection*{\textbf{6.1.1 Denoting a class with a single constructor}} \leavevmode\newline -In case the class contains only one explicit constructor - it should be converted to a primary constructor. +When a class has a single constructor, it should be defined as a primary constructor in the declaration of the class. If the class contains only one explicit constructor, it should be converted to a primary constructor. @@ -2911,7 +2920,7 @@ \subsubsection*{\textbf{Rule 6.1.1}} \end{lstlisting} -\subsubsection*{\textbf{Rule 6.1.2}} +\subsubsection*{\textbf{6.1.2 Prefer data classes instead of classes without any functional logic}} \leavevmode\newline Some people say that the data class is a code smell. However, if you need to use it (which makes your code more simple), you can utilize the Kotlin `data class`. The main purpose of this class is to hold data, @@ -2975,7 +2984,7 @@ \subsubsection*{\textbf{Rule 6.1.2}} -\subsubsection*{\textbf{Rule 6.1.3}} +\subsubsection*{\textbf{6.1.3 Do not use the primary constructor if it is empty or useless}} \leavevmode\newline The primary constructor is a part of the class header; it is placed after the class name and type parameters (optional) but can be omitted if it is not used. @@ -3018,10 +3027,10 @@ \subsubsection*{\textbf{Rule 6.1.3}} \end{lstlisting} -\subsubsection*{\textbf{Rule 6.1.4}} +\subsubsection*{\textbf{6.1.4 Do not use redundant init blocks in your class}} \leavevmode\newline -The primary constructor cannot contain any code. That is why Kotlin has introduced `init` blocks. +Several init blocks are redundant and generally should not be used in your class. The primary constructor cannot contain any code. That is why Kotlin has introduced `init` blocks. These blocks store the code to be run during the class initialization. @@ -3029,7 +3038,7 @@ \subsubsection*{\textbf{Rule 6.1.4}} Even when you follow (rule 3.2)[\#r3.2], this makes your code less readable as the programmer needs to keep in mind all init blocks and trace the execution of the code. -Therefore, you should try to use a single `init` block to reduce the code's complexity. . If you need to do some logging or make some calculations before the class property assignment, you can use powerful functional programming. This will reduce the possibility of the error if your `init` blocks' order is accidentally changed and +Therefore, you should try to use a single `init` block to reduce the code's complexity. If you need to do some logging or make some calculations before the class property assignment, you can use powerful functional programming. This will reduce the possibility of the error if your `init` blocks' order is accidentally changed and make the code logic more coupled. It is always enough to use one `init` block to implement your idea in Kotlin. @@ -3097,10 +3106,10 @@ \subsubsection*{\textbf{Rule 6.1.4}} \end{lstlisting} -\subsubsection*{\textbf{Rule 6.1.5}} +\subsubsection*{\textbf{6.1.5 Explicit supertype qualification}} \leavevmode\newline -This rule is applicable to both interfaces and classes. +The explicit supertype qualification should not be used if there is no clash between called methods. This rule is applicable to both interfaces and classes. @@ -3119,7 +3128,7 @@ \subsubsection*{\textbf{Rule 6.1.5}} \end{lstlisting} -\subsubsection*{\textbf{Rule 6.1.6}} +\subsubsection*{\textbf{6.1.6 Abstract class should have at least one abstract method}} \leavevmode\newline Abstract classes are used to force a developer to implement some of its parts in their inheritors. @@ -3159,7 +3168,7 @@ \subsubsection*{\textbf{Rule 6.1.6}} -\subsubsection*{\textbf{Rule 6.1.7}} +\subsubsection*{\textbf{6.1.7 When using the}} \leavevmode\newline Kotlin has a mechanism of [backing properties](https://kotlinlang.org/docs/reference/properties.html\#backing-properties). @@ -3184,7 +3193,7 @@ \subsubsection*{\textbf{Rule 6.1.7}} -\subsubsection*{\textbf{Recommendation 6.1.8}} +\subsubsection*{\textbf{6.1.8 Avoid using custom getters and setters}} \leavevmode\newline Kotlin has a perfect mechanism of [properties](https://kotlinlang.org/docs/reference/properties.html\#properties-and-fields). @@ -3208,11 +3217,11 @@ \subsubsection*{\textbf{Recommendation 6.1.8}} \end{lstlisting} -From the callee code these methods look like an access to this property: `A().isEmpty = true` for setter and `A().isEmpty` for getter. +From the callee code, these methods look like access to this property: `A().isEmpty = true` for setter and `A().isEmpty` for getter. -However, when `get` and `set` are overridden, it is very confusing for a developer who uses this particular class. +However, when `get` and `set` are overridden, it isn't very clear for a developer who uses this particular class. The developer expects to get the property value but receives some unknown value and some extra side-effect hidden by the custom getter/setter. @@ -3243,7 +3252,7 @@ \subsubsection*{\textbf{Recommendation 6.1.8}} -\subsubsection*{\textbf{Rule 6.1.9}} +\subsubsection*{\textbf{6.1.9 Never use the name of a variable in the custom getter or setter}} \leavevmode\newline If you ignored [recommendation 6.1.8], be careful with using the name of the property in your custom getter/setter @@ -3264,7 +3273,7 @@ \subsubsection*{\textbf{Rule 6.1.9}} \end{lstlisting} -\subsubsection*{\textbf{Recommendation 6.1.10 no trivial getters and setters are allowed in the code.}} +\subsubsection*{\textbf{6.1.10 No trivial getters and setters are allowed in the code}} \leavevmode\newline In Java, trivial getters - are the getters that are just returning the field value. @@ -3301,7 +3310,7 @@ \subsubsection*{\textbf{Recommendation 6.1.10 no trivial getters and setters are \end{lstlisting} -\subsubsection*{\textbf{Rule 6.1.11}} +\subsubsection*{\textbf{Use}} \leavevmode\newline In Java, before functional programming became popular, many classes from common libraries used the configuration paradigm. @@ -3360,15 +3369,19 @@ \subsubsection*{\textbf{Rule 6.1.11}} \subsection*{\textbf{6.2 Extension functions}} +This section describes the rules of using extension functions in your code. + + + [Extension functions](https://kotlinlang.org/docs/reference/extensions.html) is a killer-feature in Kotlin. -It gives you a chance to extend classes that were already implemented in external libraries and help you to make classes less heavy. +It gives you a chance to extend classes that were already implemented in external libraries and helps you to make classes less heavy. Extension functions are resolved statically. -\subsubsection*{\textbf{Recommendation 6.2.1}} +\subsubsection*{\textbf{6.2.1 Use extension functions for making logic of classes less coupled}} \leavevmode\newline It is recommended that for classes, the non-tightly coupled functions, which are rarely used in the class, should be implemented as extension functions where possible. @@ -3377,15 +3390,13 @@ \subsubsection*{\textbf{Recommendation 6.2.1}} -\subsubsection*{\textbf{Rule 6.2.2}} +\subsubsection*{\textbf{6.2.2 No extension functions with the same name and signature if they extend base and inheritor classes}} \leavevmode\newline -As extension functions are resolved statically. In this case, there could be a situation when a developer implements two extension functions: one is for the base class and another for the inheritor. +You should have ho extension functions with the same name and signature if they extend base and inheritor classes (possible\_bug).esolved statically. There could be a situation when a developer implements two extension functions: one is for the base class and another for the inheritor. This can lead to an issue when an incorrect method is used. -And that can lead to an issue when incorrect method is used. - \textbf{Invalid example}: @@ -3422,10 +3433,12 @@ \subsection*{\textbf{6.3 Interfaces}} \subsection*{\textbf{6.4 Objects}} -\subsubsection*{\textbf{Rule 6.4.1}} +This section describes the rules of using objects in code. + +\subsubsection*{\textbf{6.4.1 Instead of using utility classes}} \leavevmode\newline -As described in [6.2 Extension functions], extension functions are a powerful. Instead of using utility classes/objects, use it extention functions. +Avoid using utility classes/objects; use extensions instead. As described in [6.2 Extension functions], using extension functions is a powerful method. This enables you to avoid unnecessary complexity and class/object wrapping and use top-level functions instead. @@ -3454,7 +3467,7 @@ \subsubsection*{\textbf{Rule 6.4.1}} \end{lstlisting} -\subsubsection*{\textbf{Recommendation 6.4.2}} +\subsubsection*{\textbf{6.4.2 Objects should be used for Stateless Interfaces.}} \leavevmode\newline Kotlin’s objects are extremely useful when you need to implement some interface from an external library that does not have any state. From ed9199553b0b2f85d9c24313c9e94af219509278 Mon Sep 17 00:00:00 2001 From: soWhoAmI Date: Wed, 16 Dec 2020 18:53:41 +0300 Subject: [PATCH 5/5] feature/wp-update ### What's done: * Fixed bugs --- .../kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt b/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt index c7050a3540..e733fa2a6e 100644 --- a/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt +++ b/diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/generation/GenerationDocs.kt @@ -23,6 +23,7 @@ fun main() { @Suppress( "LoopWithTooManyJumpStatements", "LongMethod", + "MagicNumber", "ComplexMethod", "NestedBlockDepth", "WRONG_INDENTATION",