├── .github └── ISSUE_TEMPLATE │ ├── add_rule.yaml │ └── change_rule.yaml ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md └── style_guide ├── kotlin-code-style.md ├── markdown-style-guide.md └── resource-naming-guide.md /.github/ISSUE_TEMPLATE/add_rule.yaml: -------------------------------------------------------------------------------- 1 | name: Добавление правила 2 | description: Добавление нового правила в style guide 3 | labels: ["discussion", "add"] 4 | body: 5 | - type: input 6 | id: rule_title 7 | attributes: 8 | label: Новое правило 9 | description: Заголовок нового правила 10 | placeholder: ex. Форматирование лямбда-выражений 11 | validations: 12 | required: true 13 | 14 | - type: textarea 15 | id: rule_body 16 | attributes: 17 | label: Описание правила 18 | description: Развернутое описание правила 19 | placeholder: ex. При написании лямбда-выражения более чем в одну строку всегда использовать именованный аргумент, вместо `it` 20 | validations: 21 | required: false 22 | 23 | - type: textarea 24 | id: rule_code_ex_before 25 | attributes: 26 | label: Пример плохого кода 27 | render: Kotlin 28 | validations: 29 | required: false 30 | 31 | - type: textarea 32 | id: rule_code_ex_after 33 | attributes: 34 | label: Пример хорошего кода 35 | render: Kotlin 36 | validations: 37 | required: true 38 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/change_rule.yaml: -------------------------------------------------------------------------------- 1 | name: Изменение правила 2 | description: Изменение существующего правила из style guide 3 | labels: ["discussion", "change"] 4 | body: 5 | - type: input 6 | id: rule_link 7 | attributes: 8 | label: Ссылка на существующее правило 9 | validations: 10 | required: true 11 | 12 | - type: dropdown 13 | id: rule_type 14 | attributes: 15 | label: Тип 16 | options: 17 | - Удаление 18 | - Изменение 19 | validations: 20 | required: true 21 | 22 | - type: textarea 23 | id: rule_motivation_and_changes 24 | attributes: 25 | label: Мотивация и список изменений 26 | description: Почему и как хочется изменить правило? 27 | placeholder: ex. С приходом Compose лямбды теперь передаём в параметрах чаще и необходимость явно прописывать invoke, как мне кажется, только усложняет чтение кода. 28 | validations: 29 | required: true 30 | 31 | - type: textarea 32 | id: rule_code_ex_before 33 | attributes: 34 | label: Пример плохого кода 35 | render: Kotlin 36 | validations: 37 | required: false 38 | 39 | - type: textarea 40 | id: rule_code_ex_after 41 | attributes: 42 | label: Пример хорошего кода 43 | render: Kotlin 44 | validations: 45 | required: true 46 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | 1. Для добавления нового правила необходимо создать соответствующее Issue 2 | 2. Дождаться комментария от maintainer-ов репозитория 3 | 3. После одобрения Issue сделать fork проекта 4 | 4. Сделать feature ветку с названием нового правила, внести изменения в README.md 5 | 5. Отправить свои изменения в remote репозиторий 6 | 6. Отправить Pull Request 7 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Attribution-ShareAlike 4.0 International 2 | 3 | ======================================================================= 4 | 5 | Creative Commons Corporation ("Creative Commons") is not a law firm and 6 | does not provide legal services or legal advice. Distribution of 7 | Creative Commons public licenses does not create a lawyer-client or 8 | other relationship. Creative Commons makes its licenses and related 9 | information available on an "as-is" basis. Creative Commons gives no 10 | warranties regarding its licenses, any material licensed under their 11 | terms and conditions, or any related information. Creative Commons 12 | disclaims all liability for damages resulting from their use to the 13 | fullest extent possible. 14 | 15 | Using Creative Commons Public Licenses 16 | 17 | Creative Commons public licenses provide a standard set of terms and 18 | conditions that creators and other rights holders may use to share 19 | original works of authorship and other material subject to copyright 20 | and certain other rights specified in the public license below. The 21 | following considerations are for informational purposes only, are not 22 | exhaustive, and do not form part of our licenses. 23 | 24 | Considerations for licensors: Our public licenses are 25 | intended for use by those authorized to give the public 26 | permission to use material in ways otherwise restricted by 27 | copyright and certain other rights. Our licenses are 28 | irrevocable. Licensors should read and understand the terms 29 | and conditions of the license they choose before applying it. 30 | Licensors should also secure all rights necessary before 31 | applying our licenses so that the public can reuse the 32 | material as expected. Licensors should clearly mark any 33 | material not subject to the license. This includes other CC- 34 | licensed material, or material used under an exception or 35 | limitation to copyright. More considerations for licensors: 36 | wiki.creativecommons.org/Considerations_for_licensors 37 | 38 | Considerations for the public: By using one of our public 39 | licenses, a licensor grants the public permission to use the 40 | licensed material under specified terms and conditions. If 41 | the licensor's permission is not necessary for any reason--for 42 | example, because of any applicable exception or limitation to 43 | copyright--then that use is not regulated by the license. Our 44 | licenses grant only permissions under copyright and certain 45 | other rights that a licensor has authority to grant. Use of 46 | the licensed material may still be restricted for other 47 | reasons, including because others have copyright or other 48 | rights in the material. A licensor may make special requests, 49 | such as asking that all changes be marked or described. 50 | Although not required by our licenses, you are encouraged to 51 | respect those requests where reasonable. More_considerations 52 | for the public: 53 | wiki.creativecommons.org/Considerations_for_licensees 54 | 55 | ======================================================================= 56 | 57 | Creative Commons Attribution-ShareAlike 4.0 International Public 58 | License 59 | 60 | By exercising the Licensed Rights (defined below), You accept and agree 61 | to be bound by the terms and conditions of this Creative Commons 62 | Attribution-ShareAlike 4.0 International Public License ("Public 63 | License"). To the extent this Public License may be interpreted as a 64 | contract, You are granted the Licensed Rights in consideration of Your 65 | acceptance of these terms and conditions, and the Licensor grants You 66 | such rights in consideration of benefits the Licensor receives from 67 | making the Licensed Material available under these terms and 68 | conditions. 69 | 70 | 71 | Section 1 -- Definitions. 72 | 73 | a. Adapted Material means material subject to Copyright and Similar 74 | Rights that is derived from or based upon the Licensed Material 75 | and in which the Licensed Material is translated, altered, 76 | arranged, transformed, or otherwise modified in a manner requiring 77 | permission under the Copyright and Similar Rights held by the 78 | Licensor. For purposes of this Public License, where the Licensed 79 | Material is a musical work, performance, or sound recording, 80 | Adapted Material is always produced where the Licensed Material is 81 | synched in timed relation with a moving image. 82 | 83 | b. Adapter's License means the license You apply to Your Copyright 84 | and Similar Rights in Your contributions to Adapted Material in 85 | accordance with the terms and conditions of this Public License. 86 | 87 | c. BY-SA Compatible License means a license listed at 88 | creativecommons.org/compatiblelicenses, approved by Creative 89 | Commons as essentially the equivalent of this Public License. 90 | 91 | d. Copyright and Similar Rights means copyright and/or similar rights 92 | closely related to copyright including, without limitation, 93 | performance, broadcast, sound recording, and Sui Generis Database 94 | Rights, without regard to how the rights are labeled or 95 | categorized. For purposes of this Public License, the rights 96 | specified in Section 2(b)(1)-(2) are not Copyright and Similar 97 | Rights. 98 | 99 | e. Effective Technological Measures means those measures that, in the 100 | absence of proper authority, may not be circumvented under laws 101 | fulfilling obligations under Article 11 of the WIPO Copyright 102 | Treaty adopted on December 20, 1996, and/or similar international 103 | agreements. 104 | 105 | f. Exceptions and Limitations means fair use, fair dealing, and/or 106 | any other exception or limitation to Copyright and Similar Rights 107 | that applies to Your use of the Licensed Material. 108 | 109 | g. License Elements means the license attributes listed in the name 110 | of a Creative Commons Public License. The License Elements of this 111 | Public License are Attribution and ShareAlike. 112 | 113 | h. Licensed Material means the artistic or literary work, database, 114 | or other material to which the Licensor applied this Public 115 | License. 116 | 117 | i. Licensed Rights means the rights granted to You subject to the 118 | terms and conditions of this Public License, which are limited to 119 | all Copyright and Similar Rights that apply to Your use of the 120 | Licensed Material and that the Licensor has authority to license. 121 | 122 | j. Licensor means the individual(s) or entity(ies) granting rights 123 | under this Public License. 124 | 125 | k. Share means to provide material to the public by any means or 126 | process that requires permission under the Licensed Rights, such 127 | as reproduction, public display, public performance, distribution, 128 | dissemination, communication, or importation, and to make material 129 | available to the public including in ways that members of the 130 | public may access the material from a place and at a time 131 | individually chosen by them. 132 | 133 | l. Sui Generis Database Rights means rights other than copyright 134 | resulting from Directive 96/9/EC of the European Parliament and of 135 | the Council of 11 March 1996 on the legal protection of databases, 136 | as amended and/or succeeded, as well as other essentially 137 | equivalent rights anywhere in the world. 138 | 139 | m. You means the individual or entity exercising the Licensed Rights 140 | under this Public License. Your has a corresponding meaning. 141 | 142 | 143 | Section 2 -- Scope. 144 | 145 | a. License grant. 146 | 147 | 1. Subject to the terms and conditions of this Public License, 148 | the Licensor hereby grants You a worldwide, royalty-free, 149 | non-sublicensable, non-exclusive, irrevocable license to 150 | exercise the Licensed Rights in the Licensed Material to: 151 | 152 | a. reproduce and Share the Licensed Material, in whole or 153 | in part; and 154 | 155 | b. produce, reproduce, and Share Adapted Material. 156 | 157 | 2. Exceptions and Limitations. For the avoidance of doubt, where 158 | Exceptions and Limitations apply to Your use, this Public 159 | License does not apply, and You do not need to comply with 160 | its terms and conditions. 161 | 162 | 3. Term. The term of this Public License is specified in Section 163 | 6(a). 164 | 165 | 4. Media and formats; technical modifications allowed. The 166 | Licensor authorizes You to exercise the Licensed Rights in 167 | all media and formats whether now known or hereafter created, 168 | and to make technical modifications necessary to do so. The 169 | Licensor waives and/or agrees not to assert any right or 170 | authority to forbid You from making technical modifications 171 | necessary to exercise the Licensed Rights, including 172 | technical modifications necessary to circumvent Effective 173 | Technological Measures. For purposes of this Public License, 174 | simply making modifications authorized by this Section 2(a) 175 | (4) never produces Adapted Material. 176 | 177 | 5. Downstream recipients. 178 | 179 | a. Offer from the Licensor -- Licensed Material. Every 180 | recipient of the Licensed Material automatically 181 | receives an offer from the Licensor to exercise the 182 | Licensed Rights under the terms and conditions of this 183 | Public License. 184 | 185 | b. Additional offer from the Licensor -- Adapted Material. 186 | Every recipient of Adapted Material from You 187 | automatically receives an offer from the Licensor to 188 | exercise the Licensed Rights in the Adapted Material 189 | under the conditions of the Adapter's License You apply. 190 | 191 | c. No downstream restrictions. You may not offer or impose 192 | any additional or different terms or conditions on, or 193 | apply any Effective Technological Measures to, the 194 | Licensed Material if doing so restricts exercise of the 195 | Licensed Rights by any recipient of the Licensed 196 | Material. 197 | 198 | 6. No endorsement. Nothing in this Public License constitutes or 199 | may be construed as permission to assert or imply that You 200 | are, or that Your use of the Licensed Material is, connected 201 | with, or sponsored, endorsed, or granted official status by, 202 | the Licensor or others designated to receive attribution as 203 | provided in Section 3(a)(1)(A)(i). 204 | 205 | b. Other rights. 206 | 207 | 1. Moral rights, such as the right of integrity, are not 208 | licensed under this Public License, nor are publicity, 209 | privacy, and/or other similar personality rights; however, to 210 | the extent possible, the Licensor waives and/or agrees not to 211 | assert any such rights held by the Licensor to the limited 212 | extent necessary to allow You to exercise the Licensed 213 | Rights, but not otherwise. 214 | 215 | 2. Patent and trademark rights are not licensed under this 216 | Public License. 217 | 218 | 3. To the extent possible, the Licensor waives any right to 219 | collect royalties from You for the exercise of the Licensed 220 | Rights, whether directly or through a collecting society 221 | under any voluntary or waivable statutory or compulsory 222 | licensing scheme. In all other cases the Licensor expressly 223 | reserves any right to collect such royalties. 224 | 225 | 226 | Section 3 -- License Conditions. 227 | 228 | Your exercise of the Licensed Rights is expressly made subject to the 229 | following conditions. 230 | 231 | a. Attribution. 232 | 233 | 1. If You Share the Licensed Material (including in modified 234 | form), You must: 235 | 236 | a. retain the following if it is supplied by the Licensor 237 | with the Licensed Material: 238 | 239 | i. identification of the creator(s) of the Licensed 240 | Material and any others designated to receive 241 | attribution, in any reasonable manner requested by 242 | the Licensor (including by pseudonym if 243 | designated); 244 | 245 | ii. a copyright notice; 246 | 247 | iii. a notice that refers to this Public License; 248 | 249 | iv. a notice that refers to the disclaimer of 250 | warranties; 251 | 252 | v. a URI or hyperlink to the Licensed Material to the 253 | extent reasonably practicable; 254 | 255 | b. indicate if You modified the Licensed Material and 256 | retain an indication of any previous modifications; and 257 | 258 | c. indicate the Licensed Material is licensed under this 259 | Public License, and include the text of, or the URI or 260 | hyperlink to, this Public License. 261 | 262 | 2. You may satisfy the conditions in Section 3(a)(1) in any 263 | reasonable manner based on the medium, means, and context in 264 | which You Share the Licensed Material. For example, it may be 265 | reasonable to satisfy the conditions by providing a URI or 266 | hyperlink to a resource that includes the required 267 | information. 268 | 269 | 3. If requested by the Licensor, You must remove any of the 270 | information required by Section 3(a)(1)(A) to the extent 271 | reasonably practicable. 272 | 273 | b. ShareAlike. 274 | 275 | In addition to the conditions in Section 3(a), if You Share 276 | Adapted Material You produce, the following conditions also apply. 277 | 278 | 1. The Adapter's License You apply must be a Creative Commons 279 | license with the same License Elements, this version or 280 | later, or a BY-SA Compatible License. 281 | 282 | 2. You must include the text of, or the URI or hyperlink to, the 283 | Adapter's License You apply. You may satisfy this condition 284 | in any reasonable manner based on the medium, means, and 285 | context in which You Share Adapted Material. 286 | 287 | 3. You may not offer or impose any additional or different terms 288 | or conditions on, or apply any Effective Technological 289 | Measures to, Adapted Material that restrict exercise of the 290 | rights granted under the Adapter's License You apply. 291 | 292 | 293 | Section 4 -- Sui Generis Database Rights. 294 | 295 | Where the Licensed Rights include Sui Generis Database Rights that 296 | apply to Your use of the Licensed Material: 297 | 298 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right 299 | to extract, reuse, reproduce, and Share all or a substantial 300 | portion of the contents of the database; 301 | 302 | b. if You include all or a substantial portion of the database 303 | contents in a database in which You have Sui Generis Database 304 | Rights, then the database in which You have Sui Generis Database 305 | Rights (but not its individual contents) is Adapted Material, 306 | 307 | including for purposes of Section 3(b); and 308 | c. You must comply with the conditions in Section 3(a) if You Share 309 | all or a substantial portion of the contents of the database. 310 | 311 | For the avoidance of doubt, this Section 4 supplements and does not 312 | replace Your obligations under this Public License where the Licensed 313 | Rights include other Copyright and Similar Rights. 314 | 315 | 316 | Section 5 -- Disclaimer of Warranties and Limitation of Liability. 317 | 318 | a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE 319 | EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS 320 | AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF 321 | ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, 322 | IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, 323 | WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR 324 | PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, 325 | ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT 326 | KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT 327 | ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. 328 | 329 | b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE 330 | TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, 331 | NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, 332 | INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, 333 | COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR 334 | USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN 335 | ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR 336 | DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR 337 | IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. 338 | 339 | c. The disclaimer of warranties and limitation of liability provided 340 | above shall be interpreted in a manner that, to the extent 341 | possible, most closely approximates an absolute disclaimer and 342 | waiver of all liability. 343 | 344 | 345 | Section 6 -- Term and Termination. 346 | 347 | a. This Public License applies for the term of the Copyright and 348 | Similar Rights licensed here. However, if You fail to comply with 349 | this Public License, then Your rights under this Public License 350 | terminate automatically. 351 | 352 | b. Where Your right to use the Licensed Material has terminated under 353 | Section 6(a), it reinstates: 354 | 355 | 1. automatically as of the date the violation is cured, provided 356 | it is cured within 30 days of Your discovery of the 357 | violation; or 358 | 359 | 2. upon express reinstatement by the Licensor. 360 | 361 | For the avoidance of doubt, this Section 6(b) does not affect any 362 | right the Licensor may have to seek remedies for Your violations 363 | of this Public License. 364 | 365 | c. For the avoidance of doubt, the Licensor may also offer the 366 | Licensed Material under separate terms or conditions or stop 367 | distributing the Licensed Material at any time; however, doing so 368 | will not terminate this Public License. 369 | 370 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public 371 | License. 372 | 373 | 374 | Section 7 -- Other Terms and Conditions. 375 | 376 | a. The Licensor shall not be bound by any additional or different 377 | terms or conditions communicated by You unless expressly agreed. 378 | 379 | b. Any arrangements, understandings, or agreements regarding the 380 | Licensed Material not stated herein are separate from and 381 | independent of the terms and conditions of this Public License. 382 | 383 | 384 | Section 8 -- Interpretation. 385 | 386 | a. For the avoidance of doubt, this Public License does not, and 387 | shall not be interpreted to, reduce, limit, restrict, or impose 388 | conditions on any use of the Licensed Material that could lawfully 389 | be made without permission under this Public License. 390 | 391 | b. To the extent possible, if any provision of this Public License is 392 | deemed unenforceable, it shall be automatically reformed to the 393 | minimum extent necessary to make it enforceable. If the provision 394 | cannot be reformed, it shall be severed from this Public License 395 | without affecting the enforceability of the remaining terms and 396 | conditions. 397 | 398 | c. No term or condition of this Public License will be waived and no 399 | failure to comply consented to unless expressly agreed to by the 400 | Licensor. 401 | 402 | d. Nothing in this Public License constitutes or may be interpreted 403 | as a limitation upon, or waiver of, any privileges and immunities 404 | that apply to the Licensor or You, including from the legal 405 | processes of any jurisdiction or authority. 406 | 407 | 408 | ======================================================================= 409 | 410 | Creative Commons is not a party to its public 411 | licenses. Notwithstanding, Creative Commons may elect to apply one of 412 | its public licenses to material it publishes and in those instances 413 | will be considered the “Licensor.” The text of the Creative Commons 414 | public licenses is dedicated to the public domain under the CC0 Public 415 | Domain Dedication. Except for the limited purpose of indicating that 416 | material is shared under a Creative Commons public license or as 417 | otherwise permitted by the Creative Commons policies published at 418 | creativecommons.org/policies, Creative Commons does not authorize the 419 | use of the trademark "Creative Commons" or any other trademark or logo 420 | of Creative Commons without its prior written consent including, 421 | without limitation, in connection with any unauthorized modifications 422 | to any of its public licenses or any other arrangements, 423 | understandings, or agreements concerning use of licensed material. For 424 | the avoidance of doubt, this paragraph does not form part of the 425 | public licenses. 426 | 427 | Creative Commons may be contacted at creativecommons.org. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Style Guides 2 | 3 | Данный репозиторий содержит ряд style guides: 4 | - [Kotlin code style](style_guide/kotlin-code-style.md) 5 | - [Markdown style guide](style_guide/markdown-style-guide.md) 6 | - [Resource naming guide](style_guide/resource-naming-guide.md) -------------------------------------------------------------------------------- /style_guide/kotlin-code-style.md: -------------------------------------------------------------------------------- 1 | # Kotlin Code Style 2 | 3 | В данном документе приведен набор соглашений по оформлению кода на языке Kotlin. 4 | 5 | Этот список правил расширяет предложенные [Google](https://android.github.io/kotlin-guides/style.html) и [командой разработки Kotlin](https://kotlinlang.org/docs/reference/coding-conventions.html) гайды и пересматривает в них некоторые неоднозначные моменты. 6 | 7 | 8 | 9 | 10 | - [Длина строки](#%D0%94%D0%BB%D0%B8%D0%BD%D0%B0-%D1%81%D1%82%D1%80%D0%BE%D0%BA%D0%B8) 11 | - [Правила именования](#%D0%9F%D1%80%D0%B0%D0%B2%D0%B8%D0%BB%D0%B0-%D0%B8%D0%BC%D0%B5%D0%BD%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F) 12 | - [Форматирование выражений](#%D0%A4%D0%BE%D1%80%D0%BC%D0%B0%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5-%D0%B2%D1%8B%D1%80%D0%B0%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9) 13 | - [Функции](#%D0%A4%D1%83%D0%BD%D0%BA%D1%86%D0%B8%D0%B8) 14 | - [Функции с одним выражением](#%D0%A4%D1%83%D0%BD%D0%BA%D1%86%D0%B8%D0%B8-%D1%81-%D0%BE%D0%B4%D0%BD%D0%B8%D0%BC-%D0%B2%D1%8B%D1%80%D0%B0%D0%B6%D0%B5%D0%BD%D0%B8%D0%B5%D0%BC) 15 | - [Именованные аргументы](#%D0%98%D0%BC%D0%B5%D0%BD%D0%BE%D0%B2%D0%B0%D0%BD%D0%BD%D1%8B%D0%B5-%D0%B0%D1%80%D0%B3%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B) 16 | - [Вызов переменной функционального типа](#%D0%92%D1%8B%D0%B7%D0%BE%D0%B2-%D0%BF%D0%B5%D1%80%D0%B5%D0%BC%D0%B5%D0%BD%D0%BD%D0%BE%D0%B9-%D1%84%D1%83%D0%BD%D0%BA%D1%86%D0%B8%D0%BE%D0%BD%D0%B0%D0%BB%D1%8C%D0%BD%D0%BE%D0%B3%D0%BE-%D1%82%D0%B8%D0%BF%D0%B0) 17 | - [Форматирование лямбда-выражений](#%D0%A4%D0%BE%D1%80%D0%BC%D0%B0%D1%82%D0%B8%D1%80%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5-%D0%BB%D1%8F%D0%BC%D0%B1%D0%B4%D0%B0-%D0%B2%D1%8B%D1%80%D0%B0%D0%B6%D0%B5%D0%BD%D0%B8%D0%B9) 18 | - [Классы](#%D0%9A%D0%BB%D0%B0%D1%81%D1%81%D1%8B) 19 | - [Структура класса](#%D0%A1%D1%82%D1%80%D1%83%D0%BA%D1%82%D1%83%D1%80%D0%B0-%D0%BA%D0%BB%D0%B0%D1%81%D1%81%D0%B0) 20 | - [Аннотации](#%D0%90%D0%BD%D0%BD%D0%BE%D1%82%D0%B0%D1%86%D0%B8%D0%B8) 21 | - [Использование условных операторов](#%D0%98%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5-%D1%83%D1%81%D0%BB%D0%BE%D0%B2%D0%BD%D1%8B%D1%85-%D0%BE%D0%BF%D0%B5%D1%80%D0%B0%D1%82%D0%BE%D1%80%D0%BE%D0%B2) 22 | - [Template header](#template-header) 23 | - [Частые ошибки](#%D0%A7%D0%B0%D1%81%D1%82%D1%8B%D0%B5-%D0%BE%D1%88%D0%B8%D0%B1%D0%BA%D0%B8) 24 | - [Вызов toString() у nullable объектов](#%D0%92%D1%8B%D0%B7%D0%BE%D0%B2-tostring-%D1%83-nullable-%D0%BE%D0%B1%D1%8A%D0%B5%D0%BA%D1%82%D0%BE%D0%B2) 25 | - [Использование orEmpty() вместо ?:](#%D0%98%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5-orempty-%D0%B2%D0%BC%D0%B5%D1%81%D1%82%D0%BE-) 26 | - [Проверка nullable boolean](#%D0%9F%D1%80%D0%BE%D0%B2%D0%B5%D1%80%D0%BA%D0%B0-nullable-boolean) 27 | 28 | 29 | 30 | ## Длина строки 31 | 32 | **Рекомендуемая** длина строки: 100 символов. 33 | 34 | **Максимальная** длина строки: 120 символов. 35 | 36 | ## Правила именования 37 | 38 | Пакеты именуются **одним** словом в стиле lowercase. Если необходимо использовать несколько слов, то просто склеиваем их вместе. 39 | 40 | При объявлении констант, полей или аргументов функций рекомендуется дополнительно указывать размерность, если контекст или название функции не дает однозначного понимания их назначения: 41 | ```kotlin 42 | // Bad 43 | const val TIMEOUT = 1000L 44 | const val PADDING = 24 45 | 46 | // Bad 47 | fun someFunction(timeout: Long) 48 | 49 | // Bad 50 | val defaultTimeout get() = 1000L 51 | 52 | // Good 53 | const val TIMEOUT_MILLIS = 1000L 54 | const val PADDING_DP = 24 55 | 56 | // Good 57 | val TIMEOUT = 1000.milliseconds 58 | val PADDING = 24.dp 59 | 60 | // Good 61 | fun preferGoodNames(timeoutMillis: Long) 62 | 63 | // Good 64 | val defaultTimeoutMillis get() = 1000L 65 | ``` 66 | 67 | ## Форматирование выражений 68 | 69 | При переносе на новую строку цепочки вызова методов символ `.` или оператор `?.` переносятся на следующую строку, property при этом разрешается оставлять на одной строке: 70 | 71 | ```kotlin 72 | val collectionItems = source.collectionItems 73 | ?.dropLast(10) 74 | ?.sortedBy { it.progress } 75 | ``` 76 | 77 | Элвис оператор `?:` в многострочном выражении также переносится на новую строку: 78 | 79 | ```kotlin 80 | val throwableMessage: String = throwable?.message 81 | ?: DEFAULT_ERROR_MESSAGE 82 | 83 | throwable.message?.let { showError(it) } 84 | ?: showError(DEFAULT_ERROR_MESSAGE) 85 | ``` 86 | 87 | Если перед элвис оператором `?:` многострочная лямбда, желательно перенести также и лямбду: 88 | 89 | ```kotlin 90 | // Good 91 | throwable.message 92 | ?.let { message -> 93 | ... 94 | showError(message) 95 | } 96 | ?: showError(DEFAULT_ERROR_MESSAGE) 97 | 98 | // Not recommended 99 | throwable.message?.let { message -> 100 | ... 101 | showError(message) 102 | } 103 | ?: showError(DEFAULT_ERROR_MESSAGE) 104 | ``` 105 | 106 | При описании переменной с делегатом, не помещающимися на одной строке, оставлять описание с открывающейся фигурной скобкой на одной строке, перенося остальное выражение на следующую строку: 107 | 108 | ```kotlin 109 | private val promoItem: MarkPromoItem by lazy { 110 | extractNotNull(BUNDLE_FEED_UNIT_KEY) as MarkPromoItem 111 | } 112 | ``` 113 | 114 | ## Функции 115 | 116 | ### Функции с одним выражением 117 | 118 | Позволительно использовать функцию с одним выражением только в том случае, если она помещается в одну строку. 119 | 120 | ### Именованные аргументы 121 | 122 | Если по контексту не понятно назначение аргумента, то следует сделать его именованным. 123 | 124 | ```kotlin 125 | runOperation( 126 | method = operation::run, 127 | consumer, 128 | errorHandler, 129 | tag, 130 | cacheSize = 3, 131 | cacheMode 132 | ) 133 | calculateSquare(x = 6, y = 19) 134 | getCurrentUser(skipCache = false) 135 | setProgressBarVisible(true) 136 | ``` 137 | 138 | Если именованные аргументы не помещаются на одной строке, то следует переносить каждый аргумент на новую строку (как в примере выше). 139 | 140 | Именуем все лямбды, принимаемые функцией в качестве аргументов (кроме случаев когда лямбда вынесена за круглые скобки), 141 | чтобы во время чтения кода было понятно назначение и ответственность каждой лямбды. 142 | 143 | ```kotlin 144 | editText.addTextChangedListener( 145 | onTextChanged = { text, _, _, _ -> 146 | viewModel.onTextChanged(text?.toString()) 147 | }, 148 | afterTextChanged = { text -> 149 | viewModel.onAfterTextChanged(text?.toString()) 150 | } 151 | ) 152 | ``` 153 | 154 | Полезно именовать аргументы одинаковых типов, чтобы случайно не перепутать их местами. 155 | 156 | ```kotlin 157 | val startDate: Date = .. 158 | val endDate: Date = .. 159 | compareDates(startDate = startDate, endDate = endDate) 160 | ``` 161 | 162 | Полезно именовать аргумент при передаче `null`. 163 | 164 | ```kotlin 165 | setAdditionalArguments(arguments = null) 166 | ``` 167 | 168 | ### Вызов переменной функционального типа 169 | 170 | Допускается вызов лямбды как с `invoke`, так и сокращенный вариант `()`, если отсутствуют договоренности внутри проекта. Однако явный `invoke` имеет ряд преимуществ: 171 | 172 | > [!TIP] 173 | > Одной из основных причин использования явного `invoke` является концептуальное разделение функции как члена класса и лямбды как входного параметра функции. 174 | > Используя `invoke` явно, мы показываем, что используем лямбду, а не функцию. 175 | > 176 | > При этом дополнительным аргументом к использованию `invoke` является его заметность. Вызывая лямбду без `invoke`, у нее можно потерять скобки в месте вызова, что приведет к некорректному поведению. 177 | 178 | ```kotlin 179 | @Composable 180 | fun ProfileScreenContent( 181 | header: @Composable LazyItemScope.() -> Unit, 182 | body: @Composable LazyListScope.() -> Unit, 183 | footer: @Composable LazyItemScope.() -> Unit, 184 | ) { 185 | LazyColumn { 186 | item(content = header) 187 | 188 | // Bad 189 | body 190 | // Good 191 | body() 192 | body.invoke(this@LazyColumn) 193 | 194 | item(content = footer) 195 | } 196 | } 197 | ``` 198 | 199 | ### Форматирование лямбда-выражений 200 | 201 | По возможности передавать метод по ссылке: 202 | 203 | ```kotlin 204 | viewPager.adapter = QuestAdapter(quest, onQuestClickListener = ::onQuestClicked) 205 | ``` 206 | 207 | При написании лямбда-выражения более чем в одну строку всегда использовать именованный аргумент, вместо `it`: 208 | 209 | ```kotlin 210 | viewPager.adapter = QuestAdapter( 211 | quest, 212 | onQuestClickListener = { quest -> 213 | Log.d(..) 214 | viewModel.onQuestClicked(quest) 215 | } 216 | ) 217 | ``` 218 | 219 | Неиспользуемые параметры лямбда-выражений всегда заменять символом `_`. 220 | 221 | ## Классы 222 | 223 | Если описание класса не помещается в одну строку, и класс реализует несколько интерфейсов, то применять стандартные правила переноса, 224 | т.е. делать перенос только в случае, когда описание не помещается на одну строку, при этом продолжать перечисление интерфейсов на следующей строке. 225 | 226 | ```kotlin 227 | class MyFavouriteVeryLongClassHolder : MyLongHolder(), SomeOtherInterface, AndAnotherOne, 228 | OneMoreVeryLongInteface, OneMore{ 229 | 230 | fun foo() { /*...*/ } 231 | } 232 | ``` 233 | 234 | Использование именованных аргументов [аналогично с функциями](#%D0%B8%D0%BC%D0%B5%D0%BD%D0%BE%D0%B2%D0%B0%D0%BD%D0%BD%D1%8B%D0%B5-%D0%B0%D1%80%D0%B3%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D1%8B) 235 | 236 | ## Структура класса 237 | 238 | 1) Поля: abstract, override, public, internal, protected, private 239 | 2) Блок инициализации: init, конструкторы 240 | 3) Абстрактные методы 241 | 4) Переопределенные методы родительского класса (желательно в порядке их следования в родительском классе) 242 | 5) Реализации методов интерфейсов (желательно в порядке добавления интерфейсов в класс и следования методов в каждом интерфейсе) 243 | 6) Методы класса ([в логическом порядке](https://kotlinlang.org/docs/coding-conventions.html#class-layout). Например, метод располагается после того, в котором впервые упомянут). Можно перемешивать с методами из пунктов 3, 4, 5. 244 | 7) inner классы 245 | 8) companion object 246 | 247 | ## Аннотации 248 | 249 | Аннотации располагаются над описанием класса/поля/метода, к которому они применяются. 250 | 251 | Если к классу/полю/методу применяется несколько аннотаций, размещать каждую аннотацию с новой строки: 252 | 253 | ```kotlin 254 | @JsonValue 255 | @JvmField 256 | var promoItem: PromoItem? = null 257 | ``` 258 | 259 | Аннотации к аргументам в конструкторе класса или объявлении функции можно писать на той же строке, что и соответствующий аргумент. 260 | При этом если аннотаций к одному аргументу несколько, то все аннотации пишутся с новой строки, и соответствующий аргумент отделяется от других сверху и снизу пустыми строками. 261 | 262 | ```kotlin 263 | data class UserInfo ( 264 | @SerializedName("firstName") val firstName: String? = null, 265 | @SerializedName("secondName") val secondName: String? = null 266 | ) 267 | 268 | @Entity(tableName = "users") 269 | data class UserInfo ( 270 | @PrimaryKey val id: Int, 271 | 272 | @SerializedName("firstName") 273 | @ColumnInfo(name = "firstName") 274 | val firstName: String? = null, 275 | 276 | @SerializedName("secondName") 277 | @ColumnInfo(name = "secondName") 278 | val secondName: String? = null 279 | ) 280 | ``` 281 | 282 | ## Использование условных операторов 283 | 284 | Не обрамлять `if` выражения в фигурные скобки только если условный оператор `if` помещается в одну строку. 285 | По возможности использовать условные операторы, как выражение: 286 | 287 | ```kotlin 288 | return if (condition) foo() else bar() 289 | ``` 290 | 291 | В операторе `when` ветки, состоящие более чем из одной строки, обрамлять фигурными скобками и отделять от других case-веток пустыми строками сверху и снизу. 292 | 293 | ```kotlin 294 | when (feed.type) { 295 | FeedType.PERSONAL -> startPersonalFeedScreen() 296 | 297 | FeedType.SUM -> { 298 | showSumLayout() 299 | hideProgressBar() 300 | } 301 | 302 | FeedType.CARD -> startCardFeedScreen() 303 | else -> showError() 304 | } 305 | ``` 306 | 307 | ## Template header 308 | 309 | Не использовать Template Header для классов (касается авторства и даты создания файла). 310 | 311 | ## Частые ошибки 312 | 313 | ### Вызов toString() у nullable объектов 314 | 315 | В первом примере получится строчка `"null"`, это плохо. 316 | Необходимо сделать так, чтобы в таком случае возвращалась пустая строка `""` 317 | 318 | ```kotlin 319 | binding.authInputPassword.addTextChangeListener { editable: Editable? -> 320 | // Bad 321 | viewModel.onPasswordChanged(editable.toString()) 322 | 323 | // Good 324 | viewModel.onPasswordChanged(editable?.toString().orEmpty()) 325 | } 326 | ``` 327 | 328 | ### Использование orEmpty() вместо ?: 329 | 330 | Для коллекций и строк использовать `orEmpty()`. 331 | 332 | ```kotlin 333 | // Bad 334 | nullableString ?: "" 335 | nullableObject?.toString() ?: "" 336 | someList ?: emptyList() 337 | 338 | // Good 339 | nullableString.orEmpty() 340 | nullableObject?.toString().orEmpty() 341 | someList.orEmpty() 342 | ``` 343 | 344 | ### Проверка nullable boolean 345 | 346 | При проверке nullable boolean вместо добавления `?: false` в условии явно проверять `boolean == true` 347 | Это одна из общепринятных [идиом](https://kotlinlang.org/docs/idioms.html#nullable-boolean) Kotlin. 348 | 349 | ```kotlin 350 | // Bad 351 | val b: Boolean? = ... 352 | if (boolean ?: false) { 353 | ... 354 | } else { 355 | // `b` is false or null 356 | } 357 | 358 | // Good 359 | val b: Boolean? = ... 360 | if (b == true) { 361 | ... 362 | } else { 363 | // `b` is false or null 364 | } 365 | ``` 366 | -------------------------------------------------------------------------------- /style_guide/markdown-style-guide.md: -------------------------------------------------------------------------------- 1 | # Markdown Style Guide 2 | 3 | Формат Markdown отлично подходит для документации. 4 | Его легко читать и изменять без применения специальных редакторов. 5 | 6 | Этот кодстайл помогает нам достичь трёх целей: 7 | 8 | 1. Markdown документы легко читать не только в отрендеренном виде, но и в исходном коде. 9 | 2. Документы легко поддерживать - редактировать, проводить ревью. Стиль на разных проектах не отличается. 10 | 3. Синтаксис простой и запоминаемый. 11 | 12 | > Перед прочтением кодстайла ознакомьтесь с синтаксисом Markdown: 13 | > 14 | > - [Синтаксис Markdown][syntax] - синтаксис, который поддерживается везде 15 | > - [CommonMark] - спецификация Markdown, совместимая с большинством платформ 16 | > - [GitHub Flavored Markdown][ghfm] - дополнительные возможности, которые добавляет GitHub 17 | > - [GitLab Flavored Markdown][glfm] - дополнительные возможности, которые добавляет GitLab 18 | > - [VuePress Extensions for Markdown][vuepress-markdown] - дополнительные возможности для работы с Markdown в VuePress 19 | > 20 | > Частично пункты кодстайла взяты из [Markdown style guide от Google][google-style]. 21 | 22 | --- 23 | 24 | 25 | 26 | Оглавление: 27 | 28 | - [Именование файла](#%D0%B8%D0%BC%D0%B5%D0%BD%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5-%D1%84%D0%B0%D0%B9%D0%BB%D0%B0) 29 | - [Язык документа](#%D1%8F%D0%B7%D1%8B%D0%BA-%D0%B4%D0%BE%D0%BA%D1%83%D0%BC%D0%B5%D0%BD%D1%82%D0%B0) 30 | - [Структура файла](#%D1%81%D1%82%D1%80%D1%83%D0%BA%D1%82%D1%83%D1%80%D0%B0-%D1%84%D0%B0%D0%B9%D0%BB%D0%B0) 31 | - [Оглавление](#%D0%BE%D0%B3%D0%BB%D0%B0%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D0%B5) 32 | - [Перенос строки](#%D0%BF%D0%B5%D1%80%D0%B5%D0%BD%D0%BE%D1%81-%D1%81%D1%82%D1%80%D0%BE%D0%BA%D0%B8) 33 | - [Перенос после предложения](#%D0%BF%D0%B5%D1%80%D0%B5%D0%BD%D0%BE%D1%81-%D0%BF%D0%BE%D1%81%D0%BB%D0%B5-%D0%BF%D1%80%D0%B5%D0%B4%D0%BB%D0%BE%D0%B6%D0%B5%D0%BD%D0%B8%D1%8F) 34 | - [Принудительный перенос строки](#%D0%BF%D1%80%D0%B8%D0%BD%D1%83%D0%B4%D0%B8%D1%82%D0%B5%D0%BB%D1%8C%D0%BD%D1%8B%D0%B9-%D0%BF%D0%B5%D1%80%D0%B5%D0%BD%D0%BE%D1%81-%D1%81%D1%82%D1%80%D0%BE%D0%BA%D0%B8) 35 | - [Заголовки](#%D0%B7%D0%B0%D0%B3%D0%BE%D0%BB%D0%BE%D0%B2%D0%BA%D0%B8) 36 | - [Стиль заголовков - ATX](#%D1%81%D1%82%D0%B8%D0%BB%D1%8C-%D0%B7%D0%B0%D0%B3%D0%BE%D0%BB%D0%BE%D0%B2%D0%BA%D0%BE%D0%B2-atx) 37 | - [Отступы вокруг заголовка](#%D0%BE%D1%82%D1%81%D1%82%D1%83%D0%BF%D1%8B-%D0%B2%D0%BE%D0%BA%D1%80%D1%83%D0%B3-%D0%B7%D0%B0%D0%B3%D0%BE%D0%BB%D0%BE%D0%B2%D0%BA%D0%B0) 38 | - [Списки](#%D1%81%D0%BF%D0%B8%D1%81%D0%BA%D0%B8) 39 | - [Ленивая нумерация списков](#%D0%BB%D0%B5%D0%BD%D0%B8%D0%B2%D0%B0%D1%8F-%D0%BD%D1%83%D0%BC%D0%B5%D1%80%D0%B0%D1%86%D0%B8%D1%8F-%D1%81%D0%BF%D0%B8%D1%81%D0%BA%D0%BE%D0%B2) 40 | - [Фрагменты кода](#%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82%D1%8B-%D0%BA%D0%BE%D0%B4%D0%B0) 41 | - [Inline](#inline) 42 | - [Блоки кода](#%D0%B1%D0%BB%D0%BE%D0%BA%D0%B8-%D0%BA%D0%BE%D0%B4%D0%B0) 43 | - [Ссылки](#%D1%81%D1%81%D1%8B%D0%BB%D0%BA%D0%B8) 44 | - [Информативные названия ссылок](#%D0%B8%D0%BD%D1%84%D0%BE%D1%80%D0%BC%D0%B0%D1%82%D0%B8%D0%B2%D0%BD%D1%8B%D0%B5-%D0%BD%D0%B0%D0%B7%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F-%D1%81%D1%81%D1%8B%D0%BB%D0%BE%D0%BA) 45 | - [Алиасы ссылок](#%D0%B0%D0%BB%D0%B8%D0%B0%D1%81%D1%8B-%D1%81%D1%81%D1%8B%D0%BB%D0%BE%D0%BA) 46 | - [Изображения](#%D0%B8%D0%B7%D0%BE%D0%B1%D1%80%D0%B0%D0%B6%D0%B5%D0%BD%D0%B8%D1%8F) 47 | - [Ссылка изображения](#%D1%81%D1%81%D1%8B%D0%BB%D0%BA%D0%B0-%D0%B8%D0%B7%D0%BE%D0%B1%D1%80%D0%B0%D0%B6%D0%B5%D0%BD%D0%B8%D1%8F) 48 | 49 | 50 | 51 | ## Именование файла 52 | 53 | Используем `lower_snake_case` за исключением общепринятых имён файлов: `README.md`, `CHANGELOG.md`, `LICENSE.md`, `CONTRIBUTING.md` и т.д. 54 | 55 | Имя файла должно отражать его содержимое и в идеальном случае совпадать с заголовком документа. 56 | Исключение - файлы `README.md` и `index.md`, которые отображаются при открытии каталога по умолчанию. 57 | 58 | Если внутри каталога важен порядок Markdown файлов, используйте цифры в качестве префикса имени файла: 59 | 60 | ``` 61 | guide 62 | ├── 01_getting_started.md 63 | ├── 02_configuration.md 64 | ├── ... 65 | └── 12_changelog.md 66 | ``` 67 | 68 | ## Язык документа 69 | 70 | Выбор русского или английского языка для документа зависит от области применения. 71 | Английский язык следует выбрать, если вы не хотите ограничивать применение документа русскоязычной аудиторией, например если это документация к библиотеке. 72 | В остальных случаях лучше выбрать русский язык, чтобы снизить порог входа и исключить недопонимание из-за языкового барьера. 73 | 74 | ## Структура файла 75 | 76 | Для большинства документов достаточно такой структуры: 77 | 78 | ```markdown 79 | # Заголовок документа 80 | 81 | Краткое вступление. 82 | 83 | Оглавление (TOC) 84 | 85 | ## Заголовок раздела 86 | 87 | Содержимое раздела. 88 | ``` 89 | 90 | - `# Заголовок документа`: в идеале должен совпадать или почти совпадать с названием файла, если документ написан на английском 91 | - `Краткое вступление`: вступление из нескольких предложений, которое даёт понимание о содержании документа. 92 | Представьте, что вы не знакомы с темой, описанной в документе. 93 | Прочитав вступление вы должны понять о чем этот документ и для чего он написан. 94 | - `Оглавление (TOC)`: предоставляет механизм навигации к нужной теме. 95 | Подробнее способы создания оглавления рассмотрены в отдельном разделе - ["Оглавление"](#оглавление). 96 | - `## Заголовок раздела`: заголовки, начиная со второго уровня. 97 | 98 | > Хорошая практика - оставлять ссылки на дополнительные материалы, относящиеся к теме, в конце документа. 99 | > Так вы поможете пользователям, которые хотят глубже погрузиться в тему или не нашли нужную информацию в вашем документе. 100 | 101 | ### Оглавление 102 | 103 | На платформах с поддержкой Markdown часто есть поддержка автоматической генерации оглавления. 104 | Например, в GitLab нужно для этого использовать тег `[[_TOC_]]`: 105 | 106 | ```markdown 107 | Краткое вступление. 108 | 109 | [[_TOC_]] 110 | 111 | ## Заголовок раздела 112 | ``` 113 | 114 | > При просмотре отрендеренного документа вместо тега `[[_TOC_]]` отобразится оглавление со ссылками на разделы. 115 | 116 | Функция генерации оглавления не входит в [спецификацию CommonMark][commonmark], поэтому её реализация отличается в зависимости от платформы: 117 | 118 | - [GitLab - `[[_TOC_]]`][gitlab-toc] 119 | - [GitHub - _Нет поддержки_][github-toc] 120 | - [VuePress - `[[toc]]`][vuepress-toc] 121 | 122 | Если вам нужно, чтобы документ одинаково отображался на разных платформах, не используйте тег для автоматической генерации оглавления. 123 | Универсальное решение - генерировать оглавление с помощью утилиты [DocToc]. 124 | 125 | ## Перенос строки 126 | 127 | Ограничения по длине строки нет. 128 | Для удобства чтения файлов, используйте редактор, который поддерживает "soft wrapping" - когда длинная строка визуально отображается на нескольких строках, но физически остаётся одной строкой. 129 | 130 | ### Перенос после предложения 131 | 132 | Строку переносим после каждого предложения. 133 | Благодаря переносу по предложениям, а не по длине строки, получается меньше изменённых строк и такие изменения проще ревьюить. 134 | 135 | Если вы используете перенос по длине строки, при изменении одной строки в параграфе скорее всего придётся вносить изменения и во все следующие за ней строки. 136 | Худший случай - изменение длины первой строки: 137 | 138 | ```diff 139 | - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras a ullamcorper 140 | - enim, eu eleifend elit. Orci varius natoque penatibus et magnis dis parturient 141 | - montes, nascetur ridiculus mus. Praesent quis magna ipsum. 142 | + Lorem ipsum dolor sit amet, consectetur. Cras a ullamcorper enim, eu eleifend 143 | + elit. Orci varius natoque penatibus et magnis dis parturient montes, nascetur 144 | + ridiculus mus. Praesent quis magna ipsum. 145 | ``` 146 | 147 | Если использовать перенос по предложениям, будет изменена только одна строка: 148 | 149 | ```diff 150 | - Lorem ipsum dolor sit amet, consectetur adipiscing elit. 151 | + Lorem ipsum dolor sit amet, consectetur. 152 | Cras a ullamcorper enim, eu eleifend elit. 153 | Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. 154 | Praesent quis magna ipsum. 155 | ``` 156 | 157 | ### Принудительный перенос строки 158 | 159 | [Спецификация CommonMark][commonmark-hard-wrap] даёт нам два варианта переноса строки внутри параграфа: 160 | 161 | 1. Добавление двух и более пробелов в конце строки 162 | 2. Добавление обратного слеша (`\`) в конце строки 163 | 164 | Всегда используйте обратный слеш для принудительного переноса. 165 | Строку заканчивающуюся двумя пробелами невозможно отличить от строки без пробелов в конце без редактора, который умеет подсвечивать пробелы в конце строк. 166 | Кроме того, многие удаляют пробелы в конце строк при автоматическом форматировании. 167 | 168 | Для переноса строки не используем HTML тег `
`. 169 | Параграфы разделяем пустыми строками. 170 | 171 | ## Заголовки 172 | 173 | ### Стиль заголовков - ATX 174 | 175 | ```markdown 176 | ## Heading 2 177 | ``` 178 | 179 | Всегда используем заголовки в стиле ATX (с `#`). 180 | Заголовки в стиле SETEXT (с `-` и `=`) сложнее поддерживать: 181 | 182 | - при изменении длины заголовка, нужно изменить и строку под заголовком, если хочется чтобы заголовок оставался красивым 183 | - чтобы поменять уровень заголовка, нужно заменить все символы под заголовком, в то время как для стиля ATX достаточно добавить или убрать один символ 184 | - в стиле SETEXT можно объявить заголовки только 1-го и 2-го уровня, для заголовков 3-го и дальше уровня всё равно придётся использовать ATX 185 | - легко перепутать уровень заголовка. 186 | 187 | ```markdown 188 | Heading 1 or 2? 189 | --------------- 190 | ``` 191 | 192 | ### Отступы вокруг заголовка 193 | 194 | Отделяем заголовок от остального текста пустыми строками: 195 | 196 | ```markdown 197 | Текст перед заголовком. 198 | 199 | ## Заголовок 200 | 201 | Текст после заголовка 202 | ``` 203 | 204 | Без отступов заголовок сливается с текстом и становится менее заметен:󠁇 205 | 206 | ```markdown 207 | Текст перед заголовком. 208 | 209 | ## Заголовок 210 | Текст после заголовка. Не делайте так, нужно добавить пустую строку перед текстом. 211 | ``` 212 | 213 | ## Списки 214 | 215 | Списки отделяем от остального текста документа пустыми строками. 216 | Тогда изменения вносимые в список в диффах не будут смешиваться с изменениями текста документа: 217 | 218 | ```markdown 219 | Текст документа. 220 | 221 | - Item 1 222 | - Item 2 223 | 224 | Продолжение текста. 225 | ``` 226 | 227 | ### Ленивая нумерация списков 228 | 229 | Для нумерованных списков, которые могут изменяться используем ленивую нумерацию. 230 | Такие списки проще поддерживать, потому что при добавлении нового элемента в список индексы последующих элементов не изменятся: 231 | 232 | ```markdown 233 | 1. Item A 234 | 1. Item B 235 | 1. Item B.1 236 | 1. Item B.2 237 | 1. Item C 238 | ``` 239 | 240 | Если список небольшой и вы не планируете его изменять, лучше полностью пронумеровать его. 241 | Такой список проще читать в коде: 242 | 243 | ```markdown 244 | 1. Item A 245 | 2. Item B 246 | 3. Item C 247 | ``` 248 | 249 | ## Фрагменты кода 250 | 251 | ### Inline 252 | 253 | Используйте \`бэктики\` для выделения `кода` и имен файлов и пакетов внутри абзаца: 254 | 255 | ```markdown 256 | Чтобы обновить оглавление в файле `README.md`, 257 | запустите команду `doctoc README.md`. 258 | ``` 259 | 260 | Не стоит заключать в бэктики названия библиотек или технологий: 261 | 262 | ```markdown 263 | Мы используем `Kotlin` и бэктики где ни попадя. 264 | Не делайте `так`. 265 | ``` 266 | 267 | ### Блоки кода 268 | 269 | Во всех случаях когда вам не нужно встраивать код в абзац, используйте блоки кода: 270 | 271 | ~~~markdown 272 | ```kotlin 273 | dependencies { 274 | implementation(platform(kotlin("bom", version = 1.5.21))) 275 | } 276 | ``` 277 | ~~~ 278 | 279 | Всегда указывайте язык для блоков кода, тогда будет работать подсветка синтаксиса. 280 | 281 | Отступ в 4 пробела тоже интерпретируется как блок кода. 282 | У таких блоков нельзя указать язык, но они выглядят немного чище в коде. 283 | Используйте блоки кода с отступами если нужно написать несколько однострочных сниппетов подряд: 284 | 285 | ```markdown 286 | Установите YARN: 287 | 288 | npm install -g yarn 289 | 290 | После этого установите зависимости: 291 | 292 | yarn install 293 | 294 | Теперь можно запустить локальный сервер с документацией: 295 | 296 | yarn docs:dev 297 | 298 | ``` 299 | 300 | Блоки кода следует отделять от остального текста пустыми строками. 301 | Тогда изменения вносимые в блоки кода в диффах не будут смешиваться с изменениями текста документа: 302 | 303 | ~~~markdown 304 | Текст документа. 305 | 306 | ```markdown 307 | В Markdown можно делать **жирный текст** или *курсив*. 308 | Или ***всё вместе***. 309 | ``` 310 | 311 | Продолжение текста. 312 | ~~~ 313 | 314 | ## Ссылки 315 | 316 | Длинные ссылки усложняют чтение документа. 317 | Сокращайте ссылки когда это возможно убирая необязательные параметры в ссылках или используя короткую форму ссылок. 318 | 319 | ### Информативные названия ссылок 320 | 321 | Названия ссылок вроде "ссылка" или "тык" не информативны и ни о чем не говорят при беглом просмотре документа. 322 | В большинстве случаев такие названия только занимают место и их можно опустить. 323 | 324 | ```markdown 325 | Кодстайл можно посмотреть по [ссылке](style_guide.md). 326 | Кстати, там написано, что такие ссылки не информативны ([тык](style_guide.md#links)). 327 | ``` 328 | 329 | Лучше писать предложение как будто ссылки нет, а потом превратить в ссылку наиболее подходящую фразу: 330 | 331 | ```markdown 332 | Посмотрите [кодстайл](style_guide.md) перед тем как редактировать документацию. 333 | Кстати, там есть [секция "Ссылки"](style_guide.md#links), описывающая как правильно оформлять ссылки. 334 | ``` 335 | 336 | ### Алиасы ссылок 337 | 338 | Спецификация CommonMark позволяет объявлять [алиасы ссылок (link reference)][commonmark-link-ref]: 339 | 340 | ```markdown 341 | [Алиасы ссылок][link-alias] это очень удобно. 342 | 343 | [link-alias]: https://spec.commonmark.org/0.30/#link-reference-definition 344 | ``` 345 | 346 | Используя алиасы вместо ссылок мы получаем несколько преимуществ: 347 | 348 | - текст со ссылками выглядят аккуратнее и его проще читать 349 | - алиасы можно использовать несколько раз, при этом не нужно в каждом месте использования писать ссылку 350 | - все ссылки собраны в одном месте в конце документа и их проще проверять на актуальность и обновлять. 351 | 352 | Ссылки, которые принадлежат вам полезно отделять пустой строкой от тех которые вы не контролируете. 353 | Скорее всего изменения чаще будут вноситься в подконтрольные ссылки, поэтому располагаем их выше: 354 | 355 | ```markdown 356 | Текст документа. 357 | 358 | [01]: docs/01_getting_started.md 359 | [02]: docs/02_configuration.md 360 | 361 | [sqlite]: https://sqlite.org/ 362 | ``` 363 | 364 | Для консистентности все алиасы называем в `lower-kebab-case`. 365 | Алиасы не чувствительны к регистру и если алиас совпадает с названием ссылки, его можно опустить. 366 | В некоторых случая ссылки можно объявлять более компактно: 367 | 368 | ```markdown 369 | [CommonMark] - это наиболее распространённая спецификация Markdown. 370 | 371 | [commonmark]: https://commonmark.org 372 | ``` 373 | 374 | Алиасы не приносят пользу и их не стоит использовать если документ представляет собой набор ссылок: 375 | 376 | ```markdown 377 | ## Документация 378 | 379 | - [Соглашения](conventions.md) 380 | - [Архитектура](arch.md) 381 | 382 | ## Полезные ссылки 383 | 384 | - [Jira](https://jira.superproject.com/) 385 | ``` 386 | 387 | ## Изображения 388 | 389 | Markdown поддерживает вставку изображений в документ: 390 | 391 | ```markdown 392 | Смотрите какая милота:\ 393 | ![Кот в халате](https://cdn2.thecatapi.com/images/d60.jpg) 394 | ``` 395 | 396 | Хорошая практика - сохранять картинки в каталог рядом с документом и добавлять изображение используя относительную ссылку. 397 | В этом случае вы будете уверены, что картинка не пропадёт из документа: 398 | 399 | ```markdown 400 | Схема интеграции с сервисами заказчика:\ 401 | ![Схема интеграции](assets/integrations.png) 402 | ``` 403 | 404 | ### Ссылка изображения 405 | 406 | По умолчанию нажатие на картинку открывает файл с картинкой. 407 | Сделать картинку некликабельной не получится, но можно переопределить ссылку: 408 | 409 | ```markdown 410 | # Bat Bunker 411 | 412 | [![Logo](assets/logo.png)](#)\ 413 | (Попробуйте нажать на логотип, у вас ничего не получится) 414 | 415 | Наши спонсоры (логотипы кликабельны):\ 416 | [![Wayne Enterprises](assets/logo_wayne.png)](https://wayne.enterprises/) 417 | ``` 418 | 419 | [syntax]: https://daringfireball.net/projects/markdown/syntax 420 | [ghfm]: https://docs.github.com/en/github/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax 421 | [glfm]: https://docs.gitlab.com/ee/user/markdown.html 422 | [gitlab-toc]: https://docs.gitlab.com/ee/user/markdown.html#table-of-contents 423 | [github-toc]: https://github.com/isaacs/github/issues/215 424 | [vuepress-toc]: https://v2.vuepress.vuejs.org/guide/markdown.html#table-of-contents 425 | [vuepress-markdown]: https://v2.vuepress.vuejs.org/guide/markdown.html 426 | [google-style]: https://google.github.io/styleguide/docguide/style.html 427 | [commonmark]: https://spec.commonmark.org/current/ 428 | [commonmark-hard-wrap]: https://spec.commonmark.org/0.30/#hard-line-breaks 429 | [commonmark-link-ref]: https://spec.commonmark.org/0.30/#link-reference-definition 430 | [doctoc]: https://github.com/thlorenz/doctoc 431 | -------------------------------------------------------------------------------- /style_guide/resource-naming-guide.md: -------------------------------------------------------------------------------- 1 | # RFC 1: Правила именования ресурсов 2 | 3 | ## Соглашения 4 | 5 | constant part 6 | Предопределённые части названия, которые диктуются спецификой android разработки и никогда не меняются 7 | 8 | **required part** 9 | Часть названия, которая задается в зависимости от условий использования 10 | 11 | *optional part* 12 | Часть, которая добавляется при необходимости что-либо уточнить 13 | 14 | ## Рефакторинг 15 | 16 | Если после рефакторинга ресурс перестает принадлежать какому-то функционалу, он должен быть переименован в соответствии с этими правилами. 17 | Например иконка называлась `auth_key_icon`, но потребовалось использовать ее вне сценария авторизации. 18 | Такая иконка должна быть переименована в `key_icon`. 19 | Если архитектура приложения подразумевает разделение на модули, нужно перенести переименованную иконку в соответствующий модуль. 20 | 21 | ## Правила именования 22 | ### Animation ![Accepted](https://img.shields.io/badge/accepted-green?style=for-the-badge) 23 | 24 | > **[what i do]***_[duration/speed/etc]* 25 | 26 | Примеры: 27 | - `fade_out` 28 | - `slide_up` 29 | 30 | ### Color ![On Hold](https://img.shields.io/badge/on_hold-yellow?style=for-the-badge) 31 | 32 | > **[designer's color name]** 33 | > Цвет из Miro или дизайн системы 34 | > 35 | > **[color]***\_opacity_[opacity percent]* 36 | > Любой цвет 37 | > 38 | > **[color place]\_[color]***\_opacity\_[opacity percent]* 39 | > Цвет, который привязан к какому-то конкретному элементу интерфейса 40 | 41 | Примеры: 42 | - `sme_dark_grey` 43 | - `C14` 44 | - `brand_blue` 45 | - `white_opacity_70` 46 | - `divider_black_opacity_85` 47 | 48 | ### Color (Compose) 49 | 50 | В Compose цвета описываются в отдельном object. 51 | 52 | Пример: 53 | - `KnowledgeBaseColor` 54 | 55 | Цвета именуются по аналогии с формой наименования ресурсов в `color.xml`, но с использованием `CamelCase`. 56 | 57 | > **[Designer's color name]** 58 | > Цвет из Miro/Figma или дизайн системы 59 | > 60 | > **[Color]***\_[opacity percent]* 61 | > Любой цвет, который также может обладать определенной прозрачностью 62 | > 63 | > **[Color][Dark/Light postfix]***\_[opacity percent]* 64 | > Цвет, который встречается в более светлом/темном виде можно выделить ключевыми словами 65 | > 66 | > **[Color place]\[Color]***\_[opacity percent]* 67 | > Цвет, который привязан к какому-то конкретному элементу интерфейса 68 | 69 | Примеры: 70 | - `Grey` 71 | - `GreyLight` 72 | - `Red_90` 73 | - `ShimmerPrimary` 74 | 75 | ### Drawable ![Accepted](https://img.shields.io/badge/accepted-green?style=for-the-badge) 76 | 77 | > icon/shape/image/selector_**[what i show]***_[size_dp]* 78 | > Drawable-ресурс, который используется повсеместно в приложении 79 | > 80 | > **[feature]_** icon/shape/image/selector **_[what i show]***_[size_dp]* 81 | > Drawable-ресурс, который используется только в рамках какого-то функционала 82 | 83 | Примеры: 84 | - `icon_arrow` 85 | - `shape_search_result_background` 86 | - `auth_icon_key` 87 | 88 | ### Drawable (Compose) 89 | 90 | В Compose Drawable-ресурсы описываются в отдельном object. 91 | 92 | > **[App name][Illustration/Icon]** 93 | > Название object в котором описываются Drawable-ресурсы 94 | 95 | Примеры: 96 | - `KnowledgeBaseIcon` 97 | - `KnowledgeBaseIllustration` 98 | 99 | > **[What i show]***_[size_dp]* 100 | > Drawable-ресурс, который используется повсеместно в приложении 101 | > 102 | > **[Feature]**icon/shape/image/selector**[What i show]***[size_dp]* 103 | > Drawable-ресурс, который используется только в рамках какого-то функционала 104 | 105 | Примеры: 106 | - `Delete` 107 | - `Settings_32` 108 | - `KnowledgeBaseLogo` 109 | 110 | ### Layout ![Accepted](https://img.shields.io/badge/accepted-green?style=for-the-badge) 111 | 112 | > activity_**[what i do]** 113 | > fragment_**[what i do]** 114 | > dialog_**[what i do]** 115 | > layout_**[what i do]** 116 | > item_**[what i do]** 117 | > view_**[what i do]** 118 | 119 | Примеры: 120 | - `activity_main` 121 | - `fragment_input_pin_code` 122 | - `dialog_account_filter` 123 | - `layout_placeholder` 124 | - `item_user` 125 | - `view_shimmer` 126 | 127 | ### Layout (Compose) 128 | 129 | > [**What i do**]Screen 130 | > [**What i do**]BottomSheet 131 | > [**What i do**]Layout 132 | > [**What i do**]Item 133 | > [**What i do**]Shimmer 134 | 135 | Локальные и общие визуальные компоненты обычно именуются только по назначению, но в случае необходимости дополнить 136 | контекст или выделить их тип можно дополнить название припиской `View`. 137 | 138 | > [**What i do**]View 139 | 140 | Примеры: 141 | - `MainScreen` 142 | - `InfoBottomSheet` 143 | - `DetailsInfoLayout` 144 | - `UserItem` 145 | - `AmountShimmer` 146 | - `WebView` 147 | 148 | ### View ID ![Accepted](https://img.shields.io/badge/accepted-green?style=for-the-badge) 149 | 150 | > В параметр `[view type]` не нужно включать суффикс `_view` чтобы не захламлять название. 151 | > 152 | > **[what i contain]**_container 153 | > Любой контейнер 154 | > 155 | > **[view type]\_[what i do]** 156 | > View используемая повсеместно в приложении 157 | > 158 | > **[feature]\_[view type]\_[what i do]** 159 | > View используемая только в рамках какого-то функционала 160 | 161 | Примеры: 162 | - `view_pin_code` 163 | - `button_next` 164 | - `users_container` 165 | - `accounts_container` 166 | - `auth_button_login` 167 | - `orders_text_screen_header` 168 | - `user_profile_image_avatar` 169 | 170 | ### Menu ![Accepted](https://img.shields.io/badge/accepted-green?style=for-the-badge) 171 | 172 | > bottom_menu 173 | > Единственное на все приложение меню для "нижней" навигации 174 | > 175 | > **[why i need]**_menu 176 | > Меню, которое используется по всему приложению 177 | > 178 | > **[feature]\_[why i need]**_menu 179 | > Меню, которое используется только в каком-то конкретном функционале 180 | > 181 | > **[screen]\_[why i need]**_menu 182 | > Меню, которое используется только на конкретном экране 183 | 184 | Примеры: 185 | - `role_type_menu` 186 | - `orders_filter_menu` 187 | - `chat_toolbar_menu` 188 | - `profile_settings_user_role_menu` 189 | 190 | ### Menu item ID ![Accepted](https://img.shields.io/badge/accepted-green?style=for-the-badge) 191 | 192 | > В параметр `[menu file name]` не нужно включать суффикс `_menu` чтобы не захламлять название. 193 | > 194 | > **[menu file name]_[what i show]** 195 | 196 | Примеры: 197 | - `role_type_admin` 198 | - `orders_filter_by_name` 199 | - `chat_toolbar_call` 200 | 201 | ### Raw file ![Accepted](https://img.shields.io/badge/accepted-green?style=for-the-badge) 202 | 203 | > **[why i need]** 204 | 205 | ### Array ![Accepted](https://img.shields.io/badge/accepted-green?style=for-the-badge) 206 | 207 | > **[what i contain]\_[array type]**_array 208 | > Массив элементов, который используется по всему приложению 209 | > 210 | > **[feature]\_[what i contain]\_[array type]**_array 211 | > Массив элементов, который используется в каком-то конкретном функционале 212 | 213 | Примеры: 214 | - `months_string_array` 215 | - `role_ids_string_array` 216 | - `role_ids_int_array` 217 | - `orders_delivery_variant_string_array` 218 | 219 | ### Dimen ![Accepted](https://img.shields.io/badge/accepted-green?style=for-the-badge) 220 | 221 | > *[view type]\_***[dimen type]\_[dimen size]** 222 | > Размер который используется по всему приложению 223 | > 224 | > **[feature]***\_[view type]***\_[dimen type]\_[dimen size]** 225 | > Размер, который используется только в каком-то конкретном функционале 226 | > 227 | > **[screen]***\_[view type]***\_[dimen type]\_[dimen size]** 228 | > Размер, который используется только на каком-то конкретном экране 229 | 230 | > `[dimen type]` может содержать как общий тип вроде `margin` или `padding`, так и более уточнённый `margin_top`. 231 | > Можно использовать суффиксы `_vertical` и `_horizontal` для описания сразу двух отступов. 232 | 233 | Примеры: 234 | - `button_margin_8dp` 235 | - `auth_button_margin_12dp` 236 | - `order_info_picture_height_20dp` 237 | 238 | ### String ![Accepted](https://img.shields.io/badge/accepted-green?style=for-the-badge) 239 | 240 | > **[what i show]\_[string type]** 241 | > Строка, которая используется по всему приложению 242 | > 243 | > **[feature]\_[what i show/where i am]\_[string type]** 244 | > Строка, которая используется в каком-то конкретном функционале 245 | > 246 | > **[screen]\_[what i show/where i am]\_[string type]** 247 | > Строка, которая используется на каком-то конкретном экране 248 | 249 | `[string type]` может принимать следующие значения: 250 | - *title* - метки, заголовки кнопок и полей 251 | - *description* - любые поясняющие тексты 252 | - *hint* - подсказки для текстовых полей и потенциально для интерфейсных подсказок 253 | - *message* - сообщения пользователю 254 | - *error* - сообщения об ошибках 255 | - *mask* - маски ввода 256 | - *[custom]* - любые типы, которые требуют отдельного уточнения. 257 | Например url, secret и т.п. 258 | 259 | Примеры: 260 | - `app_name_title` 261 | - `orders_filter_button_title` 262 | - `login_password_hint` 263 | 264 | ### Styles and Themes ![On Hold](https://img.shields.io/badge/on_hold-yellow?style=for-the-badge) 265 | 266 | > Theme.**[app name].[theme name]** 267 | > Тема 268 | > 269 | > ThemeOverlay.**[app name].[theme overlay name]** 270 | > Тема, которая определяет только некоторые атрибуты и применяется поверх активной темы 271 | > 272 | > Widget.**[app name].[widget name]***.[style name]* 273 | > Стиль виджета 274 | > 275 | > TextAppearance.**[app name].[text appearance name]** 276 | > Стиль текста 277 | > 278 | > ShapeAppearance.**[app name].[shape appearance name]** 279 | > Стиль фигур 280 | 281 | Примеры: 282 | - `Theme.Openbank.TranslucentStatus` 283 | - `ThemeOverlay.Openbank.Dialog` 284 | - `Widget.Openbank.Button.Outlined` 285 | - `TextAppearance.Openbank.Body1` 286 | - `ShapeAppearance.Openbank.Small` 287 | 288 | ### XML file ![Accepted](https://img.shields.io/badge/accepted-green?style=for-the-badge) 289 | 290 | > **[why i need]** 291 | 292 | Примеры: 293 | - `network_security_config.xml` 294 | 295 | ### Font file ![On Hold](https://img.shields.io/badge/on_hold-yellow?style=for-the-badge) 296 | 297 | > **[designer's font name]** 298 | > Стандартное имя шрифта или имя придуманное дизайнерами 299 | 300 | ## FAQ 301 | 302 | **Q: Я художник! Мне не хочется думать когда я называю ресурсы, это так обязательно?** 303 | **A:** Это регулируется внутренними договоренностями в команде проекта. 304 | Если команда берет на себя ответственность за хаос и за повышение порога входа для новых сотрудников, то называть ресурсы можно как угодно. 305 | 306 | **Q: Почему в примерах написано именно так, а не иначе? 307 | Я вот думаю нужно писать по-другому!** 308 | **А:** Потому что это просто примеры, они созданы для удобства понимания правил. 309 | Если хочется, можно предложить свои. 310 | Обсудим и заменим. 311 | --------------------------------------------------------------------------------