Design pattern for workflow - c#

I don't think this is a duplicate but I actually need some one wise to confirm my question.
My pattern is going to be similar too (albeit much more complex) the picture below (where my application starts from top to bottom).
It takes a complex object as part of the constructor and then goes through various processes (saved in different .dlls).
I've not taken on a project like this before and want to get it right - I know design patterns are designed to help and give guidance.
My question, what patterns could work. I am stuck on .NET 2.0. My research suggests sequence pattern.
So, am I limited to only the sequence pattern or does any one have another other suggestion?

I have written similar code, but not just with a single pattern. Initially my approach was to code all in Transaction Script pattern and then refactor. During refactoring I came across follwings;
Template pattern: Decoupled logic to seperate classes which I called an Activity (similar to WF), and these Activity classes behaved similar way and therefore used Template pattern.
Transaction Script pattern: An Activity itself is a Transaction Script and could accept Arguments, has a Fault property, and Results which it will be used, construct, stored during the execution.
Builder pattern: To wire up all the Acitivity classes for the business scenario, I ended up with Builder pattern.

Related

MediatR when and why I should use it? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
It might have been asked before but I cannot find even in the official site why I should use MediatR and what problems it solves?
Is it because I can pass a single object in my constructor rather than a multitude of Interfaces?
Is it a replacement or competitor of ServicesBus etc...
Basically what are the benefit and what problem does it solve
I want to buy into it but its not clear to me why I should use it.
many thanks
Is it because I can pass a single object in my constructor rather than
a multitude of Interfaces?
No.
Is it a replacement or competitor of ServicesBus etc...
No.
Basically what are the benefit and what problem does it solve
Among other things, one of the problem MediatR is trying to solve is DI Constructor Explosion in your MVC controllers
public DashboardController(
ICustomerRepository customerRepository,
IOrderService orderService,
ICustomerHistoryRepository historyRepository,
IOrderRepository orderRepository,
IProductRespoitory productRespoitory,
IRelatedProductsRepository relatedProductsRepository,
ISupportService supportService,
ILog logger
)
This is a highly debated topic and there is no one-size-fits-all solution, take a look at this question
How to avoid Dependency Injection constructor madness?
If you want to hide dependencies behind even more abstractions, then at this point you will want to take a look at all the options, like refactoring, separating concerns a little more, or other techniques.
In all honesty, the example problem and solution given on the MediatR website is a little suspect, however it does have its uses. In short, you need to choose whats right for you and your environment.
Overview of the Mediator Pattern
A mediator is an object that makes decisions on how and when objects interact with each other. It encapsulates the “how” and coordinates execution based on state, the way it’s invoked or the payload you provide to it.
In regards to the spirit of your question, you should really have a look at this site:
Simplifying Development and Separating Concerns with MediatR
MediatR is an open source implementation of the mediator pattern that
doesn’t try to do too much and performs no magic. It allows you to
compose messages, create and listen for events using synchronous or
asynchronous patterns. It helps to reduce coupling and isolate the
concerns of requesting the work to be done and creating the handler
that dispatches the work.
More about Mediator Pattern
Can you in your own opinion describe why would you use it
The mediator pattern helps decoupling your application via communication through a mediator (its a thing) .
Usually a program is made up of a large number of classes. However, as more classes are added to a program, the problem of communication between these classes may become more complex. This makes the program harder to read and maintain. Furthermore, it can become difficult to change the program, since any change may affect code in several other classes.
With the mediator pattern, communication between objects is encapsulated within a mediator object. Objects no longer communicate directly with each other (decoupling), but instead communicate through the mediator. This reduces the dependencies between communicating objects, thereby reducing coupling.
In modern software, the mediator pattern is usually found within many frameworks, however you can create your own, or use one of many that are available.
From here, i think you should probably just do more research, i mean usually you figure out you need these things before you research them, however in this case i think you really need to find some good examples to know whether you want the Mediator Pattern, and even more The MediatR library
Update
wired_in had some great practical comment on this
All MediatR does is service locate a handler for a request. That is
not the mediator pattern. The "mediator" in this instance, does not
describe how two objects communicate, it uses inversion of control
that is already being used in an application and just provides a
useless layer of abstraction that only serves to make an application
harder to reason about as a whole. You already achieve decoupling by
using standard constructor injection with IoC. I don't understand why
people buy into this. Let's create multiple composite roots just so we
don't have to put interfaces in our constructor.
and
The OP is completely justified in questioning the point of MediatR.
The top responses I hear to the question involve explaining the use of
the mediator pattern in general, or that it makes the calling code
cleaner. The former explanation assumes that the MediatR library
actually implements the mediator pattern, which is far from clear. The
latter is not a justifcation for adding another abstraction on top of
an already abstracted IoC container, which creates multiple composite
roots. Just inject the handler instead of service locating it
It is just a way to implement communication between your business logic components.
Imagine that you have:
FirstRequest // which handled by FirstRequestHandler(FirstRequest)
SecondRequest // which handled by SecondRequestHandler(SecondRequest)
ThirdRequest // which handled by ThirdRequestHandler(ThirdRequest)
... there are hundreds of them ...
And then comes ComplexRequest, when ComplexResponse have to be a combination of FirstResponse and ThirdResponse.
How should we solve this?
Well, ComplexRequestHandler would have to inject FirstHandler and ThirdHandler, get their results, and combine them.
But why should ComplexRequestHandler should have access to FirstRequestHandler interface ?
Why we should bother to inject First, Third ... OneHundredAndTwentythHandler into our ComplexHandler ?
What MediatR gives us in such use case, is a third party that tells us:
"Give me a request, and I"ll get you the right response, Trust me!"
So ComplexHandler doesn't know anything about First and Third Handlers.
It knows only about the required requests and responses (which usually are only just wrapping DTOs).
Note: You don't have to necessarily use the MediatR library for that. You can read about the Mediator Pattern and implement one yourself.

Should command info be passed to aggregate using method parameters or by reference?

I'm working on implementing a basic CQRS+ES application. I've seen many examples but I don't understand the routing between the command handler and aggregate.
In some examples, the work is did in this way:
XCommandHandler:
void Handle(XCommand command) {
var aggregate = this.repository.Find<Aggregate>(command.aggId);
aggregate.InvokeSomeBusinessLogic(command.property1, command.property2);
this.repository.Save(aggregate);
}
But others do in another way:
XCommandHandler:
void Handle(XCommand command) {
var aggregate = this.repository.Find<Aggregate>(command.aggId);
aggregate.InvokeSomeBusinessLogic(command);
this.repository.Save(aggregate);
}
What is the best approach, especially when you have many properties (15 or more) in a command?
This isn't particularly a question about CQRS+ES, but just about API design overall. As Clean Code explains, a method with no parameters is better than a method with one parameter, which is better than one with two parameters, etc.
Blindly following that rule should always make you select your second option:
aggregate.InvokeSomeBusinessLogic(command);
However, blindly following any rule is rarely a good idea. In this case, it would be a good idea to consider the Interface Segregation Principle as a countering force:
Clients should not be forced to depend on methods they do not use.
Since getters and setters are methods too, I think this principle applies to Command Objects as well.
Thus, if you have 15 or more properties, but the method in question only needs two of them, perhaps it would be better to just pass those two values.
Another thing entirely is that if you have a Command Object with 15 properties, you may want to rethink your design. One of the fundamental assumptions behind CQRS+ES is that applications present task-based UIs, which ensures that each Command (and the corresponding Events) are 'small'.
Editing in Mark's comments with links because one of the links were broken:
Updating aggregate info isn't task-based; it's CRUD. Perhaps these two articles from Udi Dahan will be helpful.
Queries, Patterns, and Search – food for thought
Tasks, Messages, & Transactions – the holy trinity
I would agree with Mark in principle. I would note however that CQRS has grown from the domain driven design world. They stress the importance of language (ubiquitous language). You can capture the intent and meaningfulness in the actual name of the command object.
On a practical level refactoring methods by adding parameters can become a real pain if called from more than a few places. This can be significantly eased with a single object.
I have a couple of related posts that you may find helpful. Aggregate Root – How to Build One for CQRS and Event Sourcing and 6 Code Smells with your CQRS Events – and How to Avoid Them. While the last one is about events many of the principles apply.
Hope you find them helpful.

Best way to deal with conflated business and presentation code?

Considering a hypothetical situation where an old, legacy presentation library has been maintained over the years, and has gradually had more and more business logic coded into it through a process of hasty corrections and lack of proper architectural oversight. Alternatively, consider a business class or namespace that is not separated from presentation by assembly boundaries, and was thus capable of referencing something like System.Windows.Forms without being forced to add a reference (a much more sobering action than a simple using clause).
In situations like this, it's not unimaginable that the business code used by this UI code will eventually be called upon for reuse. What is a good way to refactor the two layers apart to allow for this?
I'm loosely familiar with design patterns--at least in principle anyway. However, I don't have a whole ton of practical experience so I'm somewhat unsure of my intuitions. I've started along the path of using the Strategy pattern for this. The idea is to identify the places where the business logic calls up to UI components to ask the user a question and gather data, and then to encapsulate those into a set of interfaces. Each method on that interface will contain the UI-oriented code from the original workflow, and the UI class will then implement that interface.
The new code that wants to reuse the business logic in question will also implement this interface, but substitute either new windows or possibly pre-fab or parameterized answers to the questions originally answered by the UI components. This way, the biz logic can be treated as a real library, albeit with a somewhat awkward interface parameter passed to some of its methods.
Is this a decent approach? How better should I go about this? I will defer to your collective internet wisdom.
Thanks!
I humbly suggest Model–View–Controller - MVC has a high probability as a successful solution to your problem. It separates various logic, much as you describe.
HTH
You seem to be taking a good approach, in which you break dependencies between concrete elements in your design to instead depend on abstractions (interfaces). When you break dependencies like this, you should immediately start using unit tests to cover your legacy code base and to evolve the design with improved assurance.
I've found the book Working Effectively with Legacy Code to be invaluable in these situations. Also, don't jump right into the patterns without first looking at the principles of object oriented design, like the SOLID principles. They often guide your choice of patterns and decisions about the evolution of the system.
I would approach it by clearly identifying the entities and the actions they can do or can be done to them. Then one by one try to start creating independent business logic objects for those refactoring the logic out of the UI, making the UI call to the BL objects.
At that point if I understand your scenario correctly you would have a hand full of BL objects, some portion of which made win forms calls, the win forms calls would need to be promoted out into the UI layer.
Then as JustBoo says, I think you'll have a distinct enough situation to start abstracting out controllers from your BL and UI and make it all function in an MVC design.
Okay, given your various comments, I would take Mr. Hoffa's advice and extend it. I'm sure you've heard hard problems should be broken down into ever smaller units of work until they can be "conquered."
Using that technique, coupled with the methodologies of Refactoring could solve your problems. There is a book and lots of information on the web about it. You now have a link. That page has a ton of links to information.
One more link from the author of the book.
So, you refactor, slowly but surely to the creamy goodness of MVC, step-by-step.
HTH

Is this a design pattern?

All over our codebase we have this repeated pattern where there's an interface with one method. Is this a real design pattern? If so what is it and what would the benefits be?
Here are a few examples:
public interface IRunnable
{
void Run();
}
public interface IAction
{
void Perform();
}
public interface ICommand
{
void Execute(ActionArgs _actionargs);
}
I've seen this referenced as the Command pattern.
I first learned about it reading Uncle Bob's Agile Principles, Patterns, and Practices in C#.
I believe its elegance is its simplicity. I've used it when I wrote a file processing service. The service performed all of the administration of reading / deleting files. When a file needed to be processed, it's respective plugin was loaded. Each plugin implemented a Process method, and did whatever was needed to process that type of file. (Mainly, parse the contents and insert into a database.)
Everytime I had to process a new file type with a new layout, all I had to do was create a new Plugin that implemented Process.
This worked for me because I needed a simple solution. If you need to take in more than one parameter, this probably is not the pattern to use.
Any of these could very well be specific cases of the Command Pattern, depending on how it's being used and the context. Part of this would depend on why and how you're setting this up.
The command pattern also normally includes a concept of state and of various objects. Typically, this type of interface would suggest that, so I'm guessing this is what you are thinking of as a design pattern here, but without the caller or multiple targets it's difficult to tell if this is a classic example of it or not...
However, this, in and of itself, is just basic interface abstraction to me, and not something I'd classify as a design pattern.
As It was said it is a Command Design Pattern. But it is ( as for me ) more like Java way of achieving the result. In C# you can use delegates and in the C++ function pointers and functors.
There is no big sense to create more and more classes if you already have some implementation of the reaction in a some Class method. Which you can bind in the C++ or set to delegate in the C#. In Java I suppose you have no choice but to write the code you have found.
I'm not sure whether you could call it a design pattern as the interfaces you provided does not provide solutions to commonly experienced problems but rather solution to very specific problems in the project that you're developing.
The reason you're properly using interfaces is due to the fact that you cannot have all your classes that needs these methods extend a base class that contains these, yet you need to know that specific classes promise to implement these.
Might be, as some of the previous posters suggested: http://en.wikipedia.org/wiki/Command_pattern
You can remove this repetition (or prevent it for future code) by using lambda expressions. Lambda expressions are exactly for this situation.
If anything, then it's a functor. It's used in languages without first class function( pointer)s for the sort of things function( pointer)s are used for, such as the main function for a thread.
There are applications for Interfaces with only one method. I mean, in .NET there are plenty - INotifyPropertyChanged, for one (the PropertyChanged event). It just guarantees that an object has a certain method (regardless of what type of object it actually is), so you can call it (again, regardless of type).
Dim runnableObjects As List(Of Object)
runnableObjects.Add(New MyRunnableObject1)
runnableObjects.Add(New MyRunnableObject2)
For Each o As IRunnable In runnableObjects
o.Run()
Next
Maybe I'm missing something, but the first two look like they could be part of the strategy pattern. Basically, an object has a member of type IAction, and that member is assigned/reassigned at runtime based on the needs of the system to perform a task in a particular way (ie using a particular strategy).

