Reputation: 1627
Suppose a User
has many Car
s. These cars only belongs to him.
You could represent this 2 ways :
A User
entity with a cars collection and a main_car attribute, pointing to one in the collection. The business rule would be: a user can only have a main car belonging to him.
OR
A User
entity, with a cars collection. One of these cars could have a Boolean is_main
attribute. The business rule would be: Only 1 car belonging to a user could be defined as main.
The business rules would be enforced in the setters.
I would like to have your advises and the pros and cons of the 2 approaches. Thanks !
Upvotes: 1
Views: 50
Reputation: 5477
Option one would be the most commonly adopted approach.
The issue with making an is_main field on a car entity is that if you selected is_main for one user, any other user that had that car would also have that car set to is_main. Furthermore, it would be possible for several cars to be the "main" car for any given user because all cars could have their is_main property set to true, it would be hard to restrict this.
If your user has a main_car field they can and will only ever have one main car at any given time.
There are also data integrity issues with your second approach (you are potentially unintentionally de-normalizing your database). You could delete a car type and therefore remove a user's main car without throwing any kind of warning or exception (causing a loss of useful information). If you tried to delete a car that was a user's main car in approach one you would get an error because the user would suddenly have a main car that did not exist.
Upvotes: 1
Reputation: 450
One big problem with the second option is say you have two people, p1 and p2, who drive the same car. The car may be the main car for p1 but not p2, so you can't simply set an is_main field for the car. This hopefully explains the class responsibility aspect a bit more.
For that reason I'd go with the first option.
Upvotes: 2
Reputation: 37299
I'd prefer the first option.
Pros:
Cons:
I hope I understood correctly what you asked and that my answer helps you
Upvotes: 2