ardalis / Result

A result abstraction that can be mapped to HTTP response codes if needed.
MIT License
836 stars 100 forks source link

New Feature: Generic Property Bag support #121

Open scottjferguson opened 1 year ago

scottjferguson commented 1 year ago

This request is to add a generic Property Bag to the Result type. This enables users to add generic information to a Result object intended to be used later downstream. For example, when an error occurs, I may want to log the error using a unique Id and add that Id to the Result so that I can return the log Id to the caller in addition to the error message.

The property would be an IDictionary<string, object> and look like this:

public IDictionary<string, object> PropertyBag { get; protected set; } = new Dictionary<string, object>();

ardalis commented 1 year ago

Do you want to do a PR for this one as well, and I'll put both of them in a new nuget package release?

scottjferguson commented 1 year ago

Hey @ardalis, I'd be happy to implement this. I would like to get your opinion on a design decision.

The ProperyBag would be useful for just about all use-cases. In order to maintain the immutability of Result, I believe I would need to have an alternate factory method for each status that takes the PropertyBag as input. Did you envision the change being so widespread? Or is there another option I'm not seeing?

One alternative I thought of is to simply add a PropertyBag as a public property, and let users manipulate it at any time. The downside is Result wouldn't be entirely immutable, upside is very low impact.

DorianGreen commented 11 months ago

You can introduce a new method that returns a copy of the result with the new property.

public Result<T> WithProperty(string key, object value)

This can be used to add or remove a property. (maybe even to remove a property if you supply a null value)