user9993
user9993

Reputation: 6170

Is this type of logical condition check bad practice?

I've got a method that returns a result class. The result class has a Boolean property to indicate if an operation was successful or not. It can only ever be true if a number of criteria are true. I thought that the following code would be more concise than the equivalent if statement but I wanted to check if what I'm doing is regarded as bad practice or not.

bool successfullyParsed;

bool conditionA = true;
bool conditionB = true;

successfullyParsed = conditionA && conditionB;
//successfullyParsed should only be true if both criteria are true.

Upvotes: 1

Views: 94

Answers (2)

Alex McMillan
Alex McMillan

Reputation: 17952

That's perfectly fine, and in fact an elegant solution to the problem.

Upvotes: 1

Joseph Woodward
Joseph Woodward

Reputation: 9281

No, it's not bad practice - in fact it can be a great way to make more complex conditional logic more readable, for instance (a trivial example):

bool isLive = pages.Any(x => x.Live == true && x.Published == true && ...)

In your example could you not just do the following to make it even more readable?

bool conditionA = true;
bool conditionB = true;

bool successfullyParsed = conditionA && conditionB;

This way you can remove the initial declaration of successfullyParsed.

If your method were to return your successfully parsed boolean then you could shorten it even further to:

bool conditionA = true;
bool conditionB = true;

return conditionA && conditionB;

Upvotes: 1

Related Questions