This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

question about declaring extraneous variables  RSS feed

 
Tom Bigbee
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Often times I come across code as such...

boolean isValid = someObject.isValid();
if (isValid) { // isValid only being used in one place
....
}

other than the fact that the variable is declared outside of the block in which it is being used, is there a performance hit (no matter how small) to doing this or does the compiler figure it out and optimize the call

This question does not apply to those cases where readability is to be take into account such as...

double commissionAmount = someObject.someReallyScrewyMethodName();
if(commissionAmount > 15.43) { // used once - var for readability only
...
}

Thanks, in advance
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I often make the extra variable as I think things out and then decide later whether or not to eliminate it. I usually make them go away unless the next line gets too long to read.

Every variable is a floating hazard to navigation in the rest of the scope. Somebody might decide to use it for something else. It's also one more unit of information the reader must comprehend and then go find all references to for understanding. These are tiny negatives, but some people are quite sensitive about them. If you decide to keep it, making it final would express your intent that it's only set once.

And if you're able, change the ridiculouslyLongMethodName to something meaningful but easy to digest. The name you were about to give the variable might be a good candidate.
[ November 16, 2007: Message edited by: Stan James ]
 
fred rosenberger
lowercase baba
Bartender
Posts: 12542
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
on the other hand, nothing makes me scream louder than seeing something like:


foo.method1().method2().method3().method4().method5();

or

foo.method1(bar.method2(oof.method3(rab.method4)));

in these cases, i'd break each method out and store what it returns in a temp. variable, every time.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm with you, Fred. I have a limit of about 2 on things like that. But some of the DSL language folks seem to love the chained methods.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!