GFlisch / Arc4u

Apache License 2.0
23 stars 18 forks source link

More efficient AddIf with function delegates #100

Closed vvdb-architecture closed 9 months ago

vvdb-architecture commented 9 months ago

Fluent logging has the capability of conditionally adding a property, using AddIf, like so:

public CommonLoggerProperties AddIf(bool condition, string key, string value)

The downside of this method is that the value argument needs to be specified, even when condition is false. If value is the result of an expensive operation:

...AddIf(condition,"MyKey", ComputeExpensiveValueForDebugging(otherParameters));

... then that expensive operation (ComputeExpensiveValueForDebugging(otherParameters) in this case) will be computed regardless of the value of the condition parameter.

To avoid this, this pull request provides for each overload of AddIf a corresponding overload with a function delegate as value parameter. For example:

public CommonLoggerProperties AddIf(bool condition, string key, Func<string> value)

This way, the previous call can be written as:

...AddIf(condition,"MyKey", () => ComputeExpensiveValueForDebugging(otherParameters));

This way, ComputeExpensiveValueForDebugging(otherParameters) will only be called when condition is true. Nothing will be called if someCondition is false.