This is a design problem I am facing. Let’s say I have a cars website. Cars have the following attributes with different possible values.
- Color: red, green, blue
- Size: small, big
Based on those attributes I want to classify between cars for young people, cars for middle aged people and cars for elder people, with the following criteria:
- Cars_young: red or green
- Cars_middle_age: blue and big
- Cars_elder: blue and small
I’ll call this criteria target
I have a table cars with columns: id, color and size.
I need to be able to:
a) when retrieving a car by id, tell its target (if it’s young, middle age or elder people)
b) be able to query the database to know how many views had cars belonging to each target
Also, as a developer, I must implement it in a way that those criteria are easily changed.
Which is the best way to implement it? Is there a design pattern for it? I can explain two possible solutions I thought about but I don’t really like:
1) create a new column in the database table called target, so it’s easy to make both a) and b).
Drawbacks: Each time crieteria changes I have to update the column target for all cars, and also, I have to change the insertNewCar() function.
2) Implement it in the ‘Cars’ class.
Drawback: Each time criteria changes I have to change query in b) as well as code in ‘getCarById’ in a).
3) Use TRIGGERS in SQL, but I would like to avoid this solution if possible
I would like to be able have this criteria definition somewhere in the code which can be changed easily, and would also hopefully be used by ‘Cars’ class. I’m thinking about some singleton or global objects for ‘target’ which can be injected in some Cars methods.
Anyone can explain a nice solution or send documentation about some post that faces this problem, or a pattern design that solves it?
On first sight
specificationpattern might meet your expectations. Wikipedia gives a nice explanation how it works, small teaser bellow:You can consider combine
specificationpattern withobservers.Also there are few other ideas:
specificationpattern on SQL generation, WHERE clauses in particular