Reputation: 489
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.?
Upvotes: 5
Views: 2415
Reputation: 17622
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
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.
Upvotes: 1
Reputation: 1
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.
Upvotes: 0
Reputation: 1116
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.
Upvotes: 1
Reputation: 8928
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
Upvotes: 3
Reputation: 121998
Imho The second one is better because it's avoiding calling getDetails(...)
method twice.
Upvotes: 4