Skip to content
This repository has been archived by the owner on Dec 21, 2023. It is now read-only.

Accessing properties which are open, var, or do not have backing fields #40

Open
damianw opened this issue May 31, 2017 · 4 comments
Open

Comments

@damianw
Copy link

damianw commented May 31, 2017

When accessing a property multiple times which cannot be smart cast, i.e. is any of the following:

  • open
  • a var
  • does not have a backing field

Prefer to first assign the property to a local variable.

val foo: String
    get() { /* ... */ }

fun good() {
  val foo = foo
  action1(foo)
  action2(foo)
}

fun bad() {
  action1(foo)
  action2(foo)
}
@cbruegg
Copy link

cbruegg commented May 31, 2017 via email

@damianw
Copy link
Author

damianw commented Jun 1, 2017

@cbruegg That's for sure; I had a similar feeling. I've phrased it as "prefer to first..." for that reason. While not strictly necessary in every situation, I think that repeated access of such a property is indicative of code smell. Kotlin properties provide a false sense of simplicity because of how easy they are to access. The equivalent Java code would be calling getFoo several times over, which should be discouraged, given that so many APIs return defensive copies, compute values on-demand, etc.

@Supuhstar
Copy link

I like this; it encourages the very good practice of caching computed values, which generally speeds up an app

@benjishults
Copy link

Why not use foo.let { action1(it); action2(it) }?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants