Composibility is a good metrics for code reuse. When possbile, always try to make a piece of code composible.
Consider this example:
public class Person {
private final String firstName, lastName;
// ctor, getters omitted
public String toJson() {
return new StringBuilder()
.append("{")
.append("\"first_name\"").append(firstName)
.append(',')
.append("\"last_name\"").append(lastName)
.append("}")
.toString();
}
}
But what if there's a need for toJsonPretty
?
public String toJson(boolean pretty) {
// omitted if-else
}
Ok, but what about there's a need for specifying level of indentation being 2 or 4?
public String toJson(boolean pretty, int indentation) {
// omitted if-else and then if else
}
Does it work? Not quite - what if there's a need of listOfPeople.toJson
? How do you tell the indentation from within Person
class? What about type List<Map<String, Person>>
?
The problem is that String
is quite a composible type.
Consider the following:
public class Person {
public Map<String, Object> toMap() {
return ImmutableMap.builder()
.put("first_name", firstName)
.put("last_name", lastName);
.build();
}
}
and then
public class JsonSerializer {
public String listToJson(List<Object> list, boolean pretty, int indentationLevel) {
// you can call mapToJson from here
}
public String mapToJson(Map<String, Object> map, boolean pretty, int indentationLevel) {
}
}