Kotlin की Best Practices
In this page:
Design for Safety First
domain की अनुमति हो वहां non-null types, val, और sealed classes को प्राथमिकता देना bugs की कई पूरी categories को runtime crashes के बजाय compile-time errors में बदल देता है।
उदाहरण: Design for Safety First
sealed class PaymentResult
// Define a data class `Approved`
data class Approved(val transactionId: String) : PaymentResult()
// Define a data class `Declined`
data class Declined(val reason: String) : PaymentResult()
// Define the function `describe` taking `result` and returning a String
fun describe(result: PaymentResult): String = when (result) {
is Approved -> "Approved: ${result.transactionId}"
is Declined -> "Declined: ${result.reason}"
}
// Entry point: execution of the program starts here
fun main() {
// Print `describe(Approved("tx_123"))` to the console, with a trailing newline
println(describe(Approved("tx_123")))
}
Login to try C/C++/Java/PHP code in the editor
Keep Functions Small and Focused
logic को छोटे, अच्छी तरह नामित functions (local और extension functions सहित) में बांटना हर टुकड़े को समझना, test करना, और खुद reuse करना आसान बनाता है।
उदाहरण: Keep Functions Small and Focused
fun Int.isPrime(): Boolean {
if (this < 2) return false
// Loop over `2 until this`, binding each item to `i`
for (i in 2 until this) {
if (this % i == 0) return false
}
// Return `true` from this function
return true
}
// Entry point: execution of the program starts here
fun main() {
// Declare a read-only variable `primes`, set to `(2..20).filter { it.isPrime() }`
val primes = (2..20).filter { it.isPrime() }
// Print `primes` to the console, with a trailing newline
println(primes)
}
Login to try C/C++/Java/PHP code in the editor
Don't Ignore Compiler Warnings
unreachable code, अनावश्यक safe calls, या unchecked casts के बारे में warnings अक्सर सीधे एक असली bug या एक design की ओर इशारा करती हैं जिसे ज़्यादा सुरक्षित बनाया जा सकता है -- उन्हें गंभीरता से लेना फायदा देता है।
उदाहरण: Don't Ignore Compiler Warnings
fun describeNumber(n: Int): String {
return if (n % 2 == 0) "even" else "odd"
// Any code placed here would be unreachable, and the compiler would warn about it
}
fun main() {
println(describeNumber(7))
}
Login to try C/C++/Java/PHP code in the editor
Write Code for the Next Reader
साफ़ नाम चुनना, चालाक tricks की तुलना में जाने-माने idioms को प्राथमिकता देना, और functions को छोटा रखना सब एक ही लक्ष्य की सेवा करते हैं: code को किसी और (या भविष्य के आप) के लिए सुरक्षित रूप से समझना और बदलना आसान बनाना।
उदाहरण: Write Code for the Next Reader
// Define the function `calculateShippingCost` taking `weightKg`, `isExpress` and returning a Double
fun calculateShippingCost(weightKg: Double, isExpress: Boolean): Double {
// Declare a read-only variable `baseCost`, set to `weightKg * 2.0`
val baseCost = weightKg * 2.0
// Return `if (isExpress) baseCost * 1.5 else baseCost` from this function
return if (isExpress) baseCost * 1.5 else baseCost
}
// Entry point: execution of the program starts here
fun main() {
// Print "Shipping cost: ${calculateShippingCost(5.0, true)}" to the console, with a trailing newline
println("Shipping cost: ${calculateShippingCost(5.0, true)}")
}
Login to try C/C++/Java/PHP code in the editor
- किसी value के type या nullability को अनिश्चित बनाने वाले underlying design को address करने के बजाय
!!या unsafe casts का एक तेज़ fix के रूप में सहारा लेना। - छोटे, अच्छी तरह नामित, single-purpose टुकड़ों को compose करने के बजाय बड़ी, सब-कुछ-करने वाली classes और functions लिखना।
- compiler warnings को नज़रअंदाज़ करना, जो अक्सर unreachable code, unused variables, या unsafe casts जैसे असली risks की ओर इशारा करते हैं।
- defensive, manual workarounds के बजाय immutability (
val, read-only collections) और null safety operators को प्राथमिकता दें। - Functions को छोटा और केंद्रित रखें, descriptive नामों के साथ जो *code क्या करता है* इस बारे में comments को ज़्यादातर अनावश्यक बना दें।
- जहां practical हो वहां invalid states को unrepresentable बनाने के लिए sealed classes और exhaustive
whenexpressions उपयोग करें। - compiler warnings पर ध्यान दें -- वे अक्सर code में असली, ठीक करने योग्य risks को उजागर करते हैं।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: