API Calls
Avoid unnecessarily repeating calls of APIs you do not control. Even though the implementation might appear fast, it can:
- Change in the future.
- Access persistence for some reason
- Call other APIs that are not fast in your context
- Synchronize execution deeper in the call stack
You can reduce API calls, using local variables. You address the API once to get the information you need and then store the information in a local variable for later reuse.
Using Local Variables
Basic Code
The following code example calls the CustomObject interface and its getName method three times.
private void printName(CustomObject cs){
if (cs.getName() != null && cs.getName().length() > 0){
System.out.println(cs.getName());
}
}
Optimized Code
The following code example only calls the CustomObject interface and its getName method once because it stores the returned name in a local string variable and reuses it.
private void printName(CustomObject cs){
String name = cs.getName() ;
if(name != null && name.length() > 0){
System.out.println(name);
}
}