- Assume a function valid(x) returns a boolean.
if (valid(x) == true) {
}
can be written as:
if (valid(x)) {
}
if (valid(x) == false) {
}
can be written as:
if (!valid(x)) {
}
- Assume m1 and m2 are strings.
if (m1.equals(m2)) {
return true;
} else {
return false;
}
can 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 accessed
}
}
- Checking whether reference is null using equals.
The following code is incorrect:
if (m.equals(null)) { // INCORRECT
System.out.println("m has null");
}
You must use ==
if (m == null) { // CORRECT
System.out.println("m has null");
}
- Accessing instance variables of a class using 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
}
}
- Appending results.
String m; // needs to be initialized to "";
m += "More data";
- Do not use void in constructor.
public class Draw {
public void Draw() { // THIS IS NOT A CONSTRUCTOR
}
}
- Order of expressions must be correct if you rely on short-circuiting.
// THIS IS INCORRECT (what happens if message is null?)
if (message.size() > 10 && message != null) {
}
// CORRECT
if (message != null && message.size() > 10) {
}
- toString() method returns a string; it does not call System.out.println.
-
Avoid the following:
if (expr)
;
else
statements