← Back to Kotlin Course | Chapter 14: JVM Interop & Best Practices | Lesson 7 of 7

Kotlin की Best Practices

Kotlin best practices अनुभवी developers का जमा किया wisdom है कि Kotlin code को कैसे लिखें जो समय के साथ साफ़, सुरक्षित, और maintain करने में आसान रहे।

Design for Safety First

domain की अनुमति हो वहां non-null types, val, और sealed classes को प्राथमिकता देना bugs की कई पूरी categories को runtime crashes के बजाय compile-time errors में बदल देता है।

उदाहरण: Design for Safety First

markup
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")))
}

Keep Functions Small and Focused

logic को छोटे, अच्छी तरह नामित functions (local और extension functions सहित) में बांटना हर टुकड़े को समझना, test करना, और खुद reuse करना आसान बनाता है।

उदाहरण: Keep Functions Small and Focused

markup
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)
}

Don't Ignore Compiler Warnings

unreachable code, अनावश्यक safe calls, या unchecked casts के बारे में warnings अक्सर सीधे एक असली bug या एक design की ओर इशारा करती हैं जिसे ज़्यादा सुरक्षित बनाया जा सकता है -- उन्हें गंभीरता से लेना फायदा देता है।

उदाहरण: Don't Ignore Compiler Warnings

markup
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))
}

Write Code for the Next Reader

साफ़ नाम चुनना, चालाक tricks की तुलना में जाने-माने idioms को प्राथमिकता देना, और functions को छोटा रखना सब एक ही लक्ष्य की सेवा करते हैं: code को किसी और (या भविष्य के आप) के लिए सुरक्षित रूप से समझना और बदलना आसान बनाना।

उदाहरण: Write Code for the Next Reader

markup
// 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)}")
}
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. किसी value के type या nullability को अनिश्चित बनाने वाले underlying design को address करने के बजाय !! या unsafe casts का एक तेज़ fix के रूप में सहारा लेना।
  2. छोटे, अच्छी तरह नामित, single-purpose टुकड़ों को compose करने के बजाय बड़ी, सब-कुछ-करने वाली classes और functions लिखना।
  3. 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 when expressions उपयोग करें।
  • compiler warnings पर ध्यान दें -- वे अक्सर code में असली, ठीक करने योग्य risks को उजागर करते हैं।
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 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.