What are disadvantages of Abstract factory design pattern? - c#-4.0

As usual to build the project with different design patterns, architects always prefer the advantageous view of that particular design pattern. But sometimes it need to understand what should be the violation area and disadvantages in terms of future extension of project. I am using Abstract factory design pattern now a days. I understood it but unable to figure out its disadvantages,its limitations, where it will get fail. can somebody please explain me this another view of Abstract Factory design pattern?

First, with any design pattern you are adding more layers of abstraction and complexity, so only apply the pattern when the pain of not having it is apparent. This is a similar idea to Bob Martin's "Take the first bullet" and Nathan Marz' "Suffering-Oriented Programming."
With Abstract Factory in particular, the decision about which factory to use is made at runtime. Typically, this is done in some code dedicated to providing the right factory by conditional branching based on some key piece of information. This means as more factories are created, this central decision point must be modified. That's annoying.
Finally, if there are any changes to any underlying detail of one factory, the interface might need to be modified for all the factories. This breaks clients. So as usual, take great care with the choice of interfaces.

Related

Can I say Axon Commands and Events are considered as anemic models?

My question here is quite straight as mentioned in the subject.
However, please allow me to give some brief explanation here about my innocent thoughts.
I've been using Axon for approximately 10 months now. I used to design my project structure based on the Hexagonal architecture with two top level packages respectively for domain and infrastructure.
Furthermore, domain package will contain different domain objects (as explained in the DDD concept) such as follow:
Aggregate (this will be an Axon aggregate class).
Repository (in my case, this will be a Spring Data Repository interface).
Entity (in my case, this contains any lookup entity that i used for set-based consistency validation as written here).
Service Port (collection of Input and Ouput port interfaces).
Commands (representing Axon Command object).
As for Events, I used to put them on a different module that I compiled as a jar file, so I can share it to other developers whom going to use the same event in their project.
I've noticed recently that all of my commands and events were basically anemic models (an anti pattern that we should avoid).
Is there any good practice on this ? Or, Is it something that intentionally used by design ?
I've been thinking to put my Command classes within my Aggregate class (as an inner classes). At least by using this approach I won't end-up with having so many anemic models scattered outside. Any thoughts ?
Commands are designed to be behavior and input structures mirroring the external world. They don't necessarily mirror an aggregate's structure.
They are not even connected clearly to one single aggregate, at times. Enclosing them within aggregates can be a code smell because you are then thinking in terms of resources and UI organization, instead of transaction boundaries and entity groups.
You are also violating the open-closed principle. Changes in volatile layers like user interface and request structures will make you edit the Aggregate class, and that is not good design.
On a more general note...
At times, this debate of anemic vs. non-anemic (or dry vs. non-dry) can push you in the direction of premature - and incorrect - optimization. Try avoiding this trap because you will end up optimising at the code level, but your domain will suffer.
DDD and CQRS guidelines align with principles that help you keep complexity at bay over the long term. Things kept distinct and separate help you achieve this.
First of all, in DDD, your domain had to be free of any frameworks, just use pure language library.
Then, mixing Commands and Aggregates cannot be a good solution. I think Commands belongs to Port while Aggregates belongs to the Hexagone.
Finally, DDD highlights the discovery of the domain thanks to the experts. Did you do that ? If not, if you're only using the Tacticts pattern, you'll miss one of the most important part of DDD.

DDD domain services: what should a service class contain?

