How to deal with a massive amount of conditions [closed] - c#

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

Related

Best way to replace multiple IF statements with design pattern or cleaner code? [closed]

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 12 months ago.
Improve this question
I have a function that returns an object whose name is Rule. Its structure is below:
public class Rule
{
public bool ShouldLogInADatabase {get;set;}
public bool ShouldLogInBDatabase {get;set;}
public bool ShouldShowNotification {get;set;}
public bool ShouldSendEmail {get;set;}
}
For example, I have this code:
var rule = ExecuteRule(); //This method returns Rule object.
Now, I have to run some functions based on rule like:
if(rule.ShouldLogInADatbase==true)
{
//Run some code
}
if(rule.ShouldLogInBDatabase==true)
{
//Run some code
}
if(rule.ShouldShowNotification == true)
{
//Run some code
}
I need to check each rule object and it is expected in the future more bools can come. I want to write in cleaner way or use some design pattern. How I can do it?
If you are interested in using Design pattern, Chain of Responsibility is a good option for this
Chain of Responsibility is behavioral design pattern that allows passing request along the chain of potential handlers until one of them handles request.
The pattern allows multiple objects to handle the request without coupling sender class to the concrete classes of the receivers. The chain can be composed dynamically at runtime with any handler that follows a standard handler interface.
https://refactoring.guru/design-patterns/chain-of-responsibility/csharp/example

Apply get set for methods? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have just learned get set principles in C# and I wonder whether there is any interest of using the same principle for methods.
If I understand well, get and set are used for variables. But it could be possible to apply the same principle for methods. For instance:
private int _GiveMultiply()
{
int a = ...
int b = ...
return c = a*b;
}
public int GiveMultiply
{
get { return _GiveMultiply(); }
}
But is there any kind of interest to do such a thing ?
For example is there a risk to use a public function that can be prevented using such a process ?
The answer is: it depends. I'll try to help you to reformulate your question: does it make any sense to return a function rather than computed result from another fuction? Then I would say: definitely yes (let me know if you'd like to know ehy, I'll update this post). But the example you showed does not return a fuction, it just wraps it into yet another fuction, which is useless. The only exception is various kinds of abstract method patterns, where you might have public function with some predefined logic and call to the abstract/virtual fuctions; rarely they do have same name, then indeed wrapping sort of works.

Using "this" in getters/setters in C# [closed]

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
Short and sweet (hopefully), is there a specific reason not to use the this keyword when writing getters and setters in C#? I know the typical format, and the one I've always used, is:
public void SetDay(int _day) { day = _day; }
public int GetDay()
{
return day;
}
Recently though, I've been learning Java, and in several of the books I've been using I've seen it written instead like this:
public void SetDay(int _day) { this.day = _day; }
public int GetDay()
{
return this.day;
}
So basically, is there a reason to avoid doing it the same way in C#? Will it cause any problems or errors, or is it a valid approach and really just a matter of personal preference. I'm wondering because, while I know the this in C# is understood, explicitly using the this keyword seems like it would aid in eliminating a bit extra ambiguity, which personally is always a good thing.
Thank you!
There's not much to it really.
You can do it, and you can avoid it. I think it's quite obvious when you're in the getter/setter that you're talking about the object you're in, so I've never used it there.
Also, it seems like Resharper will suggest it's redundant, and gray it out.
If you find it to be of use for you (readability wise), by all means, use it. Otherwise, it'll save you five keystrokes (about a second?) every time you implement a getter by hand ... :)

Way of coding in C# [closed]

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.

Using related functions in one class [closed]

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();
}

Categories

Resources