Domain Driven Design - Access modifier for domain entities - domain-driven-design

I am just starting out with domain driven design and have a project for my domain which is structured like this:
Domain
/Entities
/Boundaries
/UserStories
As I understand DDD, apart from the boundaries with which the outside world communicates with the domain, everything in the domain should be invisble. All of the examples I have seen of entity classes within a domain have a public access modifer, for example here I have a entity named Message:
public class Message
{
private string _text;
public string Text
{
get { return _text; }
set { _text = value; }
}
public Message()
{
}
public bool IsValid()
{
// Do some validation on text
}
}
Would it not be more correct if the entity class and its members were marked as internal so it is only accessible within the domain project?
For example:
internal class Message
{
private string _text;
internal string Text
{
get { return _text; }
set { _text = value; }
}
internal Message()
{
}
internal bool IsValid()
{
// Do some validation on text
}
}

I think there's a confusion here: the Bounded Context is a concept which defines the context in which a model is valid there aren't classes actualy named Boundary. Maybe those are objects for anti corruption purposes, but really the Aggregate Root should deal with that or some entry point in the Bounded Context.
I wouldn't structure a Domain like this, this is artificial, you should structure the Domain according to what make sense in the real world process. You're using DDD to model a real world process in code and I haven't heard anyone outside software devel talking aobut Entities or Value Objects. They talk about Orders, Products, Prices etc
Btw that Message is almost certain a value object, unless the Domain really needs to identify uniquely each Message. Here the Message is a Domain concept, I hope you don't mean a command or an event. And you should put the validation in the constructor or in the method where the new value is given.
In fairness this code is way to simplistc, perhaps you've picked the wrong example. About the classes being internal or public, they might be one or another it isn't a rule, it depends on many things. At one extreme you'll have the approach where almost every object is internal but implements a public interface common for the application, this can be highly inefficient.
A rule of the thumb: if the class is used outside the Domain assembly make it public, if it's something internally used by the Domain and/or implements a public interface, make it internal.

Related

Implementing user-defined business rules with DDD

Let's say If I have an application which let's user create business rules to be applied on a domain entity. A rule can be a combination of a condition and multiple actions where if condition evaluates to true then corresponding actions are executed. This rule is created by users in free-form text format which is then converted to a proprietary format which rule engine can understand and execute.
E.g. For an employee management system, if there is business rule to check if an employee is working in current Role for more than an year and has performed better than expected then can be promoted to next role with a 10% salary increment. This business rule can be entered by users as below.
Condition: Employee.CurrentRoleLength > 1 && Employee.ExceededExpectations()
Action: Employee.PromoteToNextRole() | Employee.GiveSalaryIncrement(10)
Note that multiple Actions are delimited with a |. Also in order to execute this rule, application uses a separate rule engine class library to parse this condition and both actions to a proprietary format, say, ExecutableScript also defined in the rule engine class library.
Now in order to model this requirement using DDD; I have come up with following Domain objects.
Rule (Entity)
Condition (Value Object)
Action (Value Object)
where Rule is an Entity which contains a Condition Value Object and a list of Action Value Objects as below.
public class Rule : Entity
{
public Condition Condition { get; private set; }
public IList<Action> Actions { get; private set;}
public Rule(Condition condition, IList<Action> actions)
{
Condition = condition;
Actions = actions;
}
}
public sealed class Condition : ValueObject<Condition>
{
public string ConditionText { get; private set;}
public ExecutableScript ExecutableCondition{ get; private set;}
public Condition(string conditionText)
{
ConditionText = conditionText;
}
public Parse()
{
ExecutableCondition = // How to parse using external rule engine ??;
}
public Execute()
{
// How to execute using external rule engine ??;
}
}
public sealed class Action : ValueObject<Action>
{
public string ActionText{ get; private set;}
public ExecutableScript ExecutableAction{ get; private set;}
public Action(string actionText)
{
ActionText = actionText;
}
public Parse()
{
ExecutableAction = // How to parse using external rule engine ??;
}
public Execute()
{
// How to execute using external rule engine ??;
}
}
Based on above domain model, I have following questions.
How can I parse and execute Condition and Actions without having a dependency on external rule engine. I understand Domain layer should not have any dependency on outer layers and should be confined to it's own.
Even if I Parse Condition and Actions outside their domain objects, still their parsed ExceutableScript value need to be present within them which will still need dependency on external rule engine.
Is it just that DDD is not the right approach for this scenario and I am going into wrong direction.
Sorry for the long post. Any help would be highly appreciated.
Thanks.
Technical domains may benefit from DDD tactical patterns, but the cost of creating the right abstractions is usually higher than with other domains because it often requires to abstract away complex data structures.
A good way to start thinking about the required abstractions is to ask yourself what abstractions would be needed if you were to swap the underlying technologies.
Here you have a complex text-based expression from which an ExecutableScript is created by the rules engine.
If you think about it there three major elements here:
The text-based expression syntax which is proprietary.
The ExecutableScript which is proprietary; I will assume this is an Abstract Syntax Tree (AST) with an embedded interpreter.
The rule evaluation context which is probably proprietary.
If you were to swap the underlying technology to execute the rules then the expression syntax of the other rule engine may be different and it would certainly have an entirely different rule interpretation mechanism.
At this point we have identified what have to be abstracted, but not what would be the proper abstractions.
You could decide to implement your own expression syntax, your own parser, your own AST which would be a tree-based representation of the expression in memory and finally your own rule evaluation context. This set of abstractions would then be consumed by specific rule engines. For instance, your current rule engine would have to convert a domain.Expression AST to an ExecutableScript.
Something like this (I left out the evaluation context intentionally as you did not provide any information on it).
However, creating your set of abstractions could be costly, especially if you do not anticipate to swap your rule engine. If the syntax of your current rules engine suits your needs then you may use it as your abstraction for text-based expressions. You can do this because it doesn't require a proprietary data structure to represent text in memory; it's just a String. If you were to swap your rule engine in the future then you could still use the old engine to parse the expression and then rely on the generated AST to generate the new one for the other rule engine or you could go back to writing your own abstractions.
At this point, you may decide to simply hold that expression String in your domain and pass it to an Executor when it has to be evaluated. If you are concerned by the performance cost of re-generating the ExecutableScript each time then you should first make sure that is indeed an issue; premature optimization is not desirable.
If you find out that it is too much overhead then you could implement memoization in the infrastructure executor. The ExecutableScript could either be stored in memory or persisted to disk. You could potentially use a hash of the string-based expression to identify it (beware collisions), the entire string, an id assigned by the domain or any other strategy.
Last but not least. Keep in mind that if rule actions aren't processed by aggregates or if the rule predicate spans multiple aggregates then the data used to evaluate the expression may have been stale. I'm not expanding on this because I have no idea how you plan to generate the rule evaluation context and process actions, but I thought it was still worth mentioning because invariant enforcement is an important aspect of every domains.
If you determine that all rules may be eventually consistent or that decisions made on stale data are acceptable then I'd also consider creating an entirely separate bounded context for that, perhaps called "Rule Management & Execution".
EDIT:
Here's an example that shows how creating a rule may look like form the application service perspective, given that expressions are stored as Strings in the domain.
//Domain
public interface RuleValidator {
boolean isValid(Rule rule);
}
public class RuleFactory {
private RuleValidator validator;
//...
public Rule create(RuleId id, Condition condition, List<Action> actions) {
Rule rule = new Rule(id, condition, actions);
if (!validator.isValid(rule)) {
throw new InvalidRuleException();
}
return rule;
}
}
//App
public class RuleApplicationService {
private RuleFactory ruleFactory;
private RuleRepository ruleRepository;
//...
public void createRule(String id, String conditionExpression, List<String> actionExpressions) {
transaction {
List<Action> actions = createActionsFromExpressions(actionExpressions);
Rule rule = ruleFactory.create(new RuleId(id), new Condition(conditionExpression), actions);
ruleRepository.add(rule); //this may also create and persist an `ExecutableScript` object transparently in the infrastructure, associated with the rule id.
}
}
}
How can I parse and execute Condition and Actions without having a dependency on external rule engine. I understand Domain layer should not have any dependency on outer layers and should be confined to it's own.
This part is easy: dependency inversion. The domain defines a service provider interface that describes how it wants to talk to some external service. Typically, the domain will pass a copy of some of its internal state to the service, and get back an answer that it can then apply to itself.
So you might see something like this in your model
Supervisor.reviewSubordinates(EvaluationService es) {
for ( Employee e : this.subbordinates ) {
// Note: state is an immutable value type; you can't
// change the employee entity by mutating the state.
Employee.State currentState = e.currentState;
Actions<Employee.State> actions = es.evaluate(currentState);
for (Action<Employee.State> a : actions ) {
currentState = a.apply(currentState);
}
// replacing the state of the entity does change the
// entity, but notice that the model didn't delegate that.
e.currentState = currentState;
}
}

