What's the correct way to model a true/false property in my domain?
Imagine I have开发者_运维百科 a domain with a Entity and one of properties of this Entity is a true/false property like a Active/Inactive.
What's the correct way to model this?
- Using a boolean? False = Inactive and True = Active ?
Using a Enum:
public enum Status { Active = 1, Inactive = 2 }
I think using a Enum is the correct way, but using a Boolean property I also see is not wrong.
What you guys of DDD think about this?
If it's a true/false pair, then boolean is just fine IMHO. No need to overcomplicate things.
If the value is being used as a method parameter, an enum or even class might be better for readability. But then again, you might consider calling two different methods instead.
Possible issue with enum is that one might be able to use invalid values. This can be mitigated by using a class like this:
public class ActivityState {
public static ActivityState Active = new ActivityState();
public static ActivityState Inactive = new ActivityState();
}
...
// in your entity:
public ActivityState IsActive { get; set; }
this.IsActive = ActivityState.Active; // or
this.IsActive = ActivityState.Inactive;
It can be used like an enumeration, but makes sure that no invalid values are allowed.
I would say that Enums are there just for these cases, to avoid mapping concepts with primitive types or classes.
For example, avoid mapping 2 value logic with boolean, or for more values (like the colours of a semaphore: red, green, yellow) with integers 1, 2, 3.
Enums are there just to avoid that, and to make it clear what each one of them means, improving legibility and maintainability, as well as type safety (you can restrict a method to just receive your Enum type, and not the wider Boolean type, this makes your code safer).
Use enums when You need state machine.
Enum says that flags are mutually exclusive and closely related.
E.g. - if we have a Warrior class in RPG game, it can have states "Alive" or "Dead". Those can't be truthful both simultaneously. Therefore - it makes sense to use enums here.
In contrast: Warrior can be fighting/running/drinking/talking/eating/sleeping. Here we can't use enum because those aren't mutually exclusive (Warrior should be able to run in circles while swinging his sword and eating sandwich).
精彩评论