cleancode.in

Clean code in Kotlin

Kotlin’s coding conventions: classes in upper camel case, functions and variables in camel case that starts lowercase, constants in screaming snake case, 4 spaces a level, and val rather than var whenever a value never changes.

What does Kotlin’s coding conventions ask for?

  • Names of packages are always lowercase and do not use underscores (org.example.project). source

From Kotlin coding conventions.

How should Kotlin code look?

What else does it ask?

  • A method name is a verb saying what it does. source
  • No meaningless words like Manager or Wrapper. source
  • val rather than var. source

How are names written in Kotlin?

KindExampleRule
TypesShoppingCartClasses in upper camel case. source
FunctionsaddItemFunctions, properties and locals in camel case, lowercase first. source
VariablesitemCountFunctions, properties and locals in camel case, lowercase first. source
ConstantsMAX_ITEMSConstants in screaming snake case. source

What does cleaner Kotlin look like?

Before
class DiscountManager {
    fun Calc_discount(total: Double): Double {
        var d = 0.0
        if (total > 1000) d = total * 0.05
        return d
    }
}
After
const val DISCOUNT_THRESHOLD = 1000.0
const val DISCOUNT_RATE = 0.05

class DiscountRule {
    fun calculateDiscount(total: Double): Double =
        if (total > DISCOUNT_THRESHOLD) total * DISCOUNT_RATE else 0.0
}

What changed?

  • DiscountRule says what the class is; Manager said nothing. source
  • The function is a verb phrase in camel case. source
  • No var: the if is an expression and is the function’s value. source
  • The two numbers are named constants in screaming snake case. source