How to implement SOLID principles into an existing project

I apologize for the subjectiveness of this question, but I am a little stuck and I would appreciate some guidance and advice from anyone who's had to deal with this issue before:
I have (what's become) a very large RESTful API project written in C# 2.0 and some of my classes have become monstrous. My main API class is an example of this -- with several dozen members and methods (probably approaching hundreds). As you can imagine, it's becoming a small nightmare, not only to maintain this code but even just navigating the code has become a chore.
I am reasonably new to the SOLID principles, and I am massive fan of design patterns (but I am still at that stage where I can implement them, but not quite enough to know when to use them - in situations where its not so obvious).
I need to break my classes down in size, but I am at a loss of how best to go about doing it. Can my fellow StackOverflow'ers please suggest ways that they have taken existing code monoliths and cut them down to size?
Single Responsibility Principle - A class should have only one reason to change. If you have a monolithic class, then it probably has more than one reason to change. Simply define your one reason to change, and be as granular as reasonable. I would suggest to start "large". Refactor one third of the code out into another class. Once you have that, then start over with your new class. Going straight from one class to 20 is too daunting.
Open/Closed Principle - A class should be open for extension, but closed for change. Where reasonable, mark your members and methods as virtual or abstract. Each item should be relatively small in nature, and give you some base functionality or definition of behavior. However, if you need to change the functionality later, you will be able to add code, rather than change code to introduce new/different functionality.
Liskov Substitution Principle - A class should be substitutable for its base class. The key here, in my opinion, is do to inheritance correctly. If you have a huge case statement, or two pages of if statements that check the derived type of the object, then your violating this principle and need to rethink your approach.
Interface Segregation Principle - In my mind, this principle closely resembles the Single Responsibility principle. It just applies specifically to a high level (or mature) class/interface. One way to use this principle in a large class is to make your class implement an empty interface. Next, change all of the types that use your class to be the type of the interface. This will break your code. However, it will point out exactly how you are consuming your class. If you have three instances that each use their own subset of methods and properties, then you now know that you need three different interfaces. Each interface represents a collective set of functionality, and one reason to change.
Dependency Inversion Principle - The parent / child allegory made me understand this. Think of a parent class. It defines behavior, but isn't concerned with the dirty details. It's dependable. A child class, however, is all about the details, and can't be depended upon because it changes often. You always want to depend upon the parent, responsible classes, and never the other way around. If you have a parent class depending upon a child class, you'll get unexpected behavior when you change something. In my mind, this is the same mindset of SOA. A service contract defines inputs, outputs, and behavior, with no details.
Of course, my opinions and understandings may be incomplete or wrong. I would suggest learning from people who have mastered these principles, like Uncle Bob. A good starting point for me was his book, Agile Principles, Patterns, and Practices in C#. Another good resource was Uncle Bob on Hanselminutes.
Of course, as Joel and Jeff pointed out, these are principles, not rules. They are to be tools to help guide you, not the law of the land.
EDIT:
I just found these SOLID screencasts which look really interesting. Each one is approximately 10-15 minutes long.
There's a classic book by Martin Fowler - Refactoring: Improving the Design of Existing Code.
There he provides a set of design techniques and example of decisions to make your existing codebase more manageable and maintainable (and that what SOLID principals are all about). Even though there are some standard routines in refactoring it is a very custom process and one solution couldn't be applied to all project.
Unit testing is one of the corner pillars for this process to succeed. You do need to cover your existing codebase with enough code coverage so that you'd be sure you don't break stuff while changing it. Actually using modern unit testing framework with mocking support will lead encourage you to better design.
There are tools like ReSharper (my favorite) and CodeRush to assist with tedious code changes. But those are usually trivial mechanical stuff, making design decisions is much more complex process and there's no so much tool support. Using class diagrams and UML helps. That what I would start from, actually. Try to make sense of what is already there and bring some structure to it. Then from there you can make decisions about decomposition and relations between different components and change your code accordingly.
Hope this helps and happy refactoring!
It will be a time consuming process. You need to read the code and identify parts that do not meet the SOLID principles and refactor into new classes. Using a VS add-in like Resharper (http://www.jetbrains.com) will assist with the refactoring process.
Ideally you will have good coverage of automated unit tests so that you can ensure your changes do not introduce problems with the code.
More Information
In the main API class, you need to identify methods that relate to each other and create a class that more specifically represents what actions the method performs.
e.g.
Let's say I had an Address class with separate variables containing street number, name, etc. This class is responsible for inserting, updating, deleting, etc. If I also needed to format an address a specific way for a postal address, I could have a method called GetFormattedPostalAddress() that returned the formatted address.
Alternatively, I could refactor this method into a class called AddressFormatter that takes an Address in it constructor and has a Get property called PostalAddress that returns the formatted address.
The idea is to separate different responsibilities into separate classes.
What I've done when presented with this type of thing (and I'll readily admit that I haven't used SOLID principles before, but from what little I know of them, they sound good) is to look at the existing codebase from a connectivity point of view. Essentially, by looking at the system, you should be able to find some subset of functionality that is internally highly coupled (many frequent interactions) but externally loosely coupled (few infrequent interactions). Usually, there are a few of these pieces in any large codebase; they are candidates for excision. Essentially, once you've identified your candidates, you have to enumerate the points at which they are externally coupled to the system as a whole. This should give you a good idea of the level of interdependency involved. There usually is a fair bit of interdependency involved. Evaluate the subsets and their connection points for refactoring; frequently (but not always) there ends up being a couple of clear structural refactorings that can increase the decoupling. With an eye on those refactorings, use the existing couplings to define the minimal interface required to allow the subsystem to work with the rest of the system. Look for commonalities in those interfaces (frequently, you find more than you'd expect!). And finally, implement these changes that you've identified.
The process sounds terrible, but in practice, it's actually pretty straightforward. Mind you, this is not a roadmap towards getting to a completely perfectly designed system (for that, you'd need to start from scratch), but it very certainly will decrease the complexity of the system as a whole and increase the code comprehensibility.
OOD - Object Oriented Design
SOLID - class design
Single Responsibility Principle - SRP - introduced by Uncle Bob. Method, class, module are responsible only for doing single thing(one single task)
Open/Closed Principle - OCP - introduced by Bertrand Meyer. Method, class, module are open for extension and closed for modification. Use a power of inheritance, abstraction, polymorphism, extension, wrapper. [Java example], [Swift example]
[Liskov Substitution Principle] - LSP - introduced by Barbara Liskov and Jeannette Wing. A subtype can replace supertype without side effects
Interface Segregation Principle - ISP - introduced by Uncle Bob. Your interface should be as small as possible
[Dependency Inversion Principle(DIP)] - DIP - introduced by Uncle Bob. Internal class, layer should not be depended on external class, layer. For example when you have aggregation[About] dependency you should rather use some abstraction/interfaces. [DIP vs DI vs IoC]
6 principles about packages/modules(.jar, .aar, .framework):
what to put inside a package
The Release Reuse Equivalency
The Common Closure
The Common Reuse
couplings between packages
The Acyclic Dependencies
The Stable Dependencies
The Stable Abstractions
[Protocol Oriented Programming(POP)]

Categories