aspose file tools*
The moose likes Beginning Java and the fly likes get method question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "get method question" Watch "get method question" New topic
Author

get method question

Isaac Hewitt
Ranch Hand

Joined: Jul 24, 2006
Posts: 190

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

Joined: Oct 26, 2003
Posts: 418
    
    2

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.


"Eagles may soar but weasels don't get sucked into jet engines" SCJP 1.6, SCWCD 1.4, SCJD 1.5,SCBCD 5
Isaac Hewitt
Ranch Hand

Joined: Jul 24, 2006
Posts: 190

Thanks Chris
Norm Radder
Ranch Hand

Joined: Aug 10, 2005
Posts: 690
    
    1
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

Joined: Oct 27, 2005
Posts: 19759
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Bill Cruise
Ranch Hand

Joined: Jun 01, 2007
Posts: 148
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

Joined: Jul 24, 2006
Posts: 190

Thanks Bill, Rob & Norm
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: get method question