local variable or repeated calls? [duplicate] - java

This question already has answers here:
Java optimization : local variable or function call
(5 answers)
Closed 6 years ago.
I have a very basic question. Which if the below 2 is better performance-wise:
if (getSomeValue() != null) {
processSomeValue(getSomeValue());
}
OR
String someValue = getSomeValue();
if (someValue != null) {
processSomeValue(someValue);
}
getSomeValue() is a normal getter which does not do anything else.

A best practice is to always use the 2nd way even you already know that the getSomeValue() is a simple getter. The key thing is that the call might be maintained in the future and changed by someone in the future. Any developer if change the inner code of getSomeValue() may not be aware of the invocation method that you are currently using.

Related

Avoid if for chained objects [duplicate]

This question already has answers here:
Avoiding NullPointerException in Java
(66 answers)
Closed 2 years ago.
I have one complex object just like this;
Object A
Object B
Object C
Object D
property A
property B
So If I need to show the property A in my view, I need to
A.getB().getC().getD().getPropertyA();
but what if my user doesn`t send the object C?
so I need to create one If for every object
if(A.getB() != null){
if(A.getB().getC() != null){
if(A.getB().getC().getD() != null){
//here I can show the propertyA
}
}
}
now I have to show this property in 3 views
There is a better way to does this? a framework or something like this to solve this problem?
You can use Optional.ofNullable and map:
Optional.ofNullable(A.GetB())
.map(B::getC)
.map(C::getD)
.map(D::getPropertyA)
.orElseThrow()
P.S.1: Some developers (and linters) find this approach a code smell, but I think it's more readable that way.
P.S.2: You can use a default value with .orElse instead of .orElseThrow.

What ways are there of executing code only if no break occurres in a for loop in Java? [duplicate]

This question already has answers here:
while-else-loop
(7 answers)
Efficient implementation for: "Python For Else Loop" in Java
(5 answers)
Closed 6 years ago.
So in python one can put an else statement after a for-loop to only execute code if no break occurred. Is there something similar in Java? Or do you have to use an extra boolean like this:
b = true;
for () {
if (conditional) {
b = false;
break;
}
if (b) {
doSomething();
}
No, Java has nothing similar, so if you really need to imitate that behaviour you need to use an extra variable.
However it's worth considering that since different programming languages have different idioms, converting directly from one to another may not result in code that fits the style of the destination language. Therefore depending on the actual problem being solved, it may be suitable to use a for-else in python, but a different idiom in Java.
A variable is definitely the most readable way to achieve that but here's an alternative I came up with:
loop:
{
for (...) {
if (...) break loop;
}
// no 'break loop' occurred
}

Is there a benefit of assigning an object member variable locally in a method? [duplicate]

This question already has answers here:
Why does BufferedInputStream copy a field to a local variable rather than use the field directly
(3 answers)
Closed 6 years ago.
In Netty I have seen object member variables assigned locally in class methods quite frequently. Is this a matter of style or is there a programmatic benefit?
I have included a code snippet below:
public ChannelFuture bind() {
validate();
SocketAddress localAddress = this.localAddress;
if (localAddress == null) {
throw new IllegalStateException("localAddress not set");
}
return doBind(localAddress);
}
I usually see that pattern when multi-threading is a concern. For example, if another thread may alter the member value or null it after the null check, yet it is still a valid use case for member access to occur at that point. Or the code is trying to avoid locks/synchronization. So instead the member is copied to a local and all further operations are done using the local copy to prevent a null access.

Is it more efficient to use getters or assign them to a variable? [duplicate]

This question already has answers here:
Java Method invocation vs using a variable
(14 answers)
Closed 9 years ago.
In the below scenario, all 3 getXxxxx() methods simple return a property of that class with no additional processing.
Is it more efficient for me to assign them to a temporary variable like I've done with workLimit, or should I just use the getter like I did with getCurrentWork()?
int x = 0;
int workLimit = entity.getCurrentWorkLimit();
JobSet jobSet;
JobSetQueue queue = workflowProcess.getQueue();
while (x < workLimit && (jobSet = queue.poll()) != null) {
getCurrentWork().addLast(jobSet);
}
The VM optimizes access to simple getters itself - but in fact you usually shouldn't care about it. Therefore, I would usually optimize code for readibility / maintainability instead of performance. Performance optimizations should be based on facts, not assumptions.
Assuming getCurrentWork() is just returning a variable itself, then the performance will be the same. I think that having the extra variable sometimes makes the code easier to read/scan especially when you have lots of them. In thise case, I'd probably just use the getter.
You are in essence buying one less stack operation, this is a micro-optimization and as such is almost completely useless, unless you are writing a real-time system.
At the end of the day, profile profile profile

When sent to a constructor in Java, what does "null" value do? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Which constructor is chosen when passing null?
I recently came across this curiosity while coding a few days back and can't seem to figure out why the following happens:
Given the class below
public class RandomObject{
public RandomObject(Object o){
System.out.println(1);
}
public RandomObject(String[] s){
System.out.println(2);
}
}
When the call new RandomObject(null); is made the output is always 2 regardless of the order in which the constructors were created. Why does null refer to the string array rather than the object?
The key here is that Object is the super type of String[]
Java uses the most specific available method to resolve such cases. Null can be passed to both methods without compilation errors so Java has to find the most specific method here. The version with String[] is more specific - therefore it will be chosen for execution.
Someone else has had this question earlier, check this post
If there are two cases to choose from, the compiler will first try to pick the more specific case. In this case, String will be picked over Object.
In the other question it was String str instead of String[] s
Thus, since String[] is a more specific datatype than its super type Object, it is picked.

Categories

Resources