← Back to Kotlin Course | Chapter 5: Null Safety | Lesson 6 of 6

Null Safety की Best Practices

Null safety के लिए best practices वे समझदार आदतें हैं जो आपको खाली-box surprises से बिल्कुल बचने में मदद करती हैं, बजाय सिर्फ उन पर react करने के।
Syntax
kotlin
val name: Type = value            // prefer non-null
val parsed = input?.toIntOrNull() ?: default

fun functionName(): List<Type> {   // empty list instead of null
    return emptyList()
}

Prefer Non-Null by Default

Functions और classes को इस तरह design करें कि ज़्यादातर properties और parameters non-nullable हों, ? को सिर्फ उन cases के लिए रखते हुए जहां अनुपस्थिति असल में मायने रखती हो, जो आपके बाकी code को लगातार null checks से मुक्त रखता है।

उदाहरण: Prefer Non-Null by Default

markup
// Define a data class `Product`
data class Product(val name: String, val price: Double, val discountCode: String? = null)

// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `product`, set to `Product("Book", 15.0)`
    val product = Product("Book", 15.0)
    // Print "${product.name}: $${product.price}, discount=${product.discountCode ?: "none"}" to the console, with a trailing newline
    println("${product.name}: $${product.price}, discount=${product.discountCode ?: "none"}")
}

Validate at the Boundary

जब data आपके program के बाहर से आए, जैसे parsed text या एक network response, raw nullable values को अपने logic में गहराई से पास करने के बजाय इसे जितनी जल्दी हो सके एक proper non-null domain type में convert करें।

उदाहरण: Validate at the Boundary

markup
// Define the function `parseAge` taking `input` and returning an Int
fun parseAge(input: String?): Int {
    // Return `input?.toIntOrNull() ?: error("Invalid or missing age: $input")` from this function
    return input?.toIntOrNull() ?: error("Invalid or missing age: $input")
}

// Entry point: execution of the program starts here
fun main() {
    // Print "Age: ${parseAge("42")}" to the console, with a trailing newline
    println("Age: ${parseAge("42")}")
}

Avoid Nullable Collections

किसी nullable list के बजाय एक खाली list return करने का मतलब है कि callers बिना किसी अतिरिक्त null check के सुरक्षित रूप से iterate या size जांच सकते हैं, calling code को काफी सरल बनाते हुए।

Note: 'कोई results नहीं' represent करने के लिए एक खाली list null से कहीं आसान है काम करने में।

उदाहरण: Avoid Nullable Collections

markup
// Define the function `findMatches` taking `query`, `items` and returning a `List<String>`
fun findMatches(query: String, items: List<String>): List<String> {
    // Return `items.filter { it.contains(query) }` from this function
    return items.filter { it.contains(query) }
}

// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `results`, set to `findMatches("kt", listOf("main.kt", "readme.md"))`
    val results = findMatches("kt", listOf("main.kt", "readme.md"))
    // Print "Found ${results.size} matches: $results" to the console, with a trailing newline
    println("Found ${results.size} matches: $results")
}

Reserve !! for Truly Impossible Nulls

!! को एक संकेत के रूप में treat करें कि अगर यह कभी असल में throw करे तो कुछ architecturally गलत है; इसे सिर्फ उस दुर्लभ case में उपयोग करें जहां आस-पास का logic non-null की गारंटी देता हो, और बाकी हर जगह सुरक्षित operators को प्राथमिकता दें।

उदाहरण: Reserve !! for Truly Impossible Nulls

markup
// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `cache`, set to `HashMap<String, String>()`
    val cache = HashMap<String, String>()
    cache["greeting"] = "Hello"
    // Check whether `"greeting" in cache`
    if ("greeting" in cache) {
        // Print `cache["greeting"]!!` to the console, with a trailing newline
        println(cache["greeting"]!!)
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. ऐसे APIs design करना जो nullable types return करते हैं जब एक खाली collection या एक sensible default वही जानकारी ज़्यादा सुरक्षित रूप से बता देता।
  2. यह पता लगाने के बजाय कि कोई value अप्रत्याशित रूप से क्यों null हो सकती है, codebase में हर जगह एक तेज़ fix के रूप में !! छिड़कना।
  3. अपने program की boundary पर external data (network responses, user input) को validate न करना, nulls को business logic में गहराई तक leak होने देते हुए।
चैप्टर सारांश
  • default रूप से non-nullable types को प्राथमिकता दें; किसी चीज़ को nullable सिर्फ तभी चिह्नित करें जब अनुपस्थिति genuinely एक मायने रखने वाला case हो।
  • nullable external data (JSON, user input) को जितनी जल्दी हो सके non-null domain types में validate और convert करें।
  • लगभग हर स्थिति में !! के बजाय ?., ?:, और safe scope functions का उपयोग करें।
  • nullable collection के बजाय एक खाली collection को प्राथमिकता दें ताकि callers को सिर्फ iterate करने के लिए अतिरिक्त null checks न चाहिए हों।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.