-4

I need to test whether data returned from a search is correct. Several operators can be used for search (term, prefix, wildcard etc.), several fields can be searched (firstName, lastName, email, address etc.), and of course any search word (''John'', ''Smith'', ''john.smith@gmail.com'') can be entered. Thus I have ended up with a lot of switch statements, switches inside switches, to generate the JSON query according to the parameters that the user inputs.

public static class FakeSearch
{
  public static string GenerateQuery(string _operator, string field, string value)
  {
    QueryRootobject searchObj = new QueryRootobject();
    searchObj.Query = new Query();
    searchObj.Query.Bool = new Bool();
    searchObj.Query.Bool.Must = new Must[1];
    searchObj.Query.Bool.Must[0] = new Must();

    switch (_operator)
    {
      case "term":
        searchObj.Query.Bool.Must[0].Term = new Term();
        switch (field)
        {
          case "firstName":
            searchObj.Query.Bool.Must[0].Term.FirstName = value;
            break;
          case "lastName":
            searchObj.Query.Bool.Must[0].Term.LastName = value;
            break;
          case "phone":
            searchObj.Query.Bool.Must[0].Term.Phone = value;
            break;
          case "email":
            searchObj.Query.Bool.Must[0].Term.Email = value;
            break;
        }
        break;
      case "prefix":
        searchObj.Query.Bool.Must[0].Prefix = new Prefix();
        switch (field)
        {
          case "firstName":
            searchObj.Query.Bool.Must[0].Prefix.FirstName = value;
            break;
          case "lastName":
            searchObj.Query.Bool.Must[0].Prefix.LastName = value;
            break;
          case "phone":
            searchObj.Query.Bool.Must[0].Prefix.Phone = value;
            break;
          case "email":
            searchObj.Query.Bool.Must[0].Prefix.Email = value;
            break;
        }
        break;
      }
      case "wildcard":
        // and so on
}

Can/should this be improved in some way? All the switch statements seem like way too much.

0

It is not clear from your question whether every object has the same properties or not, although the example code suggests they do.

If so, the term, prefix and wildcard objects could implement an interface that has all the properties (FirstName, LastName, Phone, Email, whatever). Then you can pass this interface to your new method.

If not, you could still isolate the inner switch in a method that has a case for every possible action, pass the object as object and check for the existence of each property before performing the assignment using reflection.

Not the answer you're looking for? Browse other questions tagged or ask your own question.