I recently watched the Pluralsight course "Functional Programming in C #". And rewrote some methods in my hobby project. Now they look like this:
public override CommandLineResult GetResult()
{
return Disposable.Using(new IndicatorRepository(), repo =>
{
return repo.AddOrUpdateIndicator(Indicator, Value, DateTimeExtensions.LocalNow().Date);
})
.Map((p) => new NumericIndicatorRecorderedModel()
{
Id = Guid.NewGuid().ToString(),
DbActionPreformed = true,
IsRewritten = Convert.ToBoolean(p),
IndicatorName = Indicator,
Value = Value,
ValueDate = ValueDate
})
.Map((model) => new CommandLineResult()
{
ActionName = "~/Views/CommandLine/_clresult_NumericIndicatorRecorderedModel.cshtml",
Model = model
});
}
There is something beautiful in this chaining approach (I removed the use with a one-time class, at every step I have expressions, not instructions, etc.).
But there are questions:
- Doesn't this approach cover some dangers? and what are they? (for example, not difficult to debug)
- What do people usually do in terms of chaining if they need to branch out the code flow? An open circuit somewhere? Write "map-if" functional extensions (would this approach create spaghetti code?)?
UPDATE: a more specific question on this issue
- :
public string GetResult(bool param) {
if (param) {
return MyClass.DoOneWay(p =>...).AlsoDo(q =>...).ToString();
}
else
{
return MyClass.DoOtherWay(p =>...).AlsoDo(q =>...).ToString();
}
}
if-helpers, :
public string GetResult(bool param)
{
return MyClass.DoIf(param, p => ...., q => ....).AlsoDo(q =>...).ToString();
}
, , true/false?
"" "" ?