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 7 years ago.
Improve this question
I am working on an C# MVC application. I have a scenario where I want to know which design patter will be best fit for it.
The scenario is:
I have to perform some sequence of steps for an entity. Like:
Step-1 Entity Created
Step-2 Entity Approved
Step-3 Entity Assigned to someone
Step-4 Entity Publish
..
....
These steps are configured means at any point of time admin can switch on/off some non-mandatory steps. Like:
If admin switched off step-2 then after step-1 I need to move directly on step-3.
Can anyone please help me to identify the design pattern for the above mentioned scenario.
Thanks
The first design pattern that comes to my mind is State. You can make each state have a GetNextState() (or similar) method which does the necessary checking and returns the corresponding following state.
That's a workflow in my opinion. Microsoft has a Workflow Engine: https://code.msdn.microsoft.com/Windows-Workflow-deed2cd5
With a workflow you can create Step1, Step2, Step3, as workflow actions and steps can be disabled and reenabled etc.
You also get a neat xaml based Workflow Designer. There is example code on the link I posted.
Maybe you can try Template Method Pattern with some state parameters.
abstract class AbsFoo {
public abstract void Step1();
public abstract void Step2();
public abstract void Step3();
public abstract void Step4();
public void process(bool doStep1,
bool doStep2,
bool doStep3,
bool doStep4) {
if (doStep1) Step1();
if (doStep2) Step2();
if (doStep3) Step3();
if (doStep4) Step4();
}
}
class ConcreteFoo : AbsFoo {
public override void Step1() {
Console.WriteLine("Do something in step 1.");
}
public override void Step2()
{
Console.WriteLine("Do something in step 2.");
}
public override void Step3()
{
Console.WriteLine("Do something in step 3.");
}
public override void Step4()
{
Console.WriteLine("Do something in step 4.");
}
}
Then in client class, you can call the method in base class.
class Client {
static void Main() {
AbsFoo foo = new ConcreteFoo();
foo.process(true, false, true, true);
Console.ReadKey();
}
}
However, if the states become more and more, you may consider combine State Pattern with this.
Hopefully I understand your question correctly;
Event-Driven programming may be of interest to you; https://msdn.microsoft.com/en-us/library/awbftdfh.aspx
You can design your 'step' code as modules, allow flags to be turned on and off from a 'control center' and raise events according to what steps needed to be taken.
This also leaves room to multi-thread steps (if you choose to develop modules, and can guarantee that they are orthogonal).
I would suggest you to use template method design pattern for this situation.
It ensures the execution order, provide the ability to switch off one or more steps.
Reference: http://www.dofactory.com/net/template-method-design-pattern
Sounds like a state machine type situation to me where steps are your state objects, and where each state may have multiple exit transitions based on conditions (such as options currently on). The State will then stand in for the C in MVC.
A discussion of the pattern can be found here with a focus on game programming with other examples available.
A state pattern will essentially will allow you you create a graph and, more importantly, allow each edge of the graph to be assigned behavior with will cause the edge to be followed.
so in your case the graph could be defined in this made up scheme I just came up with as:
[state] => [transition-to] (condition)
1 => 3 (if opt_go_to_3 == true)
1 => 2
2 => 3
2 => 5 (if some_other_optioon == true)
2 => 3
... (etc)
Now your code is nicely objectified but still pretty flexible. When it comes to the behavior you need to run based on condition.
Now if use this state object as the controller in your MVC scheme it actually all fits together pretty nice.
Your state machine's current state can create the new views on enter based on some model data.
Speaking about that model data, its not a great idea to hard code that into the state machine infrastructure as it makes everything pretty clunky pretty fast.
Instead think of using a blackboard-ing or message boarding type interface. This idea says that every state should have an interface to write a message to an object.
This can be done using delegates in C#, passing an object to every state when its created, or any other pattern that will give all states in the machine access to this "global" resource.
The idea of the board is that a states may post data to it, for example the results of some computation or the value of some user input. Then later another state running might choose to read a message for a useful value.
Related
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 1 year ago.
Improve this question
i have problem about design a module of my project.
Lets say, you have two classes which both of them almost doing the same thing. You can think like DeviceManager.
Both of them connect/disconnect/parse exactly the same way. After parse the message from device they need to do different things like one of them print a message, the other one pass it to somewhere else.
I need to design this structure best as oop allows maybe with inheritance,interface,abstract etc. but i am not sure what is the best way to approach this problem.
Note: I dont want to violate any SOLID principle.
Thanks.
Example:
// lines exactly same code
** line different code
class DeviceMessageNavigator
{
//connect
//wait message
//parse message
**//NAVIGATE MESSAGE(Pass it to somewhere else)**
//disconnect
}
class DeviceMessagePrinter
{
//connect
//wait message
//parse message
**//PRINT MESSAGE**
//disconnect
}
Your own answer is pretty pseudo code'ish, but goes into the right direction.
Please post compilable code, it's easier to copy/paste and editable. Therfore easier to help you.
public abstract class DeviceMessageBase
{
public void Connect()
{
// do connect things
}
public void WaitMessage()
{
// do wait message things
}
public void ParseMessage()
{
// do parse message things
}
public abstract void ProcessMessage();
}
public class DeviceMessageNavigator : DeviceMessageBase
{
public override void ProcessMessage()
{
//**//NAVIGATE MESSAGE(Pass it to somewhere else)**
}
}
public class DeviceMessagePrinter : DeviceMessageBase
{
public override void ProcessMessage()
{
//**//PRINT MESSAGE**
}
}
You have a couple of options actually:
You could create an abstract class with the points in common between the two and then extend it adding the methods you need.
You could write the first and then extend it to the second adding what you need
You could write a DeviceManager class with a print method and a navigate method (if they really do the same things apart from one this might be your answer)
I think that your view on OOP might not be the proper one, you might want to look more in detail about it. For example it looks to me that you are looking at those classes more like functions: every instruction you commented inside should be a method on it's own. See classes like blueprints of an actual real life object: you can build the object and use it as blueprints intended or you change them to have a different object with different properties and functions.
Let's take a car's blueprint, it has some properties like the car's shape, number of doors, etc.. and it has some functions you can use when interacting with it like turning it on, changing radio's volume, accellerating, etc... Following this example your question would be: i need two identical toyota yaris blueprints, one has an incorporated coffee machine and the other has wifi, how can i design them? And the answer would be: take the blueprints for a toyota yaris, make a copy and then add the coffee machine in one and the wifi router in the other.
From Olivier's answer i drafted this one, i am not sure this is the best approach.
abstract class DeviceMessage
{
protected string message;
//connect
//wait message
//parse message
message=recievedMessage;
abstract void ProcessMessage();
//disconnect
}
class DeviceMessageNavigator:DeviceMessage
{
//connect
//wait message
//parse message
**//NAVIGATE MESSAGE(Pass it to somewhere else)**
//disconnect
}
class DeviceMessagePrinter:DeviceMessage
{
//connect
//wait message
//parse message
**//PRINT MESSAGE**
//disconnect
}
In a aspnetcore mvc executing context .
I have this simple entity.
public class Foo
{
public int Id { get; private set; }
public string Name{ get; private set; }
public string Code { get; private set; }
private Foo() { }
public Foo(string Name, string Code)
{
GuardClauses.IsNullOrWhiteSpace(Name,nameof(Name), "cannot be null or empty");
GuardClauses.IsNullOrWhiteSpace(Code, nameof(Code), "cannot be null or empty");
this.Nom = Nom;
this.Code = Code;
}
}
In my DbContext I have this code field/constraint that ensures the Code is unique from a persistence point of view.
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Foo>()
.HasIndex(u => u.Code)
.IsUnique();
}
I want the addNewFoo method in my service class to ensure that for all Foos in my Application the property code is unique, before adding it.
I try as much as I can to respect persistence ignorance principle, but I'm not as skilled as I wish to do that.
For starters, is it the role of a Builder to determine if the Code field is Unique?
Secondly I know that in my validation layer I can determine if there is an existing foo already with the same Code that the actual foo I'm currently trying to add. But this approchah isn't thread safe or transactional.
The fact is I don't want to wait the moment I add my foo too have a SqlException, just to know it cannot be done.
What is the best approach to ensure unicity in my application with the
Fail Fast principle in mind.
Because there is't a concrete example or description of a system I will generalize a bit. If you provide a concrete example I can add additional info. Every solution has a Context to which it applies to best and of course there is always a trade-off
Let's ask couple of querstions regarding the nature of this Code and what it represents
Who is responcible for the Code generation: the User of the system or the System itself?
Can the Code be completely random (UUID for example)?
Is the code generated by some special algorithm (SSN or maybe a CarPartNumber that is composed of different parts with a special meaning)
And one more very important question:
How frequently do we expect these unique violations to occur?
If the answer to question 2 is Yes, then you don't have a problem. You can have a duplicate UUID's, but the chances are very low. You can add a Unique Constrant to you DB just in case and treat this violation as a normal error that you don't care about since it's gonna happen every once in a million years.
If the answer to question 3 is Yes, then we have a different sittuation. In a multi-user system you cannot avoid concurrency. There are couple of way to deal with the sittuation:
Option 1: Optimistic Offline Lock
Option 2: Pessimistic Offline Lock
Option 3: If System is generating codes, have a special service and queue code generation requests.
If you choose to use a lock, you can either lock the whole resource Foo or only lock the Code generation.
Option 1:
You will have to handle the SQLException. This one is used in most applications today because it ensures smooth User Experience by not causing the application to stall for large amounts of time because someone has locked a resource.
You can use an abstraction for example a Repository. Define your own application level exception UniqueCodeViolationException that will be thrown by the Repository. The repository will try{}catch{} the SQLException, process it and wrap it in UniqueCodeViolationException when is compares the error codes. This won't save you the check but at least if will hide the concrete errors and you will have the processing in only one place.
Option2:
Sometimes you realy need to ensure that there is no concurrency, so you use this option. In this case you will have to lock the process of creation of Foo for only one user and don't allow other to be able to even be able to open the dialog/form/page for creating Foo if there is a lock.
This ensures consistency and avoids the problem by creating a system that is basically unusable for multiple users that target the same Foo. It's quite possible that the application you are building will have only one person responsible for Foo creation or it may that concurrency is very low, so this may be a good solution.
I have friends who use this lock in an application for Insurances. Usually in their application one person is going to one office to make an Insurance. so the possibility of concurrency in the creation of an insurance for the same person is very low, but the cost of having multiple Insurances to the same person is very hight.
Option 3:
On the other hand If your Code is generated by the System, you can have a CodeGenerationService that deals with code generations and ensures that unique codes are generated. You can have a queue with these requests. In each generation operation in the Service you can check if this code exists and return an Error (or throw exception).
Now to question 4. If you don't expect to have collisions often, just add a Unique Constraint in your DB and treat it as a general unexpected error. Add the check if the Code already exists and show an error if it does.
You still can have a concurrency here so there will be a slim change that one user will add a Foo and another will get an error "Oooops... something whent wrong.. please try again". Since this will happen once in a 100 years it's ok.
The last solution will make your system a lot simpler by ignoring special situations that can occur in rare situations.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Many times I have seen inside Main method of the program, independently of programming language, the following pattern but I don't know how is called and why is used like this. What can I achieve buy using something like the following inside Main? There are any alternatives/variations?
class Program
{
static void Main(string[] args)
{
new Program().Run();
}
private void Run()
{
var rep = new Repository();
dynamic data = rep.GetPerson();
Console.WriteLine(data.Name);
dynamic data2 = rep.GetPersonWrappedInAnonymousType();
Console.WriteLine(data2.Person.Name);
}
}
Thanks in advance.
Edit
Also if you see something in many parts, yes it is a pattern. This is the definition of a pattern!
Making the Program class able to be instantiated (instead of making everything static) allows to have multiple "programs" running at the same time or one after the other. This is useful for testing purposes.
Probably, there are instance fields in this class. By using a fresh instance each time each test run is isolated from the other ones.
Now, if there is no instance state this is a useless thing to do.
If this is a pattern at all, it might be something around responsibility separation. You could pack it into one method:
class Program
{
static void Main(string[] args)
{
var rep = new Repository();
dynamic data = rep.GetPerson();
Console.WriteLine(data.Name);
dynamic data2 = rep.GetPersonWrappedInAnonymousType();
Console.WriteLine(data2.Person.Name);
}
}
but the person that wrote it wanted to separate the "start" of the program (standard "main" entry point) with the actual task(s) that is to be performed (get person, getpersonwrapped..).
Instantiating and object of "Program" class is IMHO for purists. It's highly uncommon to actually have multiple instances of these objects in a single project. However, Java/C# fans that often claim that in OOP "everything is an object" and despise everything what's static and not bound to objects. The static void main is a great pain for them, and so they quickly de-static-ize the Program class in this way. I didn't want to judgde that, but I agree with HansPassant's comment - looks cargo-cultish. But for me, that's no difference and just a tiny cosmetical change, and as I said, especially for the Program class it is mostly irrelevant. But I wouldn't call that a "design pattern". A "code style", or "implementation pattern", but not "design". There's really no architecture and no algorithm in creating and running a "run" method.
If you add more bits to that, some common interface that defines the Run(), some choosing-the-right-program implementation at runtime, then maybe you could get into, I dont know, maybe design pattern called "policy" or "strategy".. but that's mostly exaggerated
Unfortunately no one was willing to answer my question so i have to accept my own answer. However i do believe there are people who can give a more experience based answer on this. So the answer is yes this is a pattern! Is called The command pattern.
From Wikipedia Article :
In object-oriented programming, the command pattern is a behavioral design pattern in which an object is used to represent and encapsulate all the information needed to call a method at a later time. This information includes the method name, the object that owns the method and values for the method parameters.
Four terms always associated with the command pattern are command, receiver, invoker and client. A command object has a receiver object and invokes a method of the receiver in a way that is specific to that receiver's class. The receiver then does the work. A command object is separately passed to an invoker object, which invokes the command, and optionally does bookkeeping about the command execution. Any command object can be passed to the same invoker object. Both an invoker object and several command objects are held by a client object. The client contains the decision making about which commands to execute at which points. To execute a command, it passes the command object to the invoker object.
Using command objects makes it easier to construct general components that need to delegate, sequence or execute method calls at a time of their choosing without the need to know the class of the method or the method parameters. Using an invoker object allows bookkeeping about command executions to be conveniently performed, as well as implementing different modes for commands, which are managed by the invoker object, without the need for the client to be aware of the existence of bookkeeping or modes.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Sometimes I have to write big code in a class, so what I do is something like this,
Class ABC //it's a web service class
{
Public void Method-1() //used "-" for easy to read
{
//DoSomething and get something from database
Method-2(pass parameters that i got from database);
}
Public void Method-2(parameters)
{
DoSomething again and get data from another database. and some other source
do some processing by calling web services (just as example)
Method-3(parameter);
}
Public void Method-3(parameters)
{
DoSomething again and get data from another database. and some other source
do some processing by calling web services (just as example)
Method-4(parameter);
}
// and it keeps going
}
Another way
Class ABC //it's a web service class
{
Public void Method-1() //used "-" for easy to read
{
Method-2();
Method-3();
Method-4();
// so on....
}
}
Is this the right way of doing it and if not then what would be best way of doing it ?
Edit
#Sayse I am trying to get information from different sources and trying to build a big XML file which made me get use 4, 5 foreach loops to get data from sql etc.. so using nested methods
Both ways are good in different cases. If you have single functionalities, you should keep them separate. Second approach - calling method from method should be used when one method is part of 'outer' functionality.
Examples:
repairVehicles() {
repairCar();
repairBike();
repairTrain();
}
... but:
repairCar() {
...
repairEngine();
...
}
repairEngine() {
...
takeEngineOut();
....
}
takeEngineOut() {
...
unscrewBolts();
...
}
There cannot be a straight forward answer to your question.
First of all you should note that one method should perform one functionality. If it is true, then you can call it either way depending on your requirement.
Example:
If you have a base method takes a mathematical expression as input. And that expression contains Add, Subtract, Multiply and divide then you will call it the first way.
public int GetExpressionResult(string someExpression)
{
Divide();
Multiply();
Addition();
Subtraction();
return result;
}
in the above example the result is dependant on all four methods, so it is fine to call it like this.
now in your example 2 if the methods are totally independant of each other than you should the way you have done.
Conclusion:
There is no hard and fast rule for this, You should call the way your application demands.
As far as I understood your question, what you are describing is basically a pipeline. There is a very interesting blog (in two parts here and here) about how to elegantly tackle situations as yours.
At the end, it depends on what you're trying to do and applies, IMHO, not only to C#.
Your first option should be applied when method<i+1> is a helper for method<i>, or is included in it. I can't find an example for such a scenario.
Your second example, which is far more readable to me, should be applied when you have a long sequence of actions that need to take place. Let say:
void mainMethod()
{
ConnectToDB(); //if can't connect, log it and exit
GetUserInfo(...); //if null, log it and exit
ShowUserInfo(...);
}
In the example above, it's hard (for me) to imagine a division to methods like in your first scenario.
I want to design a class, which contains a procedure to achieve a goal.
And it must follow some order to make sure the last method, let's say "ExecuteIt", to behave correctly.
in such a case, what design patter will you use ?
which can make sure that the user must call the public method according some ordering.
If you really don't know what I am saying, then can you share me some concept of choosing a design patter, or what will you consider while design a class?
I believe you are looking for the Template Method pattern.
Template Method is what you want. It is one of the oldest, simply a formalization of a way of composing your classes.
http://en.wikipedia.org/wiki/Template_method_pattern
or as in this code sample:
abstract class AbstractParent // this is the template class
{
// this is the template method that enforces an order of method execution
final void executeIt()
{
doBefore(); // << to be implemented by subclasses
doInTheMiddle() // also to be implemented by subclasses
doLast(); // << the one you want to make sure gets executed last
}
abstract void doBefore();
abstract void doInTheMiddle();
final void doLast(){ .... }
}
class SubA extends AbstractParent
{
void doBefore(){ ... does something ...}
void doInTheMiddle(){ ... does something ...}
}
class SubB extends SubA
{
void doBefore(){ ... does something different ...}
}
But it seems you are fishing for an opportunity to use a pattern as opposed to use a pattern to solve a specific type of problem. That will only lead you to bad software development habits.
Don't think about patterns. Think about how you would go around solving that specific problem without having patterns.
Imagine there were no codified patterns (which is how it was before). How would you accomplish what you want to do here (which is what people did to solve this type of problems.) When you can do that, then you will be in a much better position to understand patterns.
Don't use them as cookie cutters. That is the last thing you want to do.
Its basically not a pattern, but: If you want to make sure, the code/methods are executes in a specific order, make the class having only one public method, which then calls the non-public methods in the right sequence.
The simple and pragmatic approach to enforcing a particular sequence of steps in any API is to define a collection of classes (instead of just one class) in such way that every next valid step takes as a parameter an object derived from the previous step, i.e.:
Fuel coal = CoalMine.getCoal();
Cooker stove = new Cooker (gas);
Filling apple = new AppleFilling();
Pie applePie = new Pie(apple);
applePie.bake(stove);
That is to say that to bake a pie you need to supply a Cooker object that in turn requires some sort of a suitable fuel to be instantiated first. Similarly, before you can get an instanse of a Pie you'd need to get some Filling ready.
In this instance the semantics of the API use are explicitly enforced by its syntax. Keep it simple.
I think you have not to really execute nothing, just prepare the statements, resources and whatever you want.
This way whatever would be the order the user invokes the methods the actual execution would be assured to be ordered; simply because you have the total control over the real execution, just before execute it.
IMHO Template Method as very little to do with your goal.
EDIT:
to be more clear. Make your class to have one public method Execute, and a number of other public methods to tell your class what to do (when to do it is a responsibility of you and not of the user); then make a number of private methods doing the real job, they will be invoked in the right order by your Execute, once the user has finished settings things.
Give the user the ability of setting, keep execution for your self. He tells what, you decide how.
Template Method is rational, if you have a class hierarchy and base class defines protected operation steps in its public template method. Could you elaborate your question?
As general concept you should choose a pattern as a standard solution to a standard problem so, I agree with Oded, the "Template Method" seems to fit your needs (but what you explained is too few maybe).
DonĀ“t use pattern as "fetish", what you have to keep in mind is:
How can I figure my problem in a standard way?
There is a pattern for this?
Is this the simplest way?