I have a interface DataStore, which provides access to a generic data store, e.g. a local database, webserver, etc. I want to provide a way to filter results directly in the query. How should i pass filters for the query?

I thought of a map which gets passed with the name of the field as the key and the desired value as the element.


class Foo {
    String firstProperty;
    int secondProperty;
    boolean thirdProperty;


    "firstProperty": "desired value",
    "secondProperty": 123

The datastore then filters the returned values (e.g. a sql query might do this more efficiently than my Java code)

Or would it be better to let the user of the DataStore filter the results?


In most cases, you should aspire to have the data store filter the results. It could save lots of I/O between your application and the data store (network I/O), as well as within the data store itself (disk I/O).

Usually, you'd want the filter to express relations more complex than just "equals to". You'd want to be able to express conditions like greater than, less than, between, not null etc.

I personally would give up on having it generic (unless providing a generic component is a real business goal), and would create a data access layer that provides answers to specific questions relevant to my application. Each method would accept a Criteria class which is built specifically for the relevant method (the QuerySales method would accept a SalesCriteria object, the FindCustomers method would accept a CustomersCriteria object).

If you insist on a generic solution:

One way would be to pass a map where the keys are the property names, and the mapped values contain both the Relation (or Operator) and the respective value or values (one for binary operations like "greater than", two for trenary operations like "between"). For more complex filters you'll need something like expression trees as devnull mentioned.

Another way would be to pass a query string in some query language, and use a query language parser.


Your solution doesn't take operators into account thus being very limited from the get go. Some languages have data structures for building expression trees which can be used by the DAL framework for filtering or sorting. If the language you're using doesn't support them you should think about building a simple expression tree engine or find an existing one.

If you let the user filter the results, depending on your data access strategy, you risk loading more data than needed. The users should only be allowed to build the filter expression and pass it to the data source.

  • Some languages even hide the building of expression trees in the language syntax. Linq-to-SQL and IQueryable spring to mind. – Caleth Aug 31 '17 at 11:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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