In Domain Driven Design, domain services should contain operations that do not naturally belong inside an entity.
I've had the habit to create one service per entity and group some methods inside it (Organization entity and OrganizationService service).
But the more I think about it: OrganizationService doesn't mean anything, "Organization" is not a service, it's a thing.
So right now I have to add a Organization deep copy functionality that will duplicate a whole Organization aggregate, so I want to put it in a service.
Should I do: OrganizationService::copyOrganization(o)?
Or should I do: OrganizationCopyService::copyOrganization(o)?
More generally: is a "service" an abstract concept containing several operations, or is a service a concrete operation?
Edit: more examples given the first one wasn't that good:
StrategyService::apply()/cancel() or StrategyApplicationService::apply()/cancel()? ("Application" here is not related to the application layer ;)
CarService::wash() or CarWashingService::wash()?
In all these examples the most specific service name seems the most appropriate. After all, in real life, "car washing service" is something that makes sense. But I may end up with a lot of services...
*Note: this is not a question about opinions! This is a precise, answerable question about the Domain Driven Design methodology. I'm always weary of close votes when asking "should I", but there is a DDD way of doing things.*
I think it's good if a domain service has only one method. But I don't think it is a rule like you must not have more than one method on a domain service or something. If the interface abstracts only one thing or one behaviour, it's certainly easy to maitain but the granularity of the domain service totally depends on your bounded context. Sometimes we focus on low coupling too much and neglect high cohesive.
This is a bit opinion based I wanted to add it as a comment but ran out space.
I believe that in this case it will make sense to group the methods into one a separate OrganizationFactory-service with different construction method.
interface OrganizationFactory{
Organization createOrganization();
Organization createOrganizationCopy(Organization organization);
}
I suppose it will be in accordance with information expert pattern and DRY principle - one class has all the information about specific object creation and I don't see any reason to repeat this logic in different places.
Nevertheless, an interesting thing is that in ddd definition of factory pattern
Shift the responsibility for creating instances of complex objects and
AGGREGATES to a separate object, which may itself have no
responsibility in the domain model but is still part of the domain
design. Provide an interface that encapsulates all complex assembly
and that does not require the client to reference the concrete classes
of the objects being instantiated.
the word "object" is in a generic sense doesn't even have to be a separate class but can also be a factory method(I mean both the method of a class and the pattern factory method) - later Evans gives an example of the factory method of Brokerage Account that creates instances of Trade Order.
The book references to the family of GoF factory patterns and I do not think that there's a special DDD way of factory decomposition - the main points are that the object created is not half-baked and that the factory method should add as few dependecies as possible.
update DDD is not attached to any particular programming paradigm, while the question is about object-oriented decomposition, so again I don't think that DDD can provide any special recommendations on the number of methods per object.
Some folks use strange rules of thumb, but I believe that you can just go with High Cohesion principle and put methods with highly related responsibilities together. As this is a DDD question, so I suppose it's about domain services(i.e. not infrastructure services). I suppose that the services should be divided according to their responsibilities in the domain.
update 2 Anyway CarService can do CarService::wash()/ CarService::repaint() / CarService::diagnoseAirConditioningProblems() but it will be strange that CarWashingService will do CarWashingService::diagnoseAirConditioningProblems() it's like in Chomsky's generative grammar - some statements(sentences) in the language make sense, some don't. But if your sentence contains too much subjects(more than say 5-7) it also will be difficult to understand, even if it is valid sentence in language.

What is common practise for designing an initial class diagram for a project?

