I'm fairly new at functional programming, and am trying to work within a very imperative code base, so I'm trying to write code that's mostly FP, but can't be fully.
I have to write an override for the following method...
protected override string CreateEntity(XElement xe)
...where xe
contains two pieces of data needed for a database update. The method needs to validate the contents of xe
, then do the update, returning "" on success or a pipe-delimited list of errors if not.
I took a cue from the credit card validation sample in the language-ext tests, and wrote some helper methods like the following (implementation very similar to the sample, so omitted)...
private Validation<string, int> ValidateRegionID(XElement xe)
In the sample, he used Apply on a collection of these, which returned a Validation
that was the new credit card object if all went OK, or an Error
if not. In my case, I don't have anything to return if all went well (as I'm doing a database update, not creating a new object), so got as far as this...
Validation<string, Unit> validation = (ValidateRegionID(xe), ValidateClinAppsID(xe))
.Apply((regionID, clinAppsID) =>
{
// Do the database update (yes, impure code)...
return Unit.Default;
});
I don't know if this is the best way to do it, so any suggestions would be welcome.
My bigger problem is what to do next. The following works, but doesn't look very elegant or FP to me...
return validation.IsFail
? string.Join("|", validation.FailAsEnumerable())
: "";
Is there a better way of doing this?