Skip to content

Kotlin convention

BryanLee edited this page Jun 5, 2020 · 11 revisions

Basically, all rules are based on the following.

For applying those rules programatically, I used ktlint.

Customed rules are below and I attached a link relate to the section.

Common rule for everywhere

  • Need a new line between all elements
  • Put related stuff together by visibility
  • Declaration order is public > internal > protected > private in all area
  • For readability set API method for public and implement it with the protected or private keyword

Structure

Property

  • val
  • val by lazy
  • var
  • lateinit var

Initializer block

Secondary constructor

  • Prefer to use primary constructor first with arguments
  • private fun

Method declarations

  • fun
  • override fun
  • private fun

Interface declarations

Nested class

companion object

  • Don't use an Uppercase letter more than 2 for class and method like not OEBPS but Oepbs.
  • Don't use the abbreviation for the name of class and method if possible.
  • The common term first then the concrete term.

About android

  • The key name follows snake_case
  • Convert snake_case resource id to camelCase variable through data binding.
  • The extra key has to start with the package name and be named snake_case if it's access public.

About test

Naming rules

  • Method name has to be started with given_when_then.
  • Use the abbreviation for the name of the variable if possible.

AAA

  • Distinct Arrange-Action-Assertion area clearly in method.
    • Define input in Arrange
    • Define actual and expect in Action
    • Define assertion with actual and expect

Use BeforeAll/AfterAll

  • All test method has to be an independent task.

In Project

  • xxxPath() method has to return with postfix of /.