amantinband/error-or

Smart way to use ErrorOr in a similar style to with-Expressions

janschreier opened this issue · 1 comments

This is more of a question than an issue. I use ErrorOr to guard my calculation engine from getting faulty data and it works great. I usually do this by making constructors private and my objects immutable and allow object creation only in form of

public static ErrorOr<T> TryCreate(parameters...);

I now have some cases where I would like to change one or two properties of the object. For C# record classes this is solved very elegantly by using with expresisons:

var person2 = person1 with {Lastname='Doe' };

The drawback of with-expressions is that in this case I cannot run all my validation logic.
In some cases I decided to create a copy constructor-like version of TryCreate() manually to still get an ErrorOr and all it's validation logic but writing copy constructors is not something I enjoy doing. This looks something like this:

 public static ErrorOr<MyClass> TryCreate(MyClass orig, int? id= null, string? name= null)
 {
     id ??= orig.Id;
     name ??= orig.Name;
     return TryCreate(id.Value, name.Value);
 }

// can be called with named parameters like so:
 var y = TryCreate(myClassObj, name:"Bill");

While this consuming part is okay, the writing part of the copy constructors is something I would want to avoid.

I wonder if there is a more elegant solution (which does not involve Reflections). I think it could be done with code generation but that's something I havent't done before.

would appreciate ideas on this topic.