Null Safety की Best Practices
In this page:
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
// 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"}")
}
Login to try C/C++/Java/PHP code in the editor
Validate at the Boundary
जब data आपके program के बाहर से आए, जैसे parsed text या एक network response, raw nullable values को अपने logic में गहराई से पास करने के बजाय इसे जितनी जल्दी हो सके एक proper non-null domain type में convert करें।
उदाहरण: Validate at the Boundary
// 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")}")
}
Login to try C/C++/Java/PHP code in the editor
Avoid Nullable Collections
किसी nullable list के बजाय एक खाली list return करने का मतलब है कि callers बिना किसी अतिरिक्त null check के सुरक्षित रूप से iterate या size जांच सकते हैं, calling code को काफी सरल बनाते हुए।
null से कहीं आसान है काम करने में।उदाहरण: Avoid Nullable Collections
// 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")
}
Login to try C/C++/Java/PHP code in the editor
Reserve !! for Truly Impossible Nulls
!! को एक संकेत के रूप में treat करें कि अगर यह कभी असल में throw करे तो कुछ architecturally गलत है; इसे सिर्फ उस दुर्लभ case में उपयोग करें जहां आस-पास का logic non-null की गारंटी देता हो, और बाकी हर जगह सुरक्षित operators को प्राथमिकता दें।
उदाहरण: Reserve !! for Truly Impossible Nulls
// 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"]!!)
}
}
Login to try C/C++/Java/PHP code in the editor
- ऐसे APIs design करना जो nullable types return करते हैं जब एक खाली collection या एक sensible default वही जानकारी ज़्यादा सुरक्षित रूप से बता देता।
- यह पता लगाने के बजाय कि कोई value अप्रत्याशित रूप से क्यों null हो सकती है, codebase में हर जगह एक तेज़ fix के रूप में
!!छिड़कना। - अपने 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: