Namespace for (DDD) entities cutting across domains - namespaces

I have a couple of business-related domains like Purchase, Marketing and Economy. Having the models arranged into a namespace* for each domain would be nice, but there are some entities cutting across domains, like an Item. How to organize those cross-cutting objects?
* = As in C#/Java/Python namespaces.

Since you have the concept of Bounded Context, you should not share domains between the namespaces. Actually, you should have one Item for each namespace that requires it, and each of those Item should have it's own fields as required by the context it is included.
As Eric Evans said, it is not a big deal replicate data in order to never share the same domain between contexts, but only data.

Determining whether you have the correct design will require some experience with the domain so you should check with your domain expert.
You may very well require a Shared Kernel for classes that are cross-cutting. You'll have to be careful that you do not abuse the shared kernel by placing too many generic / logical classes in there.
To add to what #rafaels88 has answered you may need to create a BC specific domain construct where some logical entity exists. For instance, a User in the Identity & Access Control BC would be an Author in one BC but perhaps a Supervisor in another.
You could also duplicate an AR in one BC as a VO in another. A Customer in the CRM BC may be the system of record for a customer and, therefore, contain a whole lot more information. In the Order BC, however, a Customer VO may only contain an Id, Name, and perhaps Address (for example).
So you will need to evaluate what type of object you have before deciding where to place it.

Related

Access control: RBAC with additional group memberships instead of object properties

Given an application that shows objects (e.g. films) according to certain user permissions.
The general permission to show or create objects is implemented as RBAC with roles and permissions.
The specific permission to access an object with certain attributes (e.g. a film with the attribute “drama”) should be implemented with memberships. That means the object doesn’t have the property “drama”, it is a member of the group “drama”. If the user and the object are members in the same group, the user has the specific permission to access this object. There can be different groups for showing, creating or deleting an object, like a simple viewer group or some kind of editor group. Furthermore there is a table that specifies which group types are relevant for certain actions on certain objects. For example relevant groups for the action “show” on the object "film" could be “genre” and “age” (film's suitability for certain audiences).
The reason to implement it in the described way is to have great flexibility without touching the code. Changes to groups can be processed in the database.
General database design:
Example: The film "The Revenant" is a member of the groups "genre:drama" and "age:18". The user can access it, if he is a member of these groups too.
Does this sound like a good approach? Are there any existing solutions that are similar to this approach? Does it have major drawbacks (e.g. too many database queries - there may be several hundred users every day)?
Please share your thoughts on this issue with me - the choice of "drama" as category for the example is not a coincidence ;) I just dont know if this is a dead end or if I am heading to the right direction. I stuck at this point for quite a while.
At least you have a good sense of humor :-)
Your approach sounds fine. So long as you keep the number of parameters low, then you can get away with role-based access control (RBAC) and a few additional parameters e.g. group membership.
But in the long run, if you want to implement business-driven authorization (access control), you need a way to do this independently of your code: you do not want to rewrite your app code every time there is a requirements change.
To do so, there is an access control model called Attribute-Based Access Control (ABAC) that will let you define your authorization policies independently of your code.
In ABAC, you have the following concepts:
an architecture which defines a policy enforcement point (PEP) and a policy decision point (PDP). The PEP sits in front of (or within) your app. It intercepts the business requests (e.g. a request to view a film) and sends an authorization request to the PDP. The PDP is configured with policies. Based on the request the PDP will reach a decision: either yes, Permit or no, Deny.
a policy language: the policy language is attribute-based (hence the name ABAC). This means that you can use any number of attributes (e.g. user role, user id, user group memberships, but also user age, user location, user subscription as well as resource attributes such as movie rating, movie category, movie price...)
a request / response scheme: this is how you ask for authorization. It is essentially a yes/no flow. "Can a user do X?", "Yes they can."
There are several implementations of ABAC out there - some of which are framework-specific e.g. CanCanCan. XACML and ALFA are two approaches that are not tied to any particular framework. You can choose from open-source and commercial implementations of either language e.g.:
Open Source: SunXACML, ATT XACML
Commercial: Axiomatics Policy Server

What XML or JSON or ??? data format can describe a complex set of requirements?

I need to express
A passing grade in a pre-requite class, in order to access the next one.
An exemption policy to the above, where the professor can override the requirement.
A student can only have one such exemption in a given span of time (year)
Students must be older than 21
Students can only be enrolled in 3 eligible majors
Or similarly, the NY DMV has a complex set of documents and prerequisites in order to obtain a driver's license.
Question
What abstract syntax will allow me to describe the rules listed above, in a platform neutral way?
Use case
I'm developing an app where people define eligibility rules to access certain data. Those rules may have prerequisites, or key/value ranges to access it.
I am thinking XML, but that might become cumbersome. Just as swagger has become the "easier way" to handle web services, I'm looking for a similar "easy" syntax to handle these rules.

Should I instantiate a collection or inherit from collection?

I've asked myself this question a number of times when creating classes, particularly those involving collections, but I've never come up with a satisfactory answer. It's a OOP design question.
For example, in a checkbook register program say I have a class of BankAccount. BankAccounts contain data involving the Name of the account, the Type of account (enum of Checking, Saving,...), and other data, but most importantly is a collection of the Adjustments (deposits or withdrawals) in the account.
Here, I have two options for keeping a collection of the Adjustments:
Instantiate a collection and keep it as a member within the BankAccount class. This is like saying "BankAccount has a collection of Adjustments."
Inherit from collection. This is like saying "BankAccount is a collection of Adjustments."
I think both solutions are intuitive, and, of course, both offer some advantages and disadvantages. For example, instantiating allows the class (in languages that allow only a single base class) to inherit from another class, while inheriting from collection makes it easy to control the Add, Remove, and other methods without having to write surrogate methods to 'wrap' those.
So, in such situations, which is a better approach?
To me, a bank account has a collection of adjustments. A bank account is not a collection of adjustments, because it "is" much more than that: it also "is" a name and a type, etc.
So, in your case (and similar cases), I suggest you aggregate a collection inside your class.
In case of doubt, avoid inheritance. :-)
I can argument this further. In order to use inheritance properly, the subclass must satisfy Liskov's substitution principle; this means that, in your case, BankAccount should be a valid type anywhere a Collection is expected. I don't think that's the case, because a Collection probably exposes methods such as Add() and Remove(), whereas you will want to exert some control over adding and removing adjustments from your bank account rather than letting people add and remove them freely.
Personally, I would say BankAccount has a collection of Adjustment. It will probably have other properties that aren't exclusively about what has been deposited or withdrawn ( customer, bank account type, etc ).
In terms of design, my BankAccount object would expose a late-loading property of type Adjustments.
In terms of use within the code, I would instantiate the bank account, and if I needed to know what had gone in and out of the account, I would use the exposed property. The BankAccount would be the primary object, responsible for providing the Adjustments related only to the instantiated account.
Instantiate, definitely.
I agree with the other posters about Bank Account being "more" than just a collection of other items.
Or maybe you jut picked an example which really screams out for "instantiate".
Examples:
What happens if your Bank Account needs a second collection of completely different items? (Example: collection of people who can operate on it, like husband and wife, for example, collection of credit cards, paypal accounts or anything else that can "operate" on your bank account).
Depending on the language a collection exposes too much of its info: if another object needs to access Adjustements... say for displaying your movements history on a web page you automatically expose your "collection" for injection, deletion and so on.
I think getting overly caught up in semantics like "is this more is-a or has-a" is a little bit dangerous - at the end of the day, what matters is how well your design solved the problem, how maintainable it is, etc. In fact, personally, a turning point in the way I understand object oriented programming was letting go of "objects as nouns". Objects are, when you get down to it, an abstraction one level up from a function, nothing more or less.
This was a long way to say "has a". :-) Subclassing is complicated, using is easy.

How do you come up with names for your namespaces?

I'll preface this by saying that I usually work in C#/.Net.
Normally, I use a naming scheme that puts common, reusable components into a namespace that reflects our organization and project-specific components into a namespace tied to the project. One of the reasons I do this is that I sometimes share my components with others outside my department, but within the organization. Project-specific namespaces are typically prefaced with the name or abbreviation of the department. When I reuse code between projects, I typically migrate it into one of the organization-based namespaces.
For example:
UIOWA.DirectoryServices contains classes that deal with the specific implementation of our Active Directory.
UIOWA.Calendar contains classes that deal with the University's master calendar.
LST.Inventory.Datalayer holds the classes implementing the data layer of the Learning Spaces Technology group inventory application.
I'm embarking on a project now for an entity that has a fuzzier connection to the Unviersity (a student group that runs a charity event) that has the potential to be sold outside of our University and, thus, it doesn't really fit into my normal naming conventions, i.e., the department is only the first customer of potentially many that might use the project.
My inclination is to go the organization naming route and create an "organizational project" name space for this application. I'd like to hear how others handle this and any advice you might have.
Thanks.
See also this related question about namespace organization.
EDIT
I ended up creating the org/project namespace UIOWA.MasterEvent and deriving further namespaces from there. Still interested in other opinions for future projects.
My department got his name changed thrice in the last five years, so we're all glad that someone decided against using namespaces with organisational names...
Our namespaces are organised by project names. Reusable stuff is put into the Toolbox namespace. Perhaps a bit crude, but it works quite well so far.
I'm a .NET developer, and I always use the organisational project namespace (com.bolidian.projectspace) because it guarantees uniqueness.
I use the organisation, followed by the product eg Acme.Crm. When grouping classes together in a subnamespace always use a plural or action so that it cant clash with a class. eg
Acme.Crm.Letters
Acme.Crm.Invoicing
I follow Microsoft's convention by not capitalising acronyms eg Crm instead of CRM, Sql instead of SQL - but that's more a personal preference.

How to avoid Anemic Domain Models and maintain Separation of Concerns?

It seems that the decision to make your objects fully cognizant of their roles within the system, and still avoid having too many dependencies within the domain model on the database, and service layers?
For example: Say that I've got an entity with a revision history, and several "lookup tables" that the data references, your entity object should have methods to get the details from some of the lookup tables, whether by providing access to the lookup table rows, or by delegating methods down to them, but in order to do so it depends on the database layer to read the data from those rows. Also, when the entity is saved, It needs to know not only how to save itself, but also to save entries into the revision history. Is it necessary to pass references to dozens of different data layer objects and service objects to the model object? This seems like it makes the logic far more complex to understand than just passing back and forth thin models to service layer objects, but I've heard many "wise men" recommending this sort of structure.
Really really good question. I have spent quite a bit of time thinking about such topics.
You demonstrate great insight by noting the tension between an expressive domain model and separation of concerns. This is much like the tension in the question I asked about Tell Don't Ask and Single Responsibility Principle.
Here is my view on the topic.
A domain model is anemic because it contains no domain logic. Other objects get and set data using an anemic domain object. What you describe doesn't sound like domain logic to me. It might be, but generally, look-up tables and other technical language is most likely terms that mean something to us but not necessarily anything to the customers. If this is incorrect, please clarify.
Anyway, the construction and persistence of domain objects shouldn't be contained in the domain objects themselves because that isn't domain logic.
So to answer the question, no, you shouldn't inject a whole bunch of non-domain objects/concepts like lookup tables and other infrastructure details. This is a leak of one concern into another. The Factory and Repository patterns from Domain-Driven Design are best suited to keep these concerns apart from the domain model itself.
But note that if you don't have any domain logic, then you will end up with anemic domain objects, i.e. bags of brainless getters and setters, which is how some shops claim to do SOA / service layers.
So how do you get the best of both worlds? How do you focus your domain objects only domain logic, while keeping UI, construction, persistence, etc. out of the way? I recommend you use a technique like Double Dispatch, or some form of restricted method access.
Here's an example of Double Dispatch. Say you have this line of code:
entity.saveIn(repository);
In your question, saveIn() would have all sorts of knowledge about the data layer. Using Double Dispatch, saveIn() does this:
repository.saveEntity(this.foo, this.bar, this.baz);
And the saveEntity() method of the repository has all of the knowledge of how to save in the data layer, as it should.
In addition to this setup, you could have:
repository.save(entity);
which just calls
entity.saveIn(this);
I re-read this and I notice that the entity is still thin because it is simply dispatching its persistence to the repository. But in this case, the entity is supposed to be thin because you didn't describe any other domain logic. In this situation, you could say "screw Double Dispatch, give me accessors."
And yeah, you could, but IMO it exposes too much of how your entity is implemented, and those accessors are distractions from domain logic. I think the only class that should have gets and sets is a class whose name ends in "Accessor".
I'll wrap this up soon. Personally, I don't write my entities with saveIn() methods, because I think even just having a saveIn() method tends to litter the domain object with distractions. I use either the friend class pattern, package-private access, or possibly the Builder pattern.
OK, I'm done. As I said, I've obsessed on this topic quite a bit.
"thin models to service layer objects" is what you do when you really want to write the service layer.
ORM is what you do when you don't want to write the service layer.
When you work with an ORM, you are still aware of the fact that navigation may involve a query, but you don't dwell on it.
Lookup tables can be a relational crutch that gets used when there isn't a very complete object model. Instead of things referencing things, you have codes, which must be looked up. In many cases, the codes devolve to little more than a static pool of strings with database keys. And the relevant methods wind up in odd places in the software.
However, if there is a more complete object model, we have first-class things instead of these degenerate lookup values.
For example, I've got some business transactions which have one of n different "rate plans" -- a kind of pricing model. Right now, the legacy relational database has the rate plan as a lookup table with a code, some pricing numbers, and (sometimes) a description.
[Everyone knows the codes -- the codes are sacred. No one is sure what the proper descriptions should be. But they know the codes.]
But really, a "rate plan" is an object that is associated with a contract; the rate plan has the method that computes the final price. When an app asks the contract for a price, the contract delegates some of the pricing work to the associated rate plan object.
There may have been some database query going on to lookup the rate plan when producing a contract price, but that's incidental to the delegation of responsibility between the two classes.
I aggree with DeadBeef - therein lies the tension. I don't really see though how a domain model is 'anemic' simply because it doesn't save itself.
There has to be much more to it. ie. It's anemic because the service is doing all the business rules and not the domain entity.
Service(IRepository) injected
Save(){
DomainEntity.DoSomething();
Repository.Save(DomainEntity);
}
'Do Something' is the business logic of the domain entity.
**This would be anemic**:
Service(IRepository) injected
Save(){
if(DomainEntity.IsSomething)
DomainEntity.SetItProperty();
Repository.Save(DomainEntity);
}
See the inherit difference ? I do :)
Try the "repository pattern" and "Domain driven design". DDD suggests to define certain entities as Aggregate-roots of other objects. Each Aggregate is encapsulated. The entities are "persistence ignorant". All the persistence-related code is put in a repository object which manages Data-access for the entity. This way you don't have to mix persistence-related code with your business logic. If you are interested in DDD, check out eric evans book.