Im thinking about the design of entity baseclasses for a larger application and would like some opinions. Primarily if what specified is the way it has to be done or if there are a cleaner way.
In the solution i have some baseclass variants which all entities will inherit. The relations can be specified as below:
EntityBase//the primary baseclass containing name and id + other stuff
NestedEntityBase:EntityBase //(if class will be able to contain lists of itself)
VersionedEntityBase:EntityBase //(Some parameters specific for versioned entities)
VersionNestedEntityBase:NestedEntityBase// (versioned AND nested)
CurrentStateEntityBase:VersionedEntityBase// (the currentstate objects)
VersionStateEntityBase:VersionedEntityBase// (old objects, saved when surrentstate objects change)
CurrentStateNestedEntityBase:VersionNestedEntityBase// (the currentstate objects)
VersionStateNestedEntityBase:VersionNestedEntityBase //(old objects, saved when surrentstate objects change)
This unfortunately creates some code duplication since multiple inheritance isnt possible.
It will also set the divisions for the generic services and generic controller baseclasses.
Is this how it must be handled or am i missing some clever way of doing this more effectively?
How about Decorator design pattern: http://en.wikipedia.org/wiki/Decorator_pattern
It allows to extend class hierarchy with some new behaviour without duplicating
this whole hierarchy every time. Also it adds benefit of extending behaviour in
runtime (not only at compile time).
Related
My CQRS application has some complex domain objects. When they are created, all properties of the entity are directly specified by the user, so the
CreateFooCommand has about 15 properties.
FooCreatedEvent thus also has 15 properties, because I need all entity properties on the read-side.
As the command parameters must be dispatched to the domain object and FooCreatedCommand should not be passed to the domain,
there is a manual mapping from CreateFooCommand to the domain.
As the domain should create the domain event,
That is another mapping from the domain Foo properties to FooCreatedEvent.
On the read side, I use a DTO to represent the structure of Foo as it is stored within my read-model.
So the event handler updating read-side introduces another mapping from event parameters to DTO.
To implement a simple business case, we have
Two redundant classes
Three mappings of basically the same properties
I thought about getting rid of command/event arguments and push the DTO object around, but that would imply that the domain can receive or create a DTO and assign it to the event.
Sequence:
REST Controller --Command+DTO--> Command Handler --DTO--> Domain --(Event+DTO)--> Event Handler
Any ideas about making CQRS less implementation pain?
I see the following options:
Create a immutable DTO class FooDetails that is used by both CreateFooCommand and FooCreatedEvent by injecting it in the constructor; type hint the aggregate method against FooDetails; for example new CreateFooCommand(new FooDetails(prop1, prop2, ...))
Create a immutable base class FooDetails that is inherited by both the CreateFooCommand and FooCreatedEvent and type hint the aggregate method against FooDetails
Completely change style and use the style promoted by cqrs.nu in which commands are sent directly to the aggregates; the aggregates have command methods like FooAggregate::handle(CreateFooCommand command); I personally use this style a lot.
With CQRS + ES you opted for a more complex approach with more moving parts, knowing that it would allow you to achieve more. Live with it. The strength of this approach implies separating concerns. A Command is a command, an Event is an event, etc. Although many of them may look similar along the chain, there might be exceptions. Some may contain additional data, or slightly different aspects of the same data. A Command can have meta information about the applicative context (who initiated the command, when, is it a retry, etc.) that doesn't concern the Domain. Read models will often include information about related objects to be displayed in addition to their own info (think parent-child relationship).
There's only so much of the seemingly similar code you can cut off before you block yourself from modelling these exceptions. And introducing inheritance or composition between these data structures is often more complex than the original pain of having to write boilerplate mapping code.
I have a situation whereby a predecessor has created a class that is designed to handle the creation of Note entities that are added to the database to journal actions that are carried out by the system across the site.
At present, this class has been broken down into several CreateXYZNote methods that take an enum denoting a specific note type, and an instance of the model that drives that area of the site.
My problem is, there are so many types of notes, each used only in one or two places across the system. Each of the methods is huge, consisting of a small amount of common code, and specifics (e.g. the textual content of the note) are held within a series of switch statements based on an enum. Extremely hard to find the code relating to specific notes, and very hard to maintain at present, and it's only going to grow as new types of notes find their way into the system over time.
Has anyone got any advice or patterns that could help with this sort of situation?
The simplest solution I can think of is that I have a set of profiles held outside of this class as a dictionary (keyed by the enum values) that define the title, description, categories etc. for the notes, and this class then becomes just a means of looking up those values and creating the note, but it just feels like I'm moving the problem to another place rather than resolving it.
You could use a NoteFactory that has a INote Create(NoteType type) method. The factory could depend on a Dictionary keyed by NoteType that the factory uses to find and return the appropriate Note. This way you avoid a non-OCP switch statement.
The factory can be injected with the dictionary, using an IoC container helps here, or you can create the dictionary in the constructor.
I have a database that contains "widgets", let's say. Widgets have properties like Length and Width, for example. The original lower-level API for creating wdigets is a mess, so I'm writing a higher-level set of functions to make things easier for callers. The database is strange, and I don't have good control over the timing of the creation of a widget object. Specifically, it can't be created until the later stages of processing, after certain other things have happened first. But I'd like my callers to think that a widget object has been created at an earlier stage, so that they can get/set its properties from the outset.
So, I implemented a "ProxyWidget" object that my callers can play with. It has private fields like private_Length and private_Width that can store the desired values. Then, it also has public properties Length and Width, that my callers can access. If the caller tells me to set the value of the Width property, the logic is:
If the corresponding widget object already exists in the database, then set
its Width property
If not, store the given width value in the private_Width field for later use.
At some later stage, when I'm sure that the widget object has been created in the database, I copy all the values: copy from private_Width to the database Width field, and so on (one field/property at a time, unfortunately).
This works OK for one type of widget. But I have about 50 types, each with about 20 different fields/properties, and this leads to an unmaintainable mess. I'm wondering if there is a smarter approach. Perhaps I could use reflection to create the "proxy" objects and copy field/property data in a generic way, rather than writing reams of repetitive code? Factor out common code somehow? Can I learn anything from "data binding" patterns? I'm a mathematician, not a programmer, and I have an uneasy feeling that my current approach is just plain dumb. My code is in C#.
First, in my experience, manually coding a data access layer can feel like a lot of repetitive work (putting an ORM in place, such as NHibernate or Entity Framework, might somewhat alleviate this issue), and updating a legacy data access layer is awful work, especially when it consists of many parts.
Some things are unclear in your question, but I suppose it is still possible to give a high-level answer. These are meant to give you some ideas:
You can build ProxyWidget either as an alternative implementation for Widget (or whatever the widget class from the existing low-level API is called), or you can implement it "on top of", or as a "wrapper around", Widget. This is the Adapter design pattern.
public sealed class ExistingTerribleWidget { … }
public sealed class ShinyWidget // this is the wrapper that sits on top of the above
{
public ShinyWidget(ExistingTerribleWidget underlying) { … }
private ExistingTerribleWidget underlying;
… // perform all real work by delegating to `underlying` as appropriate
}
I would recommend that (at least while there is still code using the existing low-level API) you use this pattern instead of creating a completely separate Widget implementation, because if ever there is a database schema change, you will have to update two different APIs. If you build your new EasyWidget class as a wrapper on top of the existing API, it could remain unchanged and only the underlying implementation would have to be updated.
You describe ProxyWidget having two functions (1) Allow modifications to an already persisted widget; and (2) Buffer for a new widget, which will be added to the database later.
You could perhaps simplify your design if you have one common base type and two sub-classes: One for new widgets that haven't been persisted yet, and one for already persisted widgets. The latter subtype possibly has an additional database ID property so that the existing widget can be identified, loaded, modified, and updated in the database:
interface IWidget { /* define all the properties required for a widget */ }
interface IWidgetTemplate : IWidget
{
IPersistedWidget Create();
bool TryLoadFrom(IWidgetRepository repository, out IPersistedWidget matching);
}
interface IPersistedWidget : IWidget
{
Guid Id { get; }
void SaveChanges();
}
This is one example for the Builder design pattern.
If you need to write similar code for many classes (for example, your 50+ database object types) you could consider using T4 text templates. This just makes writing code less repetitive; but you will still have to define your 50+ objects somewhere.
I am working on a project where I am wrestling with trying to move from one persistence pattern to another.
I've looked in Patterns of Enterprise Application Architecture, Design Patterns, and here at this MSDN article for help. Our current pattern is the Active Record pattern described in the MSDN article. As a first step in moving to a more modular code base we are trying to break out some of our business objects (aka tables) into multiple interfaces.
So for example, let's say I have a store application something like this:
public interface IContactInfo
{
...
}
public interface IBillingContactInfo: IContactInfo
{
...
}
public interface IShippingContactInfo: IContactInfo
{
...
}
public class Customer: IBillingContactInfo, IShippingContactInfo
{
#region IBillingContactInfo Implementation
...
#endregion
#region IShippingContactInfo Implementation
...
#endregion
public void Load(int customerID);
public void Save();
}
The Customer class represents a row in our Customer Table. Even though the Customer class is one row it actually implements two different interfaces: IBillingContactInfo, IShippingContactInfo.
Historically we didn't have those two interfaces we simply passed around the entire Customer object everywhere and made whatever changes we wanted to it and then saved it.
Here is where the problem comes in. Now that we have those two interfaces we may have a control that takes an IContactInfo, displays it to the user, and allows the user to correct it if it is wrong. Currently our IContactInfo interface doesn't implement any Save() to allow changes to it to persist.
Any suggestions on good design patterns to get around this limitation without a complete switch to other well known solutions? I don't really want to go through and add a Save() method to all my interfaces but it may be what I end up needing to do.
How many different derivatives of IContactInfo do you plan to have?
Maybe I'm missing the point, but I think you would do better with a class called ContactInfo with a BillTo and a ShipTo instance in each Customer. Since your IShippingContactInfo and IBillingContactInfo interfaces inherit from the same IContactInfo interface, your Customer class will satisfy both IContactInfo base interfaces with one set of fields. That would be a problem.
It's better to make those separate instances. Then, saving your Customer is much more straight-forward.
Are you planning on serialization for persistence or saving to a database or something else?
Using a concrete type for Customer and ContactInfo would definitely cover the first two.
(A flat file would work for your original setup, but I hope you aren't planning on that.)
I think it all comes down to how many derivatives of IContactInfo you expect to have. There is nothing wrong with a bit more topography in your graph. If that means one record with multiple portions (your example), or if that is a one-to-many relationship (my example), or if it is a many-to-many that lists the type (ShipTo, BillTo, etc.) in the join table. The many-to-many definitely reduces the relationships between Customer and the various ContactInfo types, but it creates overhead in application development for the scenarios when you want concrete relationships.
You can easily add a Save() method constraint to the inherited interfaces by simply having IContactInfo implement an IPersistable interface, which mandates the Save() method. So then anything that has IContactInfo also has IPersistable, and therefore must have Save(). You can also do this with ILoadable and Load(int ID) - or, with more semantic correctness, IRetrievable and Retrieve(int ID).
This completely depends on how you're using your ContactInfo objects though. If this doesn't make sense with relation to your usage please leave a comment/update your question and I'll revisit my answer.
If my domain object should contain string properties in 2 languages, should I create 2 separate properties or create a new type BiLingualString?
For example in plant classification application, the plant domain object can contain Plant.LatName and Plant.EngName.
The number of bi-lingual properties for the whole domain is not big, about 6-8, I need only to support two languages, information should be presented to UI in both languages at the same time. (so this is not locallization). The requirements will not change during development.
It may look like an easy question, but this decision will have impact on validation, persistance, object cloning and many other things.
Negative sides I can think of using new dualString type:
Validation: If i'm going to use DataAnattations, Enterprise Library validation block, Flued validation this will require more work, object graph validation is harder than simple property validation.
Persistance: iether NH or EF will require more work with complex properties.
OOP: more complex object initialization, I will have to initialize this new Type in constructor before I can use it.
Architecture: converting objects for passing them between layers is harder, auto mapping tools will require more hand work.
While reading your question I was thinking about why not localization all the time but when I read information should be presented to UI in both languages at the same time. I think it makes sense to use properties.
In this case I would go for a class with one string for each languages as you have mentioned BiLingualString
public class Names
{
public string EngName {get;set;}
public string LatName {get;set;}
}
Then I would use this class in my main Plant Class like this
public class Plant: Names
{
}
If you 100% sure that it will always be only Latin and English I would just stick with simplest solution - 2 string properties. It also more flexible in UI then having BiLingualString. And you won't have to deal with Complex types when persisting.
To help decide, I suggest considering how consistent this behavior will be at all layers. If you expose these as two separate properties on the business object, I would also expect to see it stored as two separate columns in a database record, for example, rather than two translations for the same property stored in a separate table. It does seem odd to store translations this way, but your justifications sound reasonable, and 6 properties is not un-managable. But be sure that you don't intend to add more languages in the future.
If you expect this system to by somewhat dynamic in that you may need to add another language at some point, it would seem to make more sense to me to implement this differently so that you don't have to alter the schema when a new language needs to be supported.
I guess the thing to balance is this: consider the likelihood of having to adjust the languages or properties to accommodate a new language against the advantage (simplicity) you gain by exposing these directly as separate properties rather than having to load translations as a separate level.