Reputation: 781
Imagine you need to develop an application, e.g. C# WPF, where a user can select a value for some option, and this selection defines available values for other options, and so on.
For example, let's consider a structure for cars.
A user selects make, model, and trim. All of these properties have a limited and predefined list of available values, like "Toyota", "Honda", "VW", "Ford", "Mazda", etc. for make.
Each manufacturer has a list of available models, like "Golf", "Passat", etc., and each model has some trims, like "SE", "LE", etc.
Selecting a trim, a user can then select other options, like an engine ("V8 Guzzoline" or "Win! Diesel"), "big fat tires, everything", "hardwood floor and stainless steel appliances", etc.
So, we could design a Car class with the following properties:
"Options" would be probably a separate class. I have a problem with those "one of a few available values, that enables further selection" properties, though.
We could use some enums for them ("one of a few available values") and then a monstrous "if-else" factory method to create a proper car object. However, these enums would be different for models and trims for all manufacturers, and basically different enum types destroy these class hierarchy.
We could use just strings, like this:
public class Car {
public string Make {get; set; }
public string Model {get; set; }
public string Trim {get; set; }
public CarOptions Options {get; set; }
}
but this is error prone, and it's tricky to ensure that the selected value is one of the predefined values.
This task seems quite common, but I couldn't find a flexible solution so far to build the class hierarchy. I wonder if there are some patterns that I'm missing.
Upvotes: 0
Views: 54
Reputation: 11301
If you have a simple system, supposedly with only values A and B, where selection of A determines available subset of B, then you can get away with just defining one table with two columns. This table would contain all valid pairs (A, B).
Then, you populate the first list with values obtained like:
SELECT DISTINCT a FROM Table
Once particular value for a has been picked, you select available B values like:
SELECT b FROM Table WHERE Table.a = selected_A
This is the simplest case. If things become more complicated, like having a number of attributes belonging to A and another bunch of attributes belonging to B, you might wish to define two distinct tables and join them with foreign key relation.
Upvotes: 0
Reputation: 5314
This is a pretty common scenario for a relational database. Consider that whether a certain trim
is related to a specific model
, and model
to make
, etc.
Then it becomes easy to define tables with foreign keys. Look at AutoZone, PepBoys, etc. for actual examples using your car scenario. User selects a make
from the drop down (first table). Then you retrieve all entries from model
table with a FK to that make
. Then same for trim
from the model
selection. And so on.
Upvotes: 1