Reputation: 1476
I have a fairly large chunk of code that produces/returns an arraylist of search results that is constructed from a number of datasources. I have been asked to include a date restriction method whereby users can build the array based off 2 date fields. If one of these date fields is populated, lets say its called dateFrom then the array will return data from after that date specified. Similarly if the dateTo is populated then it will populate the array with preceeding data and if both then if will obviously populate based off that range.
This is all nice & easy to do with a couple of simple nested if statements or a switch case, but my problem is that this will also mean that I will have to repeat hefty chunk of code. Is there a way I can prevent the same basic arraylist construction code being repeated 4 times? I know this is horrible psuedo code but it gets my point accross:
if(condition1){
setItem1(getMethod());
setItem2(getMethod());
setItem3(getMethod());
} else if (condition2) {
setItem1(getMethod());
setItem2(getMethod());
setItem3(getMethod());
} else if (condition3) {
setItem1(getMethod());
setItem2(getMethod());
setItem3(getMethod());
} else {
setItem1(getMethod());
setItem2(getMethod());
setItem3(getMethod());
}
return ArrayList();
Its worth noting that although this is more a generalised Java question I am using JSF2 framework and this method occurs in a ViewScoped bean & is implemented using the @PostContruct tag.
Cheers
Upvotes: 0
Views: 543
Reputation: 15042
How about
if(condition1 || condition2 || condition3 ||condition4){
stuff
}
Am I missing something?
Upvotes: 0
Reputation: 13380
I suggest moving the if statement to another method to decrease coupling and then moving the setItems to another method and sending the results of getmethods as parameters. (better if you modify the fields of an object) just pseudocode:
return createArray();
private List createArray()
{
if(condition1){
setItems(getMethod(),getMethod(),getMethod());
return ArrayList();
}
if (condition2) {
setItems(getMethod(),getMethod(),getMethod());
return ArrayList();
}
...
}
private void setItems(Object var1, Object var2, Object var3)
{
...
}
If you want to get rid of the if completely, you can use polymorphism and dependency injection, but it can be overkill in this case...
Upvotes: 3