avatarDennis

Summary

The article provides Kotlin best practices for Android developers, focusing on null safety, collection usage, and constructor patterns.

Abstract

The article "Kotlin Best Practices for Android Developers — Part 1" outlines essential coding practices for Android developers using Kotlin. It emphasizes the importance of null safety by distinguishing between nullable and non-nullable types, and demonstrates how to handle nullable types safely using Kotlin's language features. The article also discusses the performance and safety trade-offs between mutable and immutable collections, advising on their appropriate usage in different scenarios. Additionally, it recommends refactoring multiple 'if' statements into 'when' statements for better readability and maintainability. The author highlights Kotlin's "Named & Default Arguments" as a superior alternative to traditional constructor patterns, such as the telescoping constructor pattern and the builder pattern, promoting cleaner code with fewer constructors.

Opinions

  • The author believes that following Kotlin's best practices is crucial for writing high-quality, maintainable code.
  • Kotlin's null safety features are seen as a significant improvement over Java, with the IDE enforcing proper null handling.
  • Mutable collections are preferred for local variables where performance is a priority, while immutable collections are recommended when safety is paramount.
  • The 'when' statement is advocated for its ability to improve code readability and maintainability over multiple 'if' statements.
  • The author posits that Kotlin's "Named & Default Arguments" simplify object creation and eliminate the need for complex constructor patterns used in Java.
  • The article suggests that developers should favor primary constructors with named and default arguments over secondary constructors.

Kotlin Best Practices for Android Developers — Part 1

The recommended best practices for Kotlin-Android developers.

Photo by Louis Tsai on Unsplash

As you begin Android development using Kotlin, remember to follow Kotlin’s best practices.

These practices will help you utilize Kotlin’s powerful language features effectively. This, in turn, will enhance your code’s quality and maintainability.

If you are not a medium member you can read this story here

Null safety — Keep the code safe

Kotlin has nullable and non-nullable types of variables. IDE itself enforces you to use it properly and write the program in a null safety manner.

// Non nullale type
var name: String = "Tony"
name = null // compilation error

// Nullale type
var name: String? = "Tony"
name = null

On a nullable type > only Safe(?.) or Non-nullable operator(!!.) are allowed.

// COMPILATION ERROR
var name: String? = "Tony"
println(name.length) // since name is nullable, it will show compile time error

// RIGHT
var name: String? = "Tony"
println(name?.length) // Safe call

// WHAT IF name is NULL
var name: String? = null
println(name?.length) // prints null - entire expression becomes null

// Non-nullable operator(!!.)
var name: String? = null
println(name!!.length) // Throws nullpointer exception

Use the ?: Elvis operator to give a default value.

var name: String? = "Tony"
var length = name?.length ?: 0

When to use mutable vs immutable collections?

  • Mutable collections are faster in performance compared to immutable collections.
  • For local variables where synchronization and encapsulation are rarely needed — Use mutable collections.
  • Immutable collections are used when safety is required.
val mutableList = mutableListOf("apple", "banana", "orange")
val mutableSet = mutableSetOf("apple", "banana", "orange")
val mutableMap = mutableMapOf("apple" to 1, "banana" to 2, "orange" to 3)
val arrayList = ArrayList<Int>()

val immutableList = listOf("apple", "banana", "orange")
val immutableSet = setOf("apple", "banana", "orange")
val immutableMap = mapOf("apple" to 1, "banana" to 2, "orange" to 3)

More than one “If-statement”? refactor it into a “When”

a ‘when’ statement gives improved readability and maintainability.

when(expression) {
 value1 -> statement1
 value2 -> statement2
 ...
 default -> defaultStatement
}

Constructors best practices

Kotlin provides a cool feature “Named & Default Arguments” which is a better option compared to the below patterns.

  • Telescoping constructor pattern.

Series of constructors, each with a different number of parameters, where each constructor calls another constructor with more parameters.

  • Builder pattern.

In Java, a builder pattern is used when the object has a complex set of parameters and to get the flexibility to name parameters, specify parameters in any order, and have default values.

Both these requirements are simply served by the “Named & Default Arguments” in Kotlin.

class Person(
    val name: String = "Tony Stark",  // Default value for name parameter
    val age: Int = 45               // Default value for age parameter
)

fun main() {
    // Creating a Person object without specifying arguments
    val person1 = Person()
    println("Name: ${person1.name}, Age: ${person1.age}")

    // Creating a Person object with specified arguments
    val person2 = Person("David", 25)
    println("Name: ${person2.name}, Age: ${person2.age}")
}

Tip: Try to use a primary constructor and, if necessary, an init block since Named and default arguments give flexibility and can avoid unnecessary secondary constructors.

Stay tuned and subscribe for more Articles on Android and Kotlin.

Kotlin
Android
Programming
Best Practices
Coding
Recommended from ReadMedium