What do we call for these types of objects that used within Domain Model in DDD?

I have tried to find a solution to this naming problem, but I could not find a similar usage anywhere on the web. It could be either we have a design flow in the domain model, or we simply don't use the appropriate name for so called "ValueObjects".
Please read below..
We use Domain Driven Design with CQRS pattern. Below is how the domain model has been designed.
P.S Not related but for your information, our application uses ASP.NET MVC and the Controller comminicate withe the Service Layer. DTOs (Data Transfer Objects) are passed in/out to the MVC Controllers, which is not in the above diagram.
The problem is that we don’t use the "ValueObject" correctly. According Martin Fowler’s definition our ValueObjects are not a true representation of a ValueObject.
http://martinfowler.com/bliki/ValueObject.html
For example our ValueObjects have an identity.
public class NoteValue
{
public int Id { get; set; }
public string NoteName { get; set; }
public string NoteNumber { get; set; }
public DateTime NotExpiry { get; set; }
}
These ValueObjects simply carry data between the Commands, AggregateRoots and Domain Entities.
For example AggregateRoot simply creates ValueObjects based on the Domain Entities, and return those ValueObjects to the Command Layer.
Below is not the complete implementation. Just a simple example to show the interaction
AggregateRoot extension method:
private static IList<NoteValue> ToValueObject(this ICollection<Note> source)
{
var values = new List<NoteValue>();
if (source != null)
source.ForEach(i => values.Add(i.ToValueObject()));
return values;
}
AggregateRoot :
Public IList<NoteValue> GetNotesValues()
{
return this._notes.ToValueObject();
}
Command :
var motesValues = notesAggregate.GetNotesValues();
We are struggling to find an appropriate name for these so called “ValueObjets”. They don't seem to be DTOs either and also we want to be able to differentiate from the DTOs that are used in the Services layer. Specifically we want to know an appropriate name that we can call for these types of objects (ValueObjects). Any thoughts greatly appreciated.
I don't know if this answers your questions but I might hopefully point you in the right direction.
There is a very good talk about Value Objects by Dan Berg Johnsson: http://www.viddler.com/v/6939b23
Also have a look at Vaughn Vernon's papers on Effective Aggregate Design: http://dddcommunity.org/library/vernon_2011
All in all DDD (especially when applying CQRS on the architectural level) takes some time to grasp. Be patient, read, learn, and join the DDD/Cqrs Google group

Connecting the dots with DDD

I have read Evans, Nilsson and McCarthy, amongst others, and understand the concepts and reasoning behind a domain driven design; however, I'm finding it difficult to put all of these together in a real-world application. The lack of complete examples has left me scratching my head. I've found a lot of frameworks and simple examples but nothing so far that really demonstrates how to build a real business application following a DDD.
Using the typical order management system as an example, take the case of order cancellation. In my design I can see an OrderCancellationService with a CancelOrder method which accepts the order # and a reason as parameters. It then has to perform the following 'steps':
Verify that the current user has the necessary permission to cancel an Order
Retrieve the Order entity with the specified order # from the OrderRepository
Verify that the Order may be canceled (should the service interrogate the state of the Order to evaluate the rules or should the Order have a CanCancel property that encapsulates the rules?)
Update the state of the Order entity by calling Order.Cancel(reason)
Persist the updated Order to the data store
Contact the CreditCardService to revert any credit card charges that have already been processed
Add an audit entry for the operation
Of course, all of this should happen in a transaction and none of the operations should be allowed to occur independently. What I mean is, I must revert the credit card transaction if I cancel the order, I cannot cancel and not perform this step. This, imo, suggests better encapsulation but I don't want to have a dependency on the CreditCardService in my domain object (Order), so it seems like this is the responsibility of the domain service.
I am looking for someone to show me code examples how this could/should be "assembled". The thought-process behind the code would be helpful in getting me to connect all of the dots for myself. Thx!
Your domain service may look like this. Note that we want to keep as much logic as possible in the entities, keeping the domain service thin. Also note that there is no direct dependency on credit card or auditor implementation (DIP). We only depend on interfaces that are defined in our domain code. The implementation can later be injected in the application layer. Application layer would also be responsible for finding Order by number and, more importantly, for wrapping 'Cancel' call in a transaction (rolling back on exceptions).
class OrderCancellationService {
private readonly ICreditCardGateway _creditCardGateway;
private readonly IAuditor _auditor;
public OrderCancellationService(
ICreditCardGateway creditCardGateway,
IAuditor auditor) {
if (creditCardGateway == null) {
throw new ArgumentNullException("creditCardGateway");
}
if (auditor == null) {
throw new ArgumentNullException("auditor");
}
_creditCardGateway = creditCardGateway;
_auditor = auditor;
}
public void Cancel(Order order) {
if (order == null) {
throw new ArgumentNullException("order");
}
// get current user through Ambient Context:
// http://blogs.msdn.com/b/ploeh/archive/2007/07/23/ambientcontext.aspx
if (!CurrentUser.CanCancelOrders()) {
throw new InvalidOperationException(
"Not enough permissions to cancel order. Use 'CanCancelOrders' to check.");
}
// try to keep as much domain logic in entities as possible
if(!order.CanBeCancelled()) {
throw new ArgumentException(
"Order can not be cancelled. Use 'CanBeCancelled' to check.");
}
order.Cancel();
// this can throw GatewayException that would be caught by the
// 'Cancel' caller and rollback the transaction
_creditCardGateway.RevertChargesFor(order);
_auditor.AuditCancellationFor(order);
}
}
A slightly different take on it:
//UI
public class OrderController
{
private readonly IApplicationService _applicationService;
[HttpPost]
public ActionResult CancelOrder(CancelOrderViewModel viewModel)
{
_applicationService.CancelOrder(new CancelOrderCommand
{
OrderId = viewModel.OrderId,
UserChangedTheirMind = viewModel.UserChangedTheirMind,
UserFoundItemCheaperElsewhere = viewModel.UserFoundItemCheaperElsewhere
});
return RedirectToAction("CancelledSucessfully");
}
}
//App Service
public class ApplicationService : IApplicationService
{
private readonly IOrderRepository _orderRepository;
private readonly IPaymentGateway _paymentGateway;
//provided by DI
public ApplicationService(IOrderRepository orderRepository, IPaymentGateway paymentGateway)
{
_orderRepository = orderRepository;
_paymentGateway = paymentGateway;
}
[RequiredPermission(PermissionNames.CancelOrder)]
public void CancelOrder(CancelOrderCommand command)
{
using (IUnitOfWork unitOfWork = UnitOfWorkFactory.Create())
{
Order order = _orderRepository.GetById(command.OrderId);
if (!order.CanBeCancelled())
throw new InvalidOperationException("The order cannot be cancelled");
if (command.UserChangedTheirMind)
order.Cancel(CancellationReason.UserChangeTheirMind);
if (command.UserFoundItemCheaperElsewhere)
order.Cancel(CancellationReason.UserFoundItemCheaperElsewhere);
_orderRepository.Save(order);
_paymentGateway.RevertCharges(order.PaymentAuthorisationCode, order.Amount);
}
}
}
Notes:
In general I only see the need for a domain service when a command/use case involves the state change of more than one aggregate. For example, if I needed to invoke methods on the Customer aggregate as well as Order, then I'd create the domain service OrderCancellationService that invoked the methods on both aggregates.
The application layer orchestrates between infrastructure (payment gateways) and the domain. Like domain objects, domain services should only be concerned with domain logic, and ignorant of infrastructure such as payment gateways; even if you've abstracted it using your own adapter.
With regards to permissions, I would use aspect oriented programming to extract this away from the logic itself. As you see in my example, I've added an attribute to the CancelOrder method. You can use an intercepter on that method to see if the current user (which I would set on Thread.CurrentPrincipal) has that permission.
With regards to auditing, you simply said 'audit for the operation'. If you just mean auditing in general, (i.e. for all app service calls), again I would use interceptors on the method, logging the user, which method was called, and with what parameters. If however you meant auditing specifically for the cancellation of orders/payments then do something similar to Dmitry's example.

App-level settings in DDD?

Just wanted to get the groups thoughts on how to handle configuration details of entities.
What I'm thinking of specifically is high level settings which might be admin-changed. the sort of thing that you might store in the app or web.config ultimately, but from teh DDD perspective should be set somewhere in the objects explicitly.
For sake of argument, let's take as an example a web-based CMS or blog app.
A given blog Entry entity has any number of instance settings like Author, Content, etc.
But you also might want to set (for example) default Description or Keywords that all entries in the site should start with if they're not changed by the author. Sure, you could just make those constants in the class, but then the site owner couldn't change the defaults.
So my thoughts are as follows:
1) use class-level (static) properties to represent those settings, and then set them when the app starts up, either setting them from the DB or from the web.config.
or
2) use a separate entity for holding the settings, possibly a dictionary, either use it directly or have it be a member of the Entry class
What strikes you all as the most easy / flexible? My concerns abou the first one is that it doesn't strike me as very pluggable (if I end up wanting to add more features) as changing an entity's class methods would make me change the app itself as well (which feels like an OCP violation). The second one feels like it's more heavy, though, especially if I then have to cast or parse values out of a dictionary.
I would say that that whether a value is configurable or not is irrelevant from the Domain Model's perspective - what matters is that is is externally defined.
Let's say that you have a class that must have a Name. If the Name is always required, it must be encapsulated as an invariant irrespective of the source of the value. Here's a C# example:
public class MyClass
{
private string name;
public MyClass(string name)
{
if(name == null)
{
throw new ArgumentNullException("name");
}
this.name = name;
}
public string Name
{
get { return this.name; }
set
{
if(value == null)
{
throw new ArgumentNullException("name");
}
this.name = value;
}
}
}
A class like this effectively protects the invariant: Name must not be null. Domain Models must encapsulate invariants like this without any regard to which consumer will be using them - otherwise, they would not meet the goal of Supple Design.
But you asked about default values. If you have a good default value for Name, then how do you communicate that default value to MyClass.
This is where Factories come in handy. You simply separate the construction of your objects from their implementation. This is often a good idea in any case. Whether you choose an Abstract Factory or Builder implementation is less important, but Abstract Factory is a good default choice.
In the case of MyClass, we could define the IMyClassFactory interface:
public interface IMyClassFactory
{
MyClass Create();
}
Now you can define an implementation that pulls the name from a config file:
public ConfigurationBasedMyClassFactory : IMyClassFactory
{
public MyClass Create()
{
var name = ConfigurationManager.AppSettings["MyName"];
return new MyClass(name);
}
}
Make sure that code that needs instances of MyClass use IMyClassFactory to create it instead of new'ing it up manually.

Should I use log4net directly in my domain model objects?

I'm wondering if it's bad practice to use log4net directly on my domain object... I'll be using ELMAH for my exceptions on the ASP.NET MVC application side, but for some informational purposes I'd like to log some data about the domain model itself.
Given the following domain object:
public class Buyer
{
private int _ID;
public int ID
{
get { return _ID; }
set
{
_ID = value;
}
}
private IList<SupportTicket> _SupportTickets=new List<SupportTicket>();
public IList<SupportTicket> SupportTickets
{
get
{
return _SupportTickets.ToList<SupportTicket>().AsReadOnly();
}
}
public void AddSupportTicket(SupportTicket ticket)
{
if (!SupportTickets.Contains(ticket))
{
_SupportTickets.Add(ticket);
}
}
}
Is adding logging behavior in the AddSupportTicketMethod a bad idea...so essentialy it'd look like this:
public class Buyer
{
protected static readonly ILog log = LogManager.GetLogger(typeof(SupportTicket));
public Buyer()
{
log4net.Config.XmlConfigurator.Configure();
}
private int _ID;
public int ID
{
get { return _ID; }
set
{
_ID = value;
}
}
private IList<SupportTicket> _SupportTickets=new List<SupportTicket>();
public IList<SupportTicket> SupportTickets
{
get
{
return _SupportTickets.ToList<SupportTicket>().AsReadOnly();
}
}
public void AddSupportTicket(SupportTicket ticket)
{
if (!SupportTickets.Contains(ticket))
{
_SupportTickets.Add(ticket);
} else {
log.Warn("Duplicate Ticket Not Added.");
}
}
}
I have used log4net and log4J directly in domain objects. This has good side effects and bad ones.
+: Logging in the domain object is simple and straightforward to code and you know you can take advantage of log4net features.
--: It means the program making use of the domain objects needs to pay attention to log4net configuration, which may or may not be a problem
--: You cannot link your domain object to a different log4net version than the calling program is using. I've seen a lot of conflicts with one item linked against log4net 1.2.0.10 and another linked against an earlier release.
Not logging in your domain object is a bad idea. The alternative is as others have suggested, dependency injection or an external framework (such as commons-logging for log4J) that allows plugging different logging frameworks or creating an interface that does the logging and logging against that interface. (The code using your domain object would need to then supply an appropriate instance of that interface for logging purposes.)
If you are going to log from your domain objects and you use an IOC container which you might want to swap out, I would recommend you use the Service Locator pattern (you could look at the Sharp# architecture for a nice implementation of a SafeServiceLocator that wraps msoft's ServiceLocator with more informative error messages).
I would also like to suggest that you consider whether you want to log the type of error you show in your example. I would tend to want to have the domain object throw an exception in that case and let the caller decide whether that was something that was expected by the application (and hence shouldn't be logged) or whether that represents a situation that the caller wants to deal with in some way.
This is a classic question!
The good way of doing this would be to introduce a class member of ILogger type and abstract the logging into this interface. In your class wherever you do a call to logg something do it through this interface. Then inject this dependency at the run-time with one of the implementation using one of the available IoC container or dependency injection farmeworks. By default you can use log4net implementation of this interface.
Here is a long list of available dependency injection frameworks:
http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx
I think logging is a cross cutting concern, so it's best done in an aspect-oriented fashion. If you're using a framework like Spring.NET it's available to you.

Resources