I keep writing several utility, reusable functions in C#. Many functions return multiple values for which I use out or ref parameters. Many functions also have additional information, which may be of use to some callers (but not all callers).
Example, a function to read a CSV file may have additional information like no. of blank lines, no. of lines with duplicate values, and some other statistics.
The additional information could also include warnings, messages, etc.
Not every caller will be interested in this information, so I don't want to include all these as out, ref or Tuples, which will make it mandatory for the caller to declare all such expected variables.
I just wanted to figure out if there is a way to make the additional information available to the callers, so that the caller can choose or retrieve some of the optional additional information it is interested in.
For example, Func 1 can call Func B. After calling it, it gets all the standard return values. Additionally, can it call something like FuncB.GetAdditionalInfo(infoType) without Func B getting executed again?
It may be possible to design this using a class which serves as an intermediary to store all the optional values as well, and then return them to the caller on request; but I want it to be generic enough to be used across all my utility functions.
One possibility is Func B storing all these in some kind of global variables, which the caller can access if required. But if a utility class has several such resuable functions, I will need to have so many public variables, for the additional info of each function!
I am on .NET 4.5 as of now. Is there a design pattern for this? I am open to know if there is a good solution in F#.
Also, I want to avoid too many overloaded versions to achieve this! Thanks.
I do not contend to present you with the ideal implementation, but here is one that makes sense to me. Design two different data structures: one would represent the options that your function accepts and the second one would be the one that your function returns. For example:
In the above example
CountBlankLinesis a specific implementation that counts only blank lines and acts as "sugar" that simplifies the call, whileAnalyzeCSVis the method that actually will do the counting. Also, notice how theCSStatisticsstructure has nullablelongs. This will allow you to check if a value is null and therefore know that it was not actually analysed instead of outputting a zero (which is a possible value).The
CSVAnalysisOptionsstructure could also be replaced by bit flags, you can read about them here - https://www.dotnetperls.com/enum-flags.