I am currently taking a course that gives an introduction to project planning. It is mostly about how to draw UML diagrams (blegh), but also has a few other topics.
One part in particular keeps bugging me. In the course they describe a method for going from a set of requirements to an initial class diagram, but everything about the method gives me this feeling that it is most definitely not the way to go. Let me first give an example before proceeding.
Let's consider a system that manages a greenhouse company. The company has multiple greenhouses, and every employee is assigned to his/her own greenhouse. A greenhouse has a location and a type of plant being grown in there. An employee has a name and phone number.
Here's what according to the course's method the class diagram would look like:
To me this looks like a database layout adapted for code. When I go about designing a program, I try to identify major abstractions. Like all the code that interacts with the database or the code that is responsible for the GUI are all different parts of the system. That would be what I consider to be an initial class diagram.
I simply can not imagine that this is a common way to start designing the architecture of a project. The classes look ugly, since if you take a slightly larger example the classes will be flooded with responsibilities. To me they look like data objects that have functionality to them they shouldn't have. It does not give me a clue on how to continue from here and get a general architecture going. Everything about it seems obsolete.
All I want to know if there's someone out there that can tell me if this is a common way to get a first class diagram on paper for reasons I am overlooking.
I would say it's reasonable to start with a logical model that's free of implementation constraints. That logical model is not necessarily concerned with physical implementation details (e.g. whether or not to use a database, what type of database, OS / UI choice, etc.) and thus represents just "real" business domain objects and processes. The similarity to a potential database implementation shouldn't be surprising for the simple example.
By understanding your business domain (through the logical model you've started to construct), you will be better placed to subsequently identify, for example, which architectural patterns are appropriate, what screens you need to build, and database elements to design. Possibly, there will be another part of the course that will aid you in this stage.
In practice, you will often know that you're intending to implement, say, a web-based application using MVC with a back-end database, and may look to model the implementation classes in parallel with your business items. For your course to use a method that emphasises the distinction between logical and physical stages doesn't sound unreasonable.
When I go about designing a program, I try to identify major
abstractions
Same principle in UML as well. You represent abstractions and their relationships and due to existing Visual Tools you can do a presentation of a system to stakeholders or even generate automatically stubs from your design.

Anybody out there having success with the NWorkspace pattern?

I've just begun to delve into my first experiments with Domain Drive Design and I'm taking advantage of the NWorkspace pattern. This pattern seems to make a lot of sense however I haven't been able to find very many examples of places this pattern has been successfully used or even publicly documented. Before I get to far into my implementation I would like to know if anybody has had success using this pattern or whether somebody could point me to any references where NWorkspace has been used in any open source project that I could learn from. Also are there better or more well known alternatives to this pattern that I should know about?
Brief background on NWorkspace
For those who may not be familiar with NWorkspace, it is a pattern introduced by Jimmy Nisson's which abstracts query and persistance responsibilities. In his book Applying Domain-Driven Design and Patterns, Jimmy Nilsson shows how NWorkspace can be used to abstract the infrastructure portions of a DDD Repository as well as provide a mechanism to perform cross Repository atomicity with regard to persistence.
It seems like he's recommending separate interfaces for read and write repositories.
I don't have experience with the pattern described, but I would recommend not having cross-repository transactions. Instead, I would suggest a few solutions popular amongst the DDD community (Eric Evans, Udi Dahan, Greg Young) that have really helped me:
Always use eager loading on your aggregate roots. Then you don't need cross-repository atomicity, and figuring out what's changed when you persist the object is a lot easier.
Use separate classes for writing (i.e. domain classes) and reading (i.e. your viewmodel). Create view model repositories that retrieve viewmodels directly from the database (instead of mapping domain objects to view model classes).
See if implementing the above 2 things simplifies your design.

DDD what all terms mean for Joe the plumber who can't afford to read books few times?

I am on a tight schedule with my project so don't have time to read books to understand it.
Just like anything else we can put it in few lines after reading books for few times. So here i need some description about each terms in DDD practices guideline so I can apply them bit at a piece to my project.
I already know terms in general but can't put it in terms with C# Project.
Below are the terms i have so far known out of reading some brief description in relation with C# project. Like What is the purpose of it in C# project.
Services
Factories
Repository
Aggregates
DomainObjects
Infrastructure
I am really confused about Infrastructure, Repository and Services
When to use Services and when to use Repository?
Please let me know if anyway i can make this question more clear
I recommend that you read through the Domain-Driven Design Quickly book from infoq, it is short, free in pdf form that you can download right away and does its' best to summarize the concepts presented in Eric Evan's Blue Bible
You didn't specify which language/framework the project you are currently working on is in, if it is a .NET project then take a look at the source code for CodeCampServer for a good example.
There is also a fairly more complicated example named Fohjin.DDD that you can look at (it has a focus on CQRS concepts that may be more than you are looking for)
Steve Bohlen has also given a presentation to an alt.net crowd on DDD, you can find the videos from links off of his blog post
I've just posted a blog post which lists these and some other resources as well.
Hopefully some of these resources will help you get started quickly.
This is my understanding and I did NOT read any DDD book, even the holy bible of it.
Services - stateless classes that usually operate on different layer objects, thus helping to decouple them; also to avoid code duplication
Factories - classes that knows how to create objects, thus decouple invoking code from knowing implementation details, making it easier to switch implementations; many factories also help to auto-resolve object dependencies (IoC containers); factories are infrastructure
Repository - interfaces (and corresponding implementations) that narrows data access to the bare minimum that clients should know about
Aggregates - classes that unifies access to several related entities via single interfaces (e.g. order and line items)
Domain Objects - classes that operate purely on domain/business logic, and do not care about persistence, presentation, or other concerns
Infrastructure - classes/layers that glue different objects or layers together; contains the actual implementation details that are not important to real application/user at all (e.g. how data is written to database, how HTTP form is mapped to view models).
Repository provides access to a very specific, usually single, kind of domain object. They emulate collection of objects, to some extent. Services usually operate on very different types of objects, usually accessed via static methods (do not have state), and can perform any operation (e.g. send email, prepare report), while repositories concentrate on CRUD methods.
DDD what all terms mean for Joe the plumber who can’t afford to read books few times?
I would say - not much. Not enough for sure.
I think you're being quite ambitious in trying to apply a new technique to a project that's under such tight deadlines that you can't take the time to study the technique in detail.
At a high level DDD is about decomposing your solution into layers and allocating responsibilities cleanly. If you attempt just to do that in your application you're likely to get some benefit. Later, when you have more time to study, you may discover that you didn't quite follow all the details of the DDD approach - I don't see that as a problem, you proabably already got some benefit of thoughtful structure even if you deviated from some of the DDD guidance.
To specifically answer your question in detail would just mean reiterating material that's already out there: Seems to me that this document nicely summarises the terms you're asking about.
They say about Services:
Some concepts from the domain aren’t
natural to model as objects. Forcing
the required domain functionality to
be the responsibility of an ENTITY or
VALUE either distorts the definition
of a model-based object or adds
meaningless artificial objects.
Therefore: When a significant process
or transformation in the domain is not
a natural responsibility of an ENTITY
or VALUE OBJECT, add an operation to
the model as a standalone interface
declared as a SERVICE.
Now the thing about this kind of wisdom is that to apply it you need to be able to spot when you are "distorting the definition". And I suspect that only with experience (or guidance from someone who is experienced) do you gain the insight to spot such things.
You must expect to experiment with ideas, get it a bit wrong sometimes, then reflect on why your decisions hurt or work. Your goal should not be to do DDD for its own sake, but to produce good software. When you find it cumbersome to implement something, or difficult to maintain something think about why this is, then examine what you did in the light of DDD advice. At that point you may say "Oh, if I had made that a Service, the Model would be so nmuch cleaner", or whatever.
You may find it helpful to read an example.:

Resources