Good and Bad Code in Java
Good and Bad Code in Java
▪ Meaningful Names
▪ Comments
▪ Formatting
▪ Deal with equals method of Object
▪ Use Elementary Data Types to Avoid Automatic Packing and Unpacking
▪ Replace Strings with Characters
▪ Use StringBuilder for String Concatenation
▪ Use an isEmpty Instead of a Size Method to Detect Empty Values
▪ Directly Capture Exceptions
▪ Big O Notation (Time and Space Complexity)
Meaningful Names
} }
} }
▪ The string length is total size of the variable, whereas the character length is
fixed to 1, so it is more efficient to query and match using characters.
Use StringBuilder for String Concatenation
▪ Strings belong to the final class and the content cannot be modified. As a
result, an object is created once strings are concatenated.
▪ StringBuilder applies for a memory where subsequent strings are
concatenated in the initialization.
▪ No objects are created during the concatenation process and no additional
memory is applied.
Use an isEmpty Instead of a Size Method to Detect Empty Values
System.err.println("Got error null pointer exception when save the data" + e); System.err.println("Got error null pointer exception when save the data" + e);
} else { } catch (Exception e) {
System.err.println("Got another error exception when save the data" + e);
System.err.println("Got another error exception when save the data" + e);
}
}
}
} }
▪ Capture exceptions directly is better than using instanceof for judgment. This
makes the code improves its runtime efficiency.
Big O Notation (Time and Space Complexity)
if(totalNumber == 0){
int arrayFibonacci[]=new int[totalNumber];
return 0; if(totalNumber>0){
} arrayFibonacci[0]=0;
}
return 1;
if(totalNumber>1){
} arrayFibonacci[1]=1;
} System.out.print(arrayFibonacci[i]+" , ");
}
}
}