Use either Apache Commons ToStringBuilder or Guava's MoreObjects.ToStringHelper. Or get inspired by them.
Design pattern for long if null statements for POJO object
-
05-08-2022 - |
Вопрос
I'm looking for a design pattern or even advice on some code that I saw the other day. The general structure is this (pseudo code):
public String getUrl(){
Person person= new Person();
StringBuilder builder = new StringBuilder();
if(person.getName() != null){
builder.append(",_name=");
builder.append(person.getName());
}
if(person.getLastName() != null){
builder.append(",_lastName=");
builder.append(person.getName());
}
if(person.getPostCode() != null){
builder.append(",_postCode=");
builder.append(person.getPostCode());
}
// So on and so forth
return builder.toString();
}
Now the problem is that I don't have control over Person class (I'm just given it via an API call). I was thinking to use reflection and a map like so:
Map<String, String> methodNameToUrlParameter; //Pre Build this map with method name and the actual parameter key
Map<String, String> urlParameterToValue;
Method[] methods = person.getMethods();
for(Method method: methods ){
String result = (String) method.invoke(person, null);
if(result != null){
String urlParam = methodNameToUrlParameter.get(method.getName());
urlToValue.put(urlParam, result );
}
}
Then I can go on my merry way. But this doesn't seem too great to me and I don't really know all too much about reflection, any ideas? Remember, I have no control over the Person class and it just has getters since it's immutable.
Thanks.
Edit:
What I am asking is there a better way to represent the flow of logic here with out using a too many if statements that do null checks. Perhaps a design pattern that I do not know about.
2nd Edit: There's maybe like 20 if-null checks, which made things ugly. Is there a way todo it without none?
Решение
Другие советы
For a minor change with better readability, you could pull the redundant code into its own method:
void AddField(StringBuilder builder, String value, String fieldName) {
if (value != null) {
builder.append(",_");
builder.append(fieldName);
builder.append("=");
builder.append(value);
}
}
which would simplify your code sample to the following:
public String getUrl(){
Person person= new Person();
StringBuilder builder = new StringBuilder();
AddField(builder, person.getName(), "name");
AddField(builder, person.getLastName(), "lastName");
AddField(builder, person.getPostCode(), "postCode");
// So on and so forth
return builder.toString();
}