DDD: Administration and encapsulation - domain-driven-design

What are your methods to deal with the communication of an admin panel with a domain in the case of changing values of properties of an entity without breaking the encapsulation?
public class Book : Entity {
public Book(string title, string author, string description, decimal price, short publicationYear) {
Title = title;
Author = author;
Description = description;
Price = price;
PublicationYear = publicationYear;
}
public string Title { get; private set; }
public string Author { get; private set; }
public string Description { get; private set; }
public decimal Price { get; private set; }
public short PublicationYear { get; private set; }
}

The only way to not break encapsulation is to include some parts of the presentation logic into the object itself. Not the details, mind you, but the parts which are highly coupled to this object.
I would do something like this (pseudo-code):
public class Book {
public Book(...) {
...
}
public InputComponent<Book> createAdminView() {
return new FormGroup<Book>(
new TextInput(title),
new TextInput(author),
...);
}
}
This way there is no need to publish any of the internal data fields of the object, nobody needs to know how to book looks like, and all changes related to the object will be localized.
In fact, I've been doing this for a couple for years now, and this design results in much easier to maintain code. Have a look at my presentation about Object-Oriented Domain-Driven Design to find out more: https://speakerdeck.com/robertbraeutigam/object-oriented-domain-driven-design

Related

Explicit State Modeling in DDD

I've been looking managing Root Aggregate state/life-cycle and found some content about the benefits of using Explicit State Modeling or Explicit Modeling over State Pattern, it's much cleaner and I like how I can let explicit concepts of my domain handle their own behavior.
One of the things I read was this article that is influenced by Chapter 16 in "Patterns, Principles, and Practices of Domain-Driven Design - Scott Millett with Nick Tune" book (here's a code sample for the full example).
The problem is the idea is described very briefly and there is not much content around it and that appeared when I started to implement it and given that I am new to DDD, the concepts started to overlap, and here are some of the questions that I am hoping more experienced engineers in DDD would help or at least someone has interpreted the text better than me.
Following the article's example, how would I retrieve a list of all doors (that are both open and closed), what Domain Entity would this result-set map to?
If all the explicit states models are entities/aggregates, what would be the root aggregate?
would it be normal that there is no reference between Root Aggregate and those explicitly modeled entities?
And if the Aggregate Root (let's say a generic Door entity) returns an explicit state entity, how would the repository save it without exposing the state of the entity or aggregate?
Or are all these explicit entities root of their own aggregate?
I am not expecting to get all the above answered, I am just sharing the thoughts that am stuck at, so you are able to see where I am standing, as there is too much ambiguity for me to share code but I hope the snippets from the article and the book can help.
A git repository or a sample project addressing how would other DDD components with Explicit modeling would be really helpful (I have checked a million repositories but 90% with no luck).
Note: I am not using CQRS
Example from Medium Article:
interface ClosableDoor
{
public function close();
}
// Explicit State. (third attempt)
class CloseDoorService()
{
// inject dependencies
public function execute($doorId)
{
$door = $this->doorRepository->findClosableOfId($doorId);
if (!$door) {
throw new ClosableDoorNotFound();
}
$door = $door->close();
$this->doorRepository->persist($door);
}
}
Example from the book:
// these entities collectively replace the OnlineTakeawayOrder entity (that used the state pattern)
public class InKitchenOnlineTakeawayOrder
{
public InKitchenOnlineTakeawayOrder(Guid id, Address address)
{
...
this.Id = id;
this.Address = address;
}
public Guid Id { get; private set; }
public Address Address { get; private set; }
// only contains methods it actually implements
// returns new state so that clients have to be aware of it
public InOvenOnlineTakeawayOrder Cook()
{
...
return new InOvenOnlineTakeawayOrder(this.Id, this.Address);
}
}
public class InOvenOnlineTakeawayOrder
{
public InOvenOnlineTakeawayOrder(Guid id, Address address)
{
...
this.Id = id;
this.Address = address;
}
public Guid Id { get; private set; }
public Address Address { get; private set; }
public CookedOnlineTakeawayOrder TakeOutOfOven()
{
...
return new CookedOnlineTakeawayOrder(this.Id, this.Address);
}
}
Note: I am not using CQRS
I think this is the biggest challenge you have.
Retrieving explicitly modelled entities for the purpose of the use case being implemented would not cause such a headache if you were not also trying to use them for queries that may not be constrained to an explicit model designed for a specific use case.
I use Entity Framework which supports "table-splitting" that could help in this situation. Using this, many entities can be mapped to the same table but each can deal with a subset of the fields in the table and have dedicated behaviour.
// Used for general queries
class Door
{
public Guid Id { get; private set; }
public State State { get; private set; }
// other props that user may want included in query but are not
// relevant to opening or closing a door
public Color Color { get; private set; }
public Dimensions Dimensions { get; private set; }
public List<Fixing> Fixings { get; private set; }
}
class DoorRepository
{
List<Door> GetDoors()
{
return _context.Doors;
}
}
// Used for Open Door use case
class ClosedDoor
{
public Guid Id { get; private set; }
public State State { get; private set; }
public void Open()
{
State = State.Open;
}
}
class ClosedDoorRepository
{
List<ClosedDoor> GetClosedDoors()
{
return _context.ClosedDoors.Where(d => d.State == State.Closed);
}
}
// Used for Close Door use case
class OpenDoor
{
public Guid Id { get; private set; }
public State State { get; private set; }
public void Close()
{
State = State.Closed;
}
}
class OpenDoorRepository
{
List<OpenDoor> GetOpenDoors()
{
return _context.OpenDoors.Where(d => d.State == State.Open);
}
}

C# ConcurrentDictonary Setting values in collection other then the key

Please look through my code before closing it this time.
The code below works but seems very hacked, I am looking for suggestions on to achieve the same thing with cleaner code or is this as good as it gets.
The code calling the Add and Remove will be from different threads that could possible access the code at the same time, so it must remain thread-safe.
using System;
using System.Collections.Concurrent;
namespace Server
{
public class Company
{
public string Name { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
public ConcurrentDictionary<string, Employee> Employees = new ConcurrentDictionary<string, Employee>();
}
public class Employee
{
public string First { get; set; }
public string Last { get; set; }
public string Ext { get; set; }
}
public class Clients
{
public ConcurrentDictionary<string, Company> CompaniesDict = new ConcurrentDictionary<string, Company>();
public bool Add_Company(string ID, string Name, string Address, string Phone) //This function works
{
Company MyCompany = new Company();
Employee MyEmployees = new Employee();
MyCompany.Name = Name;
MyCompany.Address = Address;
MyCompany.Phone = Phone;
MyCompany.Employees = MyEmployees;
return CompaniesDict.TryAdd(ID, MyCompany);
}
public bool Remove_Company(string ID) //This function works
{
return CompaniesDict.TryRemove(ID, Company tCompany);
}
//This is were I need the help this seems so hacked. Im not trying to update the key, but the value intstead
public bool Set_CompanyName(string ID, string Name)
{
CompaniesDict.TryGetValue(ID, out Company oCompany);
Company nCompany;
nCompany = oCompany;
nCompany.Name = Name;
return CompaniesDict.TryUpdate(ID, nCompany, oCompany);
}
public string Get_CompanyName(string ID)
{
CompaniesDict.TryGetValue(ID, out Company tCompany);
return tCompany.Name;
}
}
}
Please don't just close this and link me to some useless code you call a duplicate. Sorry to be so blunt but this has recently happened to me by a fellow coder on this site. If you have questions that I can answer so that you can full help me please ask them.
Thanks for you help in advance.
There is a much easier approach, as you are updating a field on an object.
Please note that I don't have C# installed on my current PC, so can't validate this.
Note that I declare the out parameter, but don't construct a new one that would be destroyed immediately and I modify the object itself.
i.e.
Company company;
not
Company company=new Company();
This will still not be deterministic if multiple threads call SetCompanyName(), as the new name is updated on the live object and there could be a potential race condition. However the Add and Remove will be, even if Remove removes the company instance just before its name is updated.
public bool Set_CompanyName(string ID, string Name)
{
Company company;
var retval= CompaniesDict.TryGetValue(ID, out company)
if (retval) {
company.Name=Name; // Update your company object directly
}
//else Do something such as throw an exception if it's not found
return retval;
}

DDD Service Method Granularity

So, I'm building a system for managing contacts. My contact domain model has quite a few string properties, as well as booleans. In the spirit of keeping behavior inside of the domain models, I've gone down the path of creating "update methods." I'm starting to feel like it's getting a bit burdensome. In the past, CRUD apps would just have a single update method and it would set all of the properties in one shot.
Am I on the right path? I'm concerned about having 10 - 15 update methods on my domain service and domain entities.
FYI, the example given is a bit contrived, so imagine a model with lots of string and boolean properties.
// Application Layer Stuff
public class UpdateContactCommand
{
public UpdateNamePredicate UpdateName { get; set; }
public UpdatePhonePredicate UpdatePhone { get; set; }
public int ContactId { get; set; }
}
public class UpdateNamePredicate
{
public string NewFirstName { get; set; }
public string NewLastName { get; set; }
}
public class UpdatePhonePredicate
{
public string NewPHone { get; set; }
}
public class UpdateContactResponse
{
public bool Success { get; set; }
public string Message { get; set; }
}
public interface IWcfService
{
UpdateContactResponse UpdateContact(UpdateContactCommand updateContactCommand);
}
public class WcfService : IWcfService
{
private readonly IContactService _contactService;
public WcfService(IContactService contactService)
{
_contactService = contactService;
}
public UpdateContactResponse UpdateContact(UpdateContactCommand updateContactCommand)
{
if (updateContactCommand.UpdateName != null)
{
_contactService.UpdateName(updateContactCommand.ContactId, updateContactCommand.UpdateName.NewFirstName,
updateContactCommand.UpdateName.NewLastName);
}
if (updateContactCommand.UpdatePhone != null)
{
_contactService.UpdatePhone(updateContactCommand.ContactId, updateContactCommand.UpdatePhone.NewPHone);
}
return new UpdateContactResponse();
}
}
// Domain Layer
public interface IContactService
{
// There are lots more of these
void UpdateName(int contactId, string newFirstName, string newLastName);
void UpdatePhone(int contactId, string newPhone);
}
public class ContactService : IContactService
{
private readonly IContactRepository _contactRepository;
public ContactService(IContactRepository contactRepository)
{
_contactRepository = contactRepository;
}
public void UpdateName(int contactId, string newFirstName, string newLastName)
{
var contact = _contactRepository.GetById(contactId);
contact.SetName(newFirstName, newLastName);
_contactRepository.Commit();
}
public void UpdatePhone(int contactId, string newPhone)
{
var contact = _contactRepository.GetById(contactId);
contact.SetPhone(newPhone);
_contactRepository.Commit();
}
}
public interface IContact
{
int Id { get; set; }
// There are lots more of these
void SetName(string newFirstName, string newLastName);
void SetPhone(string newPhone);
}
public class Contact : IContact
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public void SetName(string newFirstName, string newLastName)
{
FirstName = newFirstName;
LastName = newLastName;
}
public void SetPhone(string newPhone)
{
Phone = newPhone;
}
}
public interface IContactRepository
{
IContact GetById(int id);
void Commit();
}
public class ContactRepository : IContactRepository
{
public IContact GetById(int id)
{
// Not important
throw new NotImplementedException();
}
public void Commit()
{
// Not important
throw new NotImplementedException();
}
}
First of all, not all applications lend themselves well to a DDD approach. If you say your application could pretty much have been implemented in a CRUDish way before, chances are it's still CRUD now. Don't try to apply DDD on any app because it's the shiny new thing.
That being said, you don't just write "update methods" for the fun of it. They have to reflect the domain tasks your user wants to perform. Why does the user want to update a Contact ? Has the contact moved or just changed phone number ? Changed marital status and name ? Has the point of contact in a company been taken over by another employee ?
Usually, you won't have tons of update methods for a given entity. There's always a way to group changes in operations that are meaningful for the domain. Good ways to force yourself to do it are :
Think about the maximum number of form fields you can reasonably display to the user. Couldn't you split that complex UI into smaller, more meaningful screens ? From there you have to start reasoning (preferably with the help of a domain expert) about the tasks these should reflect.
Make your entity fields immutable from the outside. Thus you'll have to think harder about their true nature -- what should be in the constructor ? what should some other manipulation methods be ?

Is instantiating a collection in a domain model considered a good practice?

I see these types of model is many samples online.
public class User
{
public long Id { get; set; }
public string Name{ get; set; }
public virtual ICollection<Product> Products { get; set; }
}
Is it considered a good practice to instantiate a collection in the constructor like the code below? If so what are the reasons? How about objects in the model?
public class User
{
public User()
{
Products = new List<Product>();
}
public long Id { get; set; }
public string Name{ get; set; }
public virtual ICollection<Product> Products { get; set; }
}
Well, I would say it depends on the situation, but Products in this case would be filled from the database, via a repository, so most probably ORM of some sort, so no initialization to new List would be needed in the constructor. The meaning of null for Products is indicative that the list isn't loaded yet. On the other hand, let's say that your object must have this collection initialized. For simple objects DDD says constructors are perfectly fine to to these things, but in case of complex objects, move the construction to the Factory.

Domain Modelling Help - Product and Suppliers

I have this domain model (simplified), that represents a product that has a basic price and attached has numerous suppliers that provide a specific discount percentage against the basic price:
public class CarDerivative
{
public string Name { get; set; } e.g. StackOverflow Supercar 3.0L Petrol
public double BasicPrice { get; set; } e.g. 10,000
public double Delivery { get; set; } e.g. 500
public IList<SupplierDiscount> { get; set; } // has 3 various suppliers
}
public class SupplierDiscount
{
public string SupplierName; { get; set; }
//public SupplierInformation SupplierDetails { get; set; } // maybe later
public double BasicDiscount { get; set; }
public double DeliveryDiscount { get; set; } // e.g. 0.10 = 10%
}
Now, I'm thinking about where stuff should sit that does stuff with this:
For example, where best does BasicDiscountedPrice (stable formula) sit, should it ideally sit on SupplierDiscount which is furnished with a reference to the parent CarDerivative via constructor injection?
Where in your opinion should an unstable formula sit? Such as SupplierPriceForDerivative (basic + delivery + tax +++) ?
My knee-jerk reaction to this would be that Discounts should be Policies. Each DiscountPolicy might look like this:
public interface IDiscountPolicy
{
decimal GetDiscountedPrice(CarDerivative car);
}
Your SupplierDiscount might be a simple implementation of such a Policy, while your unstable formulas might be implemented in a more complex class.
I think it would be safest to keep the Entities and the Policies separate, so that you can vary them independently from each other.

Resources