📎 Webclip
How to isolate complex queries in an object oriented fashion – Alfredo Motta
The article starts from a talent-hunting system that searches football players by team, shooting accuracy, and age. Instead of keeping these conditions inside TalentHunter as a chain of conditional query clauses, it proposes moving them into a separate object tied to the talent-hunting use case.
Reading notes#
- The example system searches players using three criteria: big team membership, good shooting accuracy, and young age.
- The first implementation builds the query in
TalentHunterwith conditional statements. - The text suggests refactoring with Extract Method or with scopes in the
Playermodel. - The proposed alternative uses a Query Object-style approach.
- The goal is to isolate queries in a separate object without adding scopes to the active record model.
- The text says queries like young, good shooting accuracy, and playing for a top team make sense in the talent-hunting task.
InterestingPlayeris presented as a decorator-like object that behaves likePlayerand adds query methods.- Some methods on
InterestingPlayerreturn a new wrapped object so queries can keep composing. - Other delegated methods return the final result when the underlying relation no longer matches a relation type.
TalentHunterthen uses domain terms such asright_foot,playing_for_big_team,with_great_shoot_accuracy, andyoung.- The article says this makes
find_good_forwardeasier to read and keeps the general model less polluted. - It concludes that the approach simplifies both the query builder and the
TalentHunterobject.
