• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

get method question

 
Isaac Hewitt
Ranch Hand
Posts: 191
Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
When getting a value is it better or the same if I declare it or repeat a get method. For example:



or:



I have to repeat the setColor method several times.



 
Chris Hurst
Ranch Hand
Posts: 443
3
C++ Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The second one, two stage as your going to reuse the returned value multiple times in your example code .. its more efficient, error messages will be easier to read for a beginner and it'll be easier to see what's going on in a debugger. The alternative wasn't the end of the world though.
 
Isaac Hewitt
Ranch Hand
Posts: 191
Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Chris
 
Norm Radder
Ranch Hand
Posts: 1014
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To see what code is generated for your examples, write two small programs and use the javap command to display the byte code for each and compare them.
I suspect the output will be almost the same.

Be sure to come back and tell us the results.
 
Rob Spoor
Sheriff
Pie
Posts: 20546
56
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From a performance point of view, it is wise to cache results of methods if you need them more than once. Even if a method just returns a value now, it can be changed to include complex calculations or even file I/O or database interactions at some time. By caching the results, you will ensure that the method is called only once and there will be no more duplicate execution of the same (possibly complex or time consuming) code.
 
Bill Cruise
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I disagree with the previous posts. If you're making multiple calls to setColor, I think that the first code snippet makes it a lot more clear where the color is coming from, and doesn't require that you introduce a temporary variable. As for optimization, Color objects are immutable, so the composer.getReminderColor() method probably just returns a reference anyway. Introducing the temporary variable probably isn't saving you any time at all.

When in doubt I always remember the following:

1. Code for clarity.
2. Run with a profiler.
3. Optimize the bottlenecks if necessary.
 
Isaac Hewitt
Ranch Hand
Posts: 191
Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Bill, Rob & Norm
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic