Are extension methods and extension properties bad practice?

So, if extension methods and extension properties are really static methods and properties. Static methods and properties and methods are not thread safe, therefore they should be avoided, therefore extension methods and extension properties are bad.

We are simply deceiving them because the codes we write will seem beautiful or clean, but from a performance point of view, this is not so.

It's true?

+4
source share
3 answers

, / extension. , : .

1:

fun String.countSpaces(): Int {
    return this.count { c -> c == ' ' }
}

, String .

2:

data class MutablePerson(val name: String, var speech: String)

fun MutablePerson.count(nextNumber: Int) {
    this.speech = "${this.speech} ${nextNumber}"
}

speech MutablePerson . count - .

:

fun main(args: Array<String>) {
    val person = MutablePerson("Ruslan", "I'm starting count from 0 to 10:")

    (1..10).forEach { it ->
        Thread({
            person.count(it)
            println(person.speech)
        }).start()
    }

    Thread.sleep(1000)

    println(person.speech)
}

:

I'm starting count from 0 to 10: 1
I'm starting count from 0 to 10: 1 3
I'm starting count from 0 to 10: 1 3 4
I'm starting count from 0 to 10: 1 3 4 2
I'm starting count from 0 to 10: 1 3 4 2 5
I'm starting count from 0 to 10: 1 3 4 2 5 8
I'm starting count from 0 to 10: 1 3 4 2 5 6
I'm starting count from 0 to 10: 1 3 4 2 5 6 7
I'm starting count from 0 to 10: 1 3 4 2 5 6 7 9
I'm starting count from 0 to 10: 1 3 4 2 5 6 7 9 10
I'm starting count from 0 to 10: 1 3 4 2 5 6 7 9 10

, , : , , .

+7

. , vars , , , . , , , .

Util Java , Java . .

# , , .

+7

, . , , .

Java Utils - , , .

, ( Mockito, ), .

, , (, , ...)

0

Source: https://habr.com/ru/post/1660730/


All Articles