5

I have the following scenario.. and I come across the similar scenario many a times. Which is more preferable of the following two options?

Option-1:

String result = ( getDetails(...) == null ) ? "" : getDetails(...);

Option-2:

String returnValue = getDetails(...);
String result = ( returnValue == null ) ? "" : returnValue;

Which is more preferable and/or a good practice.?

subbu
  • 524
  • 6
  • 16

5 Answers5

4

Imho The second one is better because it's avoiding calling getDetails(...) method twice.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
3

If you have to do that check for every call of getDetails then the best way would be getDetails method to return "" in cases when you return null.

Also calling the same method twice (which is probably idempotent in your case) is not a good practice even if it is very simple.

Please read this java-how-expensive-is-a-method-call. Main idea is don't do premature optimization, but you should get used to these simple cases when you can write better code

Community
  • 1
  • 1
Tala
  • 8,888
  • 5
  • 34
  • 38
1

I'd prefer the second option because it is more readable, especially when using the ternary operator.

If it is a problem or not to call getDetails(...) twice depends on your method. If it is a simple getter, the JVM might optimize the call and directly use the value so storing it in a local variable does not make a difference.
If it is a more complex method, e.g. a query to the database, I would definitely store the result in a local variable.

Generally speaking: Care about code readability first! If you find performance problems later on, try optimizing then.

joe776
  • 1,106
  • 14
  • 23
1

Option-2: is better

Option-1: Results in extra method call and such cases should always be avoided unless getDetails(...) is a getter method (a one liner method which returns something)

If you dig down to micro optimization, a method call generally results in

  • allocation of stack for the method variables
  • jumping the instruction set

which are couple of many overheads. As many say, such performance optimization should be left to Compiler and the code should be written to be more readable.

Community
  • 1
  • 1
sanbhat
  • 17,522
  • 6
  • 48
  • 64
  • Hi Sanbhat. Can I have a question relates to this post? I am not talking about Performance (CPU time consuming). I am talking about Memory consuming. As I know, for each getter call, JVM need to create a new Stack so my question is Do you think Option 1 will consume more memory than Option 2 ( I assume that getDetails called a lot )? Thanks. – LHA Mar 21 '14 at 16:21
0

option-2 will be always optimized one what ever you wrote in the calling function. Even if you are writing any in-build function or expression two times it will take fraction of section more than option-2.