MrMoog
MrMoog

Reputation: 417

Design pattern for a multi field search box

I realized an advanced search module for a website (made in Struts 2). This search area is a form with many different fields. I can put strings in all, some or none of the fields getting different results depending on the choice. What I do now is to check with a big bad if/elseif statement if there are blank fields (and which) and then apply the right method.

Example

    if (field_1.equals("") && field_2.equals("")) {
        dao.searchAll;
    } else if (field_1.equals("") && !field_2.equals("")) {
        dao.searchType1;
    } else if (!field_1.equals("") && !field_2.equals("")) {
        dao.searchType2;
    } else if {
       ...
       ...

Where dao's methods are HQL (hibernate) queries.

This example is more simple than my case in which I have 5 textinput fields.

There is a better and flexible way to do the same thing? Some design pattern like Strategy?

Upvotes: 0

Views: 494

Answers (2)

Rob
Rob

Reputation: 11733

Struts is really weak. First thing to note is don't tie your behavior directly to interface components. In JSF, you would bind those fields to properties on a class then reference them from there (the components embodying the query dispatching should know nothing about the input sources).

A dispatcher is basically what you have here: when certain messages are received, trigger specific responses. I would put the values into some immutable form and then make a factory method(s) to fetch or make the appropriate queries. Then execute outside the factory construct.

It's not a strategy. You could have different ways of figuring out what to do but this is a creational problem: you are turning fragments of input into queries.

Upvotes: 1

proskor
proskor

Reputation: 1412

Take a look at the Hibernate Criteria API. You can use it to construct queries based on the fields. So, for example, you could write something like this:

Criteria criteria = session.createCriteria(Some.class);
if (!field_1.equals("")) {
  criteria.add( /*some criteria for field_1 */ );
}
if (!field_2.equals("")) {
  criteria.add( /*some criteria for field_2 */ );
}

Upvotes: 0

Related Questions