views:

57

answers:

3

When creating domain model, we almost always have Id field or property for our entities which represents the primary key column of corresponding table in the database. My question is - if I have this key property that has nothing to do with the domain model (in other words, it's just database concern; Martin Fowler prefers to name it meaningless key), is persistence layer leaking into my domain? And if it is, how do I prevent it?

+1  A: 

From the big book titled: Database Systems - The complete book.

Keys are attributes or sets of attributes that uniquely identify an entity within its entity set. No two entities may agree in their values for all of the attributes that constitute a key. It is permissible, however, for two entities to agree on some, but not all, of the attributes.

-

Our experience [...] might lead us to believe that it is difficult to find keys or to be sure that the set of attributes forms a key. In practice the matter is usually much simpler. In the real-world situations commonly modeled by databases, people often go out of their way for entity sets. For example, companies generally assign employee ID's to all employees, and these ID's are carefully chosen to be unique numbers. One purpose of these ID's are to make sure that in the company database each employee can be distinguished from all others, even if there are several employees with the same name. Thus, the employee-ID attribute can server as a key for employees in the database.

While it is true that entities differing only in the inserted artificial ID may introduce duplicate (redundant) data, their use is far from meaningless. An an extra way of distinguishing different domain entities, does not in my opinion interfere with the domain itself.

But as for an answer for your question:

Is persistence layer leaking into my domain? And if it is, how do I prevent it?

If you really, really want to. You can use a combination of entity attributes to define the entity keys.

Hope it helps.

Thomas Børlum
+1  A: 

Look at the problem another way: Will hiding the Primary Keys make it easier for your team to develop the solution, or make it even harder?

Don't worry about PK values 'leaking' into your entities - I'm sure your software has bigger problems that need to be solved.

Vijay Patel
A: 

Make sure the meaningful keys are identified in the model as well. Including the surrogates may be optional but including the meaningful keys that make sense of your data in the real world is much more important.

dportas