Which object-oriented code smells come up most often in Java reviews, and how do you refactor each one?
Here are the six that come up most often in Java reviews, with the fix for each one.
public class Main {
public static void main(String[] args) {
Renderer r = new HtmlRenderer();
System.out.println(r.render("hi"));
}
}
And here they are.
the smell the fix
---------------------------------------- --------------------------------------------
a long parameter list make a class out of the
parameters that travel together
a long method split it into named methods
a switch on the type of the object give the object the method
a public mutable field make it private and check
a class with one job and a name that split it, one class per job
does not match
static methods that reach into pass the thing in
everything
And the fourth one is worth showing, because it is the one that the switch on the type replaces.
// The smell. The method asks what the object is.
public String render(Object item) {
if (item instanceof HtmlDocument) {
return ((HtmlDocument) item).toHtml();
}
if (item instanceof PlainDocument) {
return ((PlainDocument) item).toPlain();
}
return "";
}
// The fix. The object answers for itself.
public interface Renderable {
String render();
}
And the last one is worth explaining, because it is a common one in older code bases. A static method that reaches into global state is hard to test and hard to reason about, because the thing it depends on is hidden.
// The smell. The dependency is hidden.
public static void save(User user) {
Database.write(user);
}
// The fix. The dependency is a parameter.
public static void save(User user, Database database) {
database.write(user);
}
And there is one more smell that is worth knowing about, and it is the one that the other question in this topic is about. And that is the refused bequest.
So the rule to remember is this. A long list, a long method, a type switch, a public field and a hidden dependency are the five you will see most.
The last question in this topic is about the refused bequest.