I agree with Joost Klitsie, the author is holding it wrong ;-). Scope functions are very useful if used properly. Showing bad examples of scope usage and then deducing that scopes make your code less readable is a logical fallacy.

The deleteImage is such a bad example. As Joost already demonstrated, there are better ways to write that code without falling back to the terrible Java like null check. My favorite is:

val imageFile = getImage() ?: return

But this would do nicely too (no scope):

if (imageFile?.exists() == true) imageFile?.delete()

Even using run is better than the Java style null check:

imageFile?.run { if (exists()) delete() }

I agree with decomposing functional chains using actual functions / fun is a great way to get more readable code (and also more testable code). I would like to point out that the problem with chaining is sometimes just the formatting of the code! If you write the startActivity example like this, it’s already much easier to read:

Intent(context, MyActivity::class.java)
.apply {
// scope to configure object
putExtra(“data”, 123)
addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT)
}
.also {
startActivity(this@FooActivity,intent)
}

Just look at the difference formatting makes for this simple RxJava subscribe function:

.subscribe( { result ->
println(“do stuff with result”)
}, { error ->
println(“handle error”)
} )

vs:

.subscribe(
{ result -> println(“do stuff with result”) },
{ error -> println(“handle error”) }
)

Or the run example:

preferenceManager.getInstance()
?.run {
// do some more stuff here
getName()
}
?: run {
// do some more stuff here
getString(R.string.stranger)
}

Doesn’t look that terrible any more (extension functions is definitely the way to go here though).

To wrap up my comment, imo a simple but good example of using scopes:

val args = Bundle().apply {
putString(“Key”, “Value”)
putInt(“AnotherKey”, 1)
}

The author’s conclusion that “extensions look sensible and pragmatic but as whole they are not readable or maintainable” is imo wrong. Scopes are not readable/maintainable if used incorrectly, used correctly, they can give you very concise and readable code.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store