Introduced factory to decide on the query type and general refactoring.