C
C#12mo ago
Ryalia

❔ How would you refactor something like this? Is there a pattern that could help me?

Is there a way to clean something like this up? I've got a lot of evaluations to perform based on a bunch of different bool settings
void Main()
{
GetResult();
}

public Result GetResult()
{
var result = new Result();

bool condition1overridesCondition2 = true; // Configuration value
bool condition2 = true;
bool? condition3overridesCondition3 = true;
bool? condition4 = false;

// ... more conditions

if (!condition1overridesCondition2)
{
result.Valid = false;
result.Reason = "A";
return result;
}

if (!condition2) {
result.Valid = false;
result.Reason = "B";
}

if (condition3overridesCondition3 != true) {
result.Valid = false;
result.Reason = "C";
}

result.Valid = condition4 == true;
result.Reason = "D";


// ... More evaluations

return result;
}

public class Result
{
public string Reason { get; set; }
public bool Valid { get; set; }
}
void Main()
{
GetResult();
}

public Result GetResult()
{
var result = new Result();

bool condition1overridesCondition2 = true; // Configuration value
bool condition2 = true;
bool? condition3overridesCondition3 = true;
bool? condition4 = false;

// ... more conditions

if (!condition1overridesCondition2)
{
result.Valid = false;
result.Reason = "A";
return result;
}

if (!condition2) {
result.Valid = false;
result.Reason = "B";
}

if (condition3overridesCondition3 != true) {
result.Valid = false;
result.Reason = "C";
}

result.Valid = condition4 == true;
result.Reason = "D";


// ... More evaluations

return result;
}

public class Result
{
public string Reason { get; set; }
public bool Valid { get; set; }
}
7 Replies
Unknown User
Unknown User12mo ago
Message Not Public
Sign In & Join Server To View
Ryalia
Ryalia12mo ago
This is interesting, I'll give it a shot. I had the idea of making it a class of its own but I wasn't sure if the RulesEngine approach would work
ero
ero12mo ago
the answer is obviously CallerArgumentExpression lmao
Ryalia
Ryalia12mo ago
Reason being that some of these "rules" short circuit the evaluation and I don't want to evaluate the rest
ero
ero12mo ago
(joke)
Ryalia
Ryalia12mo ago
Something like this maybe? (Obviously not gonna copy paste) https://yiniski.medium.com/rule-engine-pattern-8a3f0e0c2d81 The business idea is that: I'm trying to build something (I guess a rule engine) that determines whether something should be done. Got a whole bunch of configurations So something e.g. MasterSwitchThatShutsDownTheEntireOperation will stop and short circuit the rest but e.g. ConditionOneThatNeedsToBeSuccessfulAlongWithOtherConditions will need to continue evaluating other conditions
Accord
Accord12mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts