A domain model that does not contain the business logic for the model is considered an anti-pattern by some -
https://en.wikipedia.org/wiki/Anemic_domain_model
But in some applications, such as .NET applications, seem to prefer a model with out business logic.
Would the following be a good implementation of combining these two concepts.
Have a base model, with the constructor and all "set" statements defined as protected, then have a class that inherits from that base class, which implements the business logic for the base class and helps create the base object. The base model could then be used for something like an MVC View.
Base class -
public class Customer
{
protected Customer()
{
}
public string FirstName { get; protected set; }
public string LastName { get; protected set; }
public int Age { get; protected set; }
}
Inheriting class -
public class CustomerCreator : Customer
{
public void SetFirstName(string firstName)
{
this.FirstName = firstName;
}
public void SetLastName(string lastName)
{
this.LastName = lastName;
}
public string SetAge(int age)
{
string result = "";
if (age < 18)
{
return "can't be less than 18";
}
this.Age = age;
return result;
}
public Customer GetCustomer()
{
return this;
}
}
Are there any potential hazards to this pattern?
Is this a pattern that is already commonly used?
I don't think you're really buying yourself anything here. Ultimately casting to Customer via the GetCustomer() method doesn't actually change anything in terms of the ability to get properties on the model. You're still indirectly robbing your customer of its own business logic with the derived CustomerCreator class. I think you're better off placing your logic in the class you expect to work with (ie Customer) and creating a projection in the form of a viewmodel or DTO for displaying data to the client. Try something like this for your domain model:
public class Customer
{
private int _age;
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age
{
get => _age;
set
{
if (value < 18)
{
throw new ArgumentOutOfRangeException(nameof(Age), "can't be less than 18");
}
_age = value;
}
}
protected Customer() { }
}
A couple of additional points:
I'd recommend avoiding restricting access on your properties unnecessarily. In the case of FirstName and LastName there are no invariants attached to them so the protected setters are not only confusing, but require additional unnecessary indirection to work with. This could also be confusing in the future if other devs (or you after some time away to forget) question why the accessibility was limited to begin with. Going from less to more restricted access modifiers can be done when business rules demand it and it's a relatively safe operation- almost all issues that can arise as a result of restricting access will do so at design time. Going from more restrictive to less restrictive access should always be done with an abundance of caution- if a property/field/method/etc is less than public then hopefully it was designed that way with good reason. Overlooking those reasons can lead the circumvention of invariants, which can lead to runtime issues, inconsistent system state, and corrupt data.
There is nothing particular to C#/.NET that requires or recommends anemic models. Many developers write their models that way and then act upon them with a variety of services, but that general pattern is not necessary by any means nor is it specific to C#. The teams I have worked with implement rich models that are directly persisted and rehydrated via ORMs such as Entity Framework and while it sometimes requires making concessions due the the quirks of a particular ORM, it always ends up working well.
What you're describing is a builder pattern a pattern that's a part of a more broadly defined set of creational patterns. The most obvious examples are builders such as StringBuilder and UriBuilder.
There's a few problems with a builder pattern on the entity side of things in the DDD world, and in particular your current implementation.
First, builders are suitable for value objects, which are fungible and can have value even if not complete (e.g. just a street address with no zip code). For entities, a factory would be more suitable because we want our entities to always be valid (see this great blog entry by Vladimir Khorikov). A factory doesn't turn out an incomplete car, for example; no one would buy that car because, well, it's not a car yet!
Second, your example uses inheritance, and mixes concepts. Let's examine this.
(Wrong) Alternatives
Inheritance models an is-a relationship. Ask yourself, "Is a CustomerBuilder a Customer?" The answer is no; you can say a HouseBuilder (a person) is not a House so inheritance is not appropriate here. It's the same with customers.
You're also not going to do this using composition, which models a has-a relationship. Does a CustomerBuilder have a Customer? No. By analogy, a HouseBuilder does not have a house, a house builder makes a house. Aside: the builder might live in a house, and thus own one, but how does that have anything to do with building some other house?
Creational Patterns
So, the most natural relationship here is a creational one, and in particular a factory. In your case you'd want a customer factory that creates a customer. It accepts all the inputs such as name, age, and so on, and when finally ready to create the customer, it constructs the customer all at once, completely and correctly. If the final customer is not meant to have things like name or age changes, these properties could be made get-only.
What's important here, is that if you extend customer with a builder as you were doing, you could allow that customer to be changed incorrectly; this is antithetical to DDD. Worse, you've got the confusion between the thing being built and the thing doing the building.
Refinements
Ok, so what if your domain allows a customer to age or their name to change? You don't want unfettered write access to these properties. Consider this example: John Doe is 21 years old. Some piece of calling code sets the first name to Mike and then the age to 30 one year later! Makes no sense. Not only is your entity anemic (no internal logic), the logic is external to your domain and allows for time travel!
Let's instead make your Customer less anemic, and provide sensible rules or policies:
public class Customer
{
public Customer(string firstName, string lastName, int age)
{
...
}
public string FirstName { get; private set; }
public string LastName { get; private set; }
public int Age { get; private set; }
public void AgeByOneYear()
=> Age += 1;
public void ChangeFirstName(string newName, IRenamingPolicy renamingPolicy)
=> FirstName = renamingPolicy.ValidateName(newName);
...
}
Relationship of the Factory/Builder to the Domain
In DDD, factories are part of the domain, but not the domain model itself. At this point you may ask, "Well, wait. This factory has domain logic in it, shouldn't that be in the domain model?"
Good question. The answer is yes, and this will make your domain model less anemic. Another aside: you can have entities in your domain model that don't have much (if any) internal logic without your model being considered anemic. As long as the business/domain logic is in your DDD model, and not in your orchestration, persistence, or other layers, you can skate by the anemic label. This is what I did by externalizing renaming logic in a policy, but effecting the renaming action in the Customer. The RenamingPolicy contains domain logic and is part of your domain.
Final Thoughts
Anemic models (or not) and creational patterns are orthogonal concepts, but I've shown how thinking of them together can lead to a coherent domain model.
Using a Customer entity (even if it was a base class of some kind) is probably not a good idea to use as an MVC view or view model. The needs are different; an entity has behavior in a domain whereas a view model is anemic and expresses properties that are bound to a view for presentation.
If your experience is that .NET domain models are anemic, I'd say that's anecdotal and shouldn't set precedent. For simple apps, that's fine; for rich enterprise apps, you might be looking at a bad design.
A model is anemic if you are using it to just store/carry data and keeping business logic related to it in some other place.
In your example you are inheriting a class purely to create Customer object in a specific way but it's not really protecting any in-variance other than supporting a style of writing code. While I refrain to say something is wrong because there might be a reason behind it, I fail to see a valid one here.
Two main purpose of a language supporting inheritance, in my opinion/understanding are:
Code reuse
Encapsulation - indirect
If you really want to protect how a Customer Object can be instantiated, you could have a static factory method on the Customer class itself. However that doesn't make that model 'rich'.
Difference between 'rich' and 'anemic' is where you decide to keep the business logic - outside of your domain entities (aggregates to be precise but will go with entity for simplicity) or as an operation on domain entities.
If you consider your system as a series of coordinated state changes of entities, you have a choice where you keep the logic of that state change. In rich model you include it as an operation on the entity itself so you have tighter control maintaining the invariant.
I found a "Simple alternate solution" in auto numbered table rows (javafx) for auto-incrementing values
This works well. However, if I sort the column in the table, this is not getting sorted. Any fix for this?
Also, according the solution if I delete a row in the middle and write the table contents to a file, the row number is adjusted in the table view but not in the file. The row will be deleted in the file but the auto-incremented value does not get adjusted. Please help.
If you want a persistent numbering which is attached to the data objects so that the numbers get sorted with the data objects, then you should create a data item which includes the numbering.
For example:
public class IdentifiedPerson {
private IntegerProperty id;
private ObjectProperty<Person> person;
public IdentifiedPerson(int id, Person person) {
this.id = new SimpleIntegerProperty(id);
this.person = new SimpleObjectProperty<>(person);
}
public IntegerProperty idProperty() {
return id;
}
public ObjectProperty<Person> personProperty() {
return person;
}
}
Then your TableView is defined as:
private TableView<IdentifiedPerson> table = new TableView<IdentifiedPerson>();
And you provide cell value factories for each of your table columns to supply the relevant data (either the person id or some person attribute).
So the id/row number essentially becomes part of your object model. If you can modify the Person object directly, then you can stick the id in there rather than having the wrapper class for the person id + person object.
Anyway, I think the above info will help you solve your issues. If not, or if you can't come up with a working example yourself, add some further comments or edit the question and maybe somebody can put an example together for you.
I have been having issues with persisting a generic Collection on Google datastore using Objectify4. E.g.
#Entity
class AnimalInfo
{
#Id
String id;
Collection<Animal> animals;
}
#EntitySubClass
class Cat extends Animal
{
String name;
}
#EntitySubClass
class Dog extends Animal
{
String name;
}
#Entity
class Animal
{
#Id
String id;
}
How can I persist the AnimalInfo class and retrieve it again. I have tried:
objectify.save().entities(animalInfo).now(); but while fetching it back again: objectify.load().type(AnimalInfo.class).id(animalInfo.id).get(); doesnt have the name field corresponding to the extended class Cat or Dog.
This is also probably logical because Animal class doesnt have a field name. But how do I get this to work? A generic interface IAnimal (in place of Animal class) is a better solution design-wise, but that doesnt work with Objectify as it needs concrete types.
Any solution for the above problem??
Thanks in advance.
Shaun
To summarize, it looks like you want a collection of references to polymorphic entities. Do this:
#Entity
class AnimalInfo {
#Id String id;
Collection<Ref<Animal>> animals = new ArrayList<Ref<Animal>>();
}
You need Refs to create the reference to the other entities. You could use Key too, but it will be less convenient. You may also want to look into the #Load annotation.
I am facing an issue when validating object which has more than one relationship to bean of particular type but each of relationship must be validated in a different manner.
Composite class:
public class Composite{
#Valid
private Person insurer;
#Valid
private Person insured;
...(other properties)
private String foo;
}
Person class:
public class Person{
#NotNull(groups={Insurer.class,Insured.class})
private String name;
#NotNull(groups={Insurer.class,Insured.class})
private String surname;
...
#NotNull(groups={Insurer.class})
private String ssn;
}
So we have a single type Person which can represent insurer and insured. The problem is that when validating Composite i want to have insurer property to be validated with Insurer group and insured with Insured. Is there anyway it can be accomplished or i need to wait for https://hibernate.onjira.com/browse/BVAL-208 resolving...
To solve your issue in a standardized way you indeed have to wait for Bean Validation 1.1 which will address BVAL-208 (group translations).
In case your Person class also has a flag or some other criteria you could use to determine whether this person is an insurer or insured you could also use a custom class level constraints. The downside is that you are loosing some of the expressiveness of annotations, since you would have to do all validation yourself in the custom constraint validator implementation.
The other alternative (again you need a way to distinguish between insurer and insured) is to use the Hibernate Validator specific GroupSequenceProvider. This way you can keep your current configuration and you just would return the right group depending on the type of Person.
the title is confusing sorry, if you can think of a better one, please change it.
I have three tables, say, bikes, owners and a relationship table (something like many to many) that defines all owners of a bike, or all bikes of an owner.
So, I want to select All bikes of OwnerId 1
But, my mapping is like so:
BikeOwners references one Bike
BikeOwners References one OWner
How do I write the criterion in nhibernate to do this?
Right now, I am trying:
DetachedCriteria crit = DetachedCriteria.For<Bikes>()
.Add(Expression.Eq("OwnerId", _ownerId));
and it errors out saying there isn't any OwnerId in Bikes table, which I understand..
Hope the question is clear.. If you need any details, please ask!
I know I can get first get a list of all Bike id's from Bike owner table and then use that int array to get all bikes in bikes table - BUT - it is two database access and I am doing it manually, there should be a way to do this in one go, right?
This is my plan b, if all else fails, I'll do this.
Thanks
It really depends on your entities. I have mocked up a sample entity, just adopt it to yours.
public class Bike
{
public int BikeId;
public IList<BikeOwners> BikeOwners;
public string BikeName;
}
public class Owners
{
public int OwnerId;
public IList<BikeOwners> OwnersBikes;
public string OwnerName;
}
public class BikeOwners
{
public int Id;
public Owners owner;
public Bikes bike;
}
Now, you are going to write your nhibernate criteria like this:
DetachedCriteria crit = DetachedCriteria.For<Bikes>()
.CreateCriteria("BikeOwners") //from Bikes class
.CreateCriteria("owner") // from BikeOwners class
.Add(Expression.Eq("OwnerId", _OwnerId)); //from Owners class
obviously, you need to modify it to your entities and names.
Unless there's more column in the BikeOwners table, it shouldn't be represented in the domain model at all. Bike and Owner should be mapped as a many-to-many relationship. Also, I find it unusual that a Bike can have multiple Owners.