I have a class that defines a fluent interface, including an Else
method, which can only be called once. The problem I therefore have, is how to tell if it has been called. Currently, I'm doing this via an extra bool field:
public class FluentMatcher<T1, T2, TResult>
{
private bool _elseValueSet;
private TResult _elseValue;
...
public FluentMatcher<T1, T2, TResult> Else(TResult resultIfElseRequired)
{
if (_elseValueCalled)
{
throw new ElseAlreadyAddedException();
}
_elseValue = resultIfElseRequired;
_elseValueSet = true;
return this;
}
}
I am uncomfortable with this though and so I'm considering something like:
public class FluentMatcher<T1, T2, TResult>
{
private Initialisable<TResult> _elseValue;
...
public FluentMatcher<T1, T2, TResult> Else(TResult resultIfElseRequired)
{
if (_elseValue != null)
{
throw new ElseAlreadyAddedException();
}
_elseValue = new Initialisable<TResult>(resultIfElseRequired);
return this;
}
}
This raises two questions:
- Is there already a way to test if the field has been initialised? I'm assuming not, as it could be a struct and thus cannot be null. Did I miss something though?
- I have a feeling that I'm not really fixing anything with my new version and that I'm playing with semantics. The first version works just fine, I just think it ugly. Is there a good reason to not use a bool in this case?