I am learning about LanguageExt and using functional programming styles in C#. I have created a new class, with my goal being a ValueObject:
public sealed class AlertDefinition : NewType<AlertDefinition, AlertDefinitionType>
{
private AlertDefinition(AlertDefinitionType value) : base(value)
{
}
public static Validation<Error, AlertDefinition> Create(AlertDefinitionType alertDefinitionType) =>
(AllAlertDefinitionTypeValidator(alertDefinitionType))
.Map(adt => new AlertDefinition(adt));
}
and where my validator is:
public static Validation<Error, AlertDefinitionType> AllAlertDefinitionTypeValidator(AlertDefinitionType alertDefinitionType) =>
Enum.IsDefined(typeof(AlertDefinitionType), alertDefinitionType)
? Success<Error, AlertDefinitionType>(alertDefinitionType)
: Fail<Error, AlertDefinitionType>(Error.New($"The value {alertDefinitionType} is not a valid {nameof(AlertDefinitionType)}"));
AlertDefinitionType is just an enum and I need to make certain that integers passed in a REST endpoint are valid against the enum.
Several things are tripping me up:
- Is this a good pattern for creating value objects in a functional way?
- How do I extract the
AlertDefinitionTypevalue from myAlertDefinitionobject? I've seen references.Match, but is it necessary every time or is there an easier way?
This link helped me after the fact:
https://github.com/louthy/language-ext/issues/231
I was getting thrown by the fact that when retrieving a value I was getting either a
Unitor aValidation<Error, AlertDefinition>type when all I wanted was theAlertDefinitionTypevalue. This appears to give me what I want:The cast on the
Failseems a bit ugly, so if anyone has a better idea, I'm all ears.