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.
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
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I am trying to write a console app that has multiple methods (hopefully my terminology is correct, new to this), so I could call using 3 parameters (string, string, int) and/ or two params (string int). I was going to write two method... but Main can only have one entry point. So how can I make this work? Was wondering if anyone knew of a technique to work around this, maybe a best practice I can emulate.
Main method (entry point) has a parameter of type string[] (string array).
You can pass parameters as many as you want. For example if you want to pass three parameters you can do it in this way
C:\ConsoleApplication1 arg1 arg2 arg3
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
if(args.Length == 3)
{
//process your three parameters
var parameter1 = args[0];
var parameter2 = args[1];
var parameter3 = args[2];
}
else
{
//process for example 2 parameters
}
}
}
}
For debug purposes you can define your parameters in debug tab as in image.
Currently, this is not possible in the way you've described it.
However, there are some workarounds you could try. You can either have a single main method with a string[] for arguments and do the parsing yourself, calling the correct method depending on what arguments you receive (this is fine for very simple cases like the one you described, but not recommended for more complex cases), or you can have a library do the hard work for you.
I'd recommend trying System.CommandLine for more complicated cases, as it'll handle the parsing logic for you and just call your methods, which is probably the closest you'll get to what you're after.
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 3 years ago.
Improve this question
Intro
I am trying to build a system that will give information to the front-end which elements should and shouldn’t be shown.
But the problem i am running into is that i have to deal with massive amount of conditions, these could vary from rights to which modules are available and even which data is available.
So i was expecting that someone else would also have run in to this problem, but i couldn’t find anything.
What i have tried
I first start searching for design patterns that could possibly deal with this problem but i couldn’t find any that did. Then i went to source making and read all the descriptions of possible patterns but to me none of them seemed to be the solution to my problem.
Afterwards i just searched around if someone had encounter a similar problem and once again i did not seem to find any close comparisons to my problem.
So are their any suggestion how i could improve searching
Or did i overlook something?
I would suggest that you take a look to something like the Rules design pattern
Effectively, this would be a large set of predicates.
Steps needed to accomplise this:
1. Change boolean logic to predicates and extentions
2. Create interfaces that provide the proper logic and transformations
With the Rules Pattern there is an Evaluator class that loops through a collection of rules and executes them. It evaluates the result and decides what action to take. In the simplest case it just executes all the rules, but it is also possible to add some selection logic to each rule that allows the Evaluator class to decide whether or not to run the rule (such as the IsMatch() method on the IRule interface above).
You can put your if statements into method which return bool value. For example:
public void GetMeal(Behavior behavior)
{
if (isAnimal(behavior))
GetMilk();
else
ChangeBattery();
}
private bool isAnimal(Behavior behavior)
{
if (behavior.HasVoice
&& behavior.HasVoice
&& !behavior.HasBattery )
return true;
return false;
}
public class Behavior
{
public bool HasVoice { get; set; }
public bool HasName { get; set; }
public bool HasBattery { get; set; }
}
I would suggest replacing those statements with commands. Here is a link with more info. The code is not in C# tho but I think you can understand the main idea from it.
https://scrutinizer-ci.com/docs/refactorings/replace-conditional-dispatcher-with-command
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.
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 4 years ago.
Improve this question
I have a class with two related functions (methods):
public class class1
{
public void SubscribeToListOfEvents()
{
// ....
}
public void UnSubscribeFromListOfEvents()
{
// ....
}
}
What's the best practice to use related functions in one class ?
Do you know of any implementations of related functions as one function ? Are they good ? In what situations are they good ? If so, can hyou give me an example?
Any available options of code above will be appreciated.
If the functions belong to the class, logically, then they are fine that way.
A class should be cohesive and methods that do an operation normally should have the mirror operation defined as well (Subscribe/Unsubscribe, Add/Remove etc...).
You have named them well, as they are very descriptive of what they do - how would you name a merged one? It is better to leave them separate, as this way they are self documenting and will not confuse users of the class.
With the example you provided, they are related - but only because they may work with the same set of data or objects.
Personally i would NEVER merge these into a single function. While it may be more typing, it is easier both to read and to maintain to keep them separate. When either of those two functions are being called it is obvious what is going to happen - if you were to merge them then it becomes not so obvious. This is a simple example though - if you were to merge two functions that were more complicated then things could get very murky, and you could end up having unintended side effects from calling the merged function.
Remember KISS - Keep It Simple, Stupid :) For every function, try and follow SRP - Single Responsibility Principle. While Wikipedia talks about SRP at the class/object level, there is no reason to not also apply it at the function level where practicable.
dont merge them, make an interface that will force you implement both methods
interface ISubscriber
{
void Subscribe();
void Unsubscribe();
}