- Examples
- Course.java
- Student.java
- Utilities.java
- Assume a function valid(x) returns a boolean
if (valid(x) == true) {
// code here
}
should be written as:
if (valid(x)) {
// code here
}
if (valid(x) == false) {
// code here
}
should be written as:
if (!valid(x)) {
// code here
}
- Assume m1 and m2 are strings
if (m1.equals(m2)) {
return true;
} else {
return false;
}
should be written as:
return m1.equals(m2);
- Accessing private fields of class
public class Example {
private int cost;
public int getCost() { return cost; }
public Example(Example e) {
cost = e.getCost();
}
// copy constructor can be written as:
public Example(Example e) {
cost = e.cost; // even though cost is private it can be access
// you don't need to use a getMethod
}
}
- Accessing instance variables of a class using current object reference ("this")
public class Example {
private int cost;
public Example(int cost) {
this.cost = cost; // you need "this"
}
public int getCost() {
return this.cost; // you don't need "this"
}
public void setCost(int costIn) {
cost = costIn; // you don't need "this"
}
}
- null statement
if (expr)
; // null statement (do nothing)
else {
// statements
}
should be written as:
if (!expr) {
// statements
}
- cascaded if - When you have a set of cases and only one case should be executed
Avoid:
if (expr1) {
// statements1
}
if (expr2) {
// statements2
}
if (expr3) {
// statements3
} else {
// else statements
}
above should be written as:
if (expr1) {
// statements1
} else if (expr2) {
// statements2
} else if (expr3) {
// statements3
} else {
// else statements
}
In the second one once an expression is true, no further expression evaluation
takes place.