0% found this document useful (0 votes)
6 views

Good and Bad Code in Java

Uploaded by

Reddy Chandra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Good and Bad Code in Java

Uploaded by

Reddy Chandra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Good and Bad Code in Java

Name : Jake Lukas Ekel


Email : [email protected]
Outline

▪ 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

Bad Code Good Code


private static void copyChars(char a1[], char private static void copyChars(char source[],
a2[]){ char destination[]){
for(int i = 0; i<a1.length; i++){ for(int i = 0; i<source.length; i++){
a2[i] = a1[i]; destination[i] = source[i];
} }
} }

▪ Use intention revealing names


▪ Make meaningful distinctions
Meaningful Names (contd.)

Bad Code Good Code


public class Study { public class Student {

private String nm;


private String name;
private Integer ag;
private Integer age;
private String hmadr;
private String homeAddress;
private String eml; private String email;
} }

▪ Use English word(s)


▪ Use pronounceable names
▪ Classes and Objects name should have noun or noun phrase. Class name
should not be verb.
▪ Method name should have verb or verb phrase.
Comments

Bad Code Good Code


// if student name starts with b and 16 is more than the student
age, the student is eligible for door prize if(isEligibleDoorPrize(name,age){
if(student.getNm().toLowerCase().startsWith("b") && 16 >
student.getAg()){ return true;
return true; }
}
//if(student.getNm().toLowerCase().startsWith("a") && 14 >
student.getAg()){
// return true;
//}

▪ It is necessary to explain directly in the code, without comment


▪ Remove commented out code
Formatting

Bad Code Good Code


public class Main { public class Main {

private static void copyChars(char a1[], char a2[]){


private static void copyChars(char source[], char destination[]){
for(int i = 0; i<a1.length; i++){
for(int i = 0; i<source.length; i++){
a2[i] = a1[i];
destination[i] = source[i];
} }

} }

private static Study student(String nm,Integer ag,


String eml, String hmadr){ private static Student constructStudent(String name, Integer age, String email, String
homeAddress){


} }

} }

▪ Vertical Openness Between Concepts


▪ Horizontal Openness and Density
▪ Indentation
Deal with equals method of Object

Bad Code Good Code


private static boolean checkStudentName(String checkName, String studentName){ private static boolean checkStudentName(String checkName, String studentName){
if(studentName.equals(checkName)){ if(checkName.equals(studentName)){
return true; return true;
} }
return false; return false;
} }
public static void main(String[] args) { public static void main(String[] args) {
… …
checkStudentName("Bob",student.getName(); checkStudentName("Bob",student.getName();
} }

▪ It is possible that NullPointerException be thrown while calling the equals


method of Object. In conclusion, equals should be invoked by a constant or
an object that is definitely not null.
Use Elementary Data Types to Avoid Automatic Packing and Unpacking

Bad Code Good Code


private static void loopFunction(){ private static void loopFunction(){
Integer total = 0; int total = 0;
int[] numbers = {10,40,30,20,50}; int[] numbers = {10,40,30,20,50};
for(int number : numbers){ for(int number : numbers){
total +=number; total +=number;
} }
System.out.println("total = "+total);
System.out.println("total = "+total);
}
}

▪ JVMs (Java virtual machines) support automatic conversion between


elementary data types and packing classes, which is called automatic
packing and unpacking.
▪ Packing and unpacking consume CPU and memory resources, so we should
avoid automatic packing and unpacking as much as possible.
Replace Strings with Characters

Bad Code Good Code


private static void replaceChar(){ private static void replaceChar(){
String source = "a=1,b=2,c=3,d=4"; String source = "a=1,b=2,c=3,d=4";
String target = source.replace("=", ":"); String target = source.replace('=', ':');
System.out.println("target "+target); System.out.println("target "+target);
} }

▪ 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

Bad Code Good Code


private static void appendString(){ private static void appendString(){
String word = ""; StringBuilder word = new StringBuilder(128);
for (int i=0; i<10; i++) { for (int i = 0; i < 10; i++) {
if (i!=0) { if (i != 0) {
word += ','; word.append(',');
} }
word += i; word.append(i);
} }
System.out.println("word = "+word); System.out.println("word = "+word);
} }

▪ 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

Bad Code Good Code


private static void getNames(){ private static void getNames(){
List<String> nameList = new ArrayList<>(); List<String> nameList = new ArrayList<>();
nameList.add("Andy"); nameList.add("Andy");
nameList.add("Bob"); nameList.add("Bob");
nameList.add("Chelsea"); nameList.add("Chelsea");
int nameListLength = nameList.size();
if(nameList.size() == 0){ if(nameList.isEmpty()){
System.out.println("nameList is empty"); System.out.println("nameList is empty");
} }
else{ else{
System.out.println("nameList is not empty"); System.out.println("nameList is not empty");
} }
} }

▪ The time complexity for implementing any isEmpty method is O(1)


▪ The time complexity for implementing equal to size methods is O(n).
Directly Capture Exceptions

Bad Code Good Code


private static void saveStudentData(){
private static void saveStudentData(){
try{
try{
addStudent("Bob",15,"[email protected]","Meisenweg 6 67663 Kaiserslautern");
addStudent("Bob",15,"[email protected]","Meisenweg 6 67663 Kaiserslautern");
} catch (Exception e){
if (e instanceof NullPointerException) { } catch (NullPointerException e) {

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)

Bad Code Good Code


private static int getFibonacciNumber(int totalNumber) { private static void getFibonacciNumber(int totalNumber){

if(totalNumber == 0){
int arrayFibonacci[]=new int[totalNumber];
return 0; if(totalNumber>0){

} arrayFibonacci[0]=0;

else if(totalNumber == 1){ System.out.print(arrayFibonacci[0]+" , ");

}
return 1;
if(totalNumber>1){
} arrayFibonacci[1]=1;

else{ System.out.print(arrayFibonacci[1]+" , ");

return getFibonacciNumber(totalNumber - 1) + for(int i=2;i<totalNumber;i++){

getFibonacciNumber(totalNumber - 2); arrayFibonacci[i] = arrayFibonacci[i-1] + arrayFibonacci[i-2];

} System.out.print(arrayFibonacci[i]+" , ");

}
}
}

▪ Bad Code Time and Space Complexity : O(2^n)


▪ Good Code Time and Space Complexity : O(n)

You might also like