Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DDD: Enum like entities

I have the following DB model:

**Person table**
ID    |    Name    | StateId
------------------------------
1          Joe       1
2          Peter     1
3          John      2

**State table**
ID    |    Desc
------------------------------
1          Working
2          Vacation

and domain model would be (simplified):

public class Person
{
    public int Id { get; }
    public string Name { get; set; }
    public State State { get; set; }
}

public class State
{
    private int id;
    public string Name { get; set; }
}

The state might be used in the domain logic e.g.:

if(person.State == State.Working)
    // some logic

So from my understanding, the State acts like a value object which is used for domain logic checks. But it also needs to be present in the DB model to represent a clean ERM.

So state might be extended to:

public class State
{
    private int id;
    public string Name { get; set; }

    public static State New {get {return new State([hardCodedIdHere?], [hardCodeNameHere?]);}}
}

But using this approach the name of the state would be hardcoded into the domain.

Do you know what I mean? Is there a standard approach for such a thing? From my point of view what I am trying to do is using an object (which is persisted from the ERM design perspective) as a sort of value object within my domain. What do you think?

Question update: Probably my question wasn't clear enough.

What I need to know is, how I would use an entity (like the State example) that is stored in a database within my domain logic. To avoid things like:

  if(person.State.Id == State.Working.Id)
      // some logic

or

if(person.State.Id == WORKING_ID)
// some logic
like image 745
Chris Avatar asked Feb 10 '10 14:02

Chris


2 Answers

Your proposed structure seems fine. (Terminology digression: since State has an ID, it's not a Value Object, but rather an Entity.)

Enums are a code smell, so don't attempt to go that route. It's much more object-oriented to move the behavior into the State object using the State pattern.

Instead of having to write

if (person.State == State.Working)
    // do something...

all over your code, this would allow you to write

person.State.DoSomething();

That's much cleaner, and will allow you to add new States if need be.

like image 64
Mark Seemann Avatar answered Sep 30 '22 07:09

Mark Seemann


A previous question of mine unearthed some useful links that I suspect are pertinent to your question, in particular Jimmy Bogard's discussions of Enumeration Classes.

like image 45
rohancragg Avatar answered Sep 30 '22 06:09

rohancragg