I have the case of repeated very similar logic that is used to check if a boolean value was changed from the initial value and prevent it from changing back, or to summarize multiple boolean return values like:
bool SomeMethod()
{
bool endResult = true;
foreach(var obj in objs)
{
bool result = obj.Method();
if(!result)
endResult = false;
}
return endResult;
}
I reworked the logic into a class where a boolean can only be changed from the initial value, so that the boolean logic is all in one place. The IsChanged
property is for LINQ queries.
public class OneUseBool
{
private readonly bool _initValue;
public OneUseBool(bool init)
{
_initValue = init;
_currentValue = init;
_isChanged = false;
}
private bool _currentValue;
public bool CurrentValue
{
get { return _currentValue; }
set
{
if (_initValue != value)
{
_currentValue = value;
IsChanged = true;
}
}
}
private bool _isChanged;
public bool IsChanged
{
get { return _isChanged; }
private set
{
if(!_isChanged)
_isChanged = value;
}
}
}
So the original code gets changed to:
bool SomeMethod()
{
OneUseBool endResult = new OneUseBool(true);
foreach(var obj in objs)
{
endResult.CurrentValue = obj.Method();
}
return endResult.CurrentValue;
}
Is this a good way to do this sort of logic with bools, or am I just overcomplicating a simple problem?