← Back to Kotlin Course | Chapter 10: Extension Functions & Properties | Lesson 6 of 6

Extension Function की Best Practices

Extensions के लिए best practices वे अच्छी आदतें हैं जो आपकी bolted-on abilities को बाद में बिखरे और भ्रामक होने के बजाय साफ़ और ढूंढने में आसान रखती हैं।

Naming Extensions Clearly

एक अच्छे extension function के नाम को call site पर स्वाभाविक रूप से पढ़ा जाना चाहिए और स्पष्ट रूप से बताना चाहिए कि यह क्या करता है, ऐसे अस्पष्ट नामों से बचते हुए जो असंबंधित behavior के साथ confuse हो सकें।

उदाहरण: Naming Extensions Clearly

markup
fun String.isValidEmail(): Boolean = this.contains("@") && this.contains(".")

// Entry point: execution of the program starts here
fun main() {
    // Print `"[email protected]".isValidEmail()` to the console, with a trailing newline
    println("[email protected]".isValidEmail())
    // Print `"not-an-email".isValidEmail()` to the console, with a trailing newline
    println("not-an-email".isValidEmail())
}

Avoiding Surprising Side Effects

चूंकि caller को एक extension function बिल्कुल एक असली member function जैसा दिखता है, इसे predictably व्यवहार करना चाहिए -- ऐसे extensions से बचें जो चुपचाप shared state को अप्रत्याशित तरीकों से mutate करें।

उदाहरण: Avoiding Surprising Side Effects

markup
fun MutableList<Int>.addIfPositive(value: Int): Boolean {
    // Return `if (value > 0) {` from this function
    return if (value > 0) {
        add(value)
        true
    // Otherwise, run this branch
    } else {
        false
    }
}

// Entry point: execution of the program starts here
fun main() {
    // Declare a read-only variable `numbers`, set to `mutableListOf(1, 2)`
    val numbers = mutableListOf(1, 2)
    numbers.addIfPositive(5)
    numbers.addIfPositive(-3)
    // Print `numbers` to the console, with a trailing newline
    println(numbers)
}

Scoping Extensions to Specific Types

किसी extension को सबसे संकरे type के खिलाफ लिखना जो समझ में आए (बजाय Any जैसे बहुत व्यापक type के) इसे relevant रखता है और असंबंधित types के लिए autocomplete suggestions को गंदा करने से बचाता है।

उदाहरण: Scoping Extensions to Specific Types

markup
fun Collection<Int>.sumOfSquares(): Int = this.sumBy { it * it }

// Entry point: execution of the program starts here
fun main() {
    // Print `listOf(1, 2, 3).sumOfSquares()` to the console, with a trailing newline
    println(listOf(1, 2, 3).sumOfSquares())
}

Grouping Related Extensions Together

एक ही type या feature area से संबंधित extension functions को एक स्पष्ट रूप से नामित file में organize करना उन्हें दूसरे developers (और भविष्य के आपके लिए) ढूंढना आसान बनाता है।

उदाहरण: Grouping Related Extensions Together

markup
fun String.truncate(maxLength: Int): String =
    if (this.length <= maxLength) this else this.take(maxLength) + "..."

fun String.titleCase(): String =
    this.split(" ").joinToString(" ") { it.capitalize() }

// Entry point: execution of the program starts here
fun main() {
    // Print `"kotlin programming language".titleCase()` to the console, with a trailing newline
    println("kotlin programming language".titleCase())
    // Print `"This is a long sentence".truncate(10)` to the console, with a trailing newline
    println("This is a long sentence".truncate(10))
}
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. बहुत व्यापक types (जैसे Any) पर अत्यधिक generic नामों वाले extension functions जोड़ना, name clashes और भ्रामक autocomplete suggestions का जोखिम उठाते हुए।
  2. callers को हैरान करने वाले side effects वाले extensions रखना, क्योंकि call site पर एक extension बिल्कुल एक normal member function जैसा दिखता है।
  3. discoverability के लिए संबंधित वालों को साथ group करने के बजाय extension functions को कई असंबंधित files में बिखेर देना।
चैप्टर सारांश
  • Extension functions को केंद्रित, अच्छी तरह नामित, और जितना मायने रखे उतनी specific type तक सीमित रखें।
  • भ्रामक side effects वाले extensions से बचें, क्योंकि call sites एक नज़र में किसी extension को असली member से अलग नहीं बता सकते।
  • संबंधित extension functions को discover और maintain करना आसान बनाने के लिए एक स्पष्ट रूप से नामित file में साथ group करें।
  • किसी एक use case के लिए specific one-off logic के बजाय genuinely reusable, general-purpose helpers के लिए extensions को प्राथमिकता दें।
🔒

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.