Reputation: 402
I have a single data structure that holds a relatively small amount of objects (ca. 1500) and several methods that are acting on it. Is there a programming pattern to iterate the methods over the data instead of writing significantly more boilerplate code?
Upvotes: 0
Views: 109
Reputation: 14064
If the commonality between these methods is just that they take a list as an input and output a result, but the result is of a different type each time, there's not much you can de-duplicate. If there's some common abstraction to the result types instead, you could model it simply as a series of :
Func<IEnumerable<TInput>, TResult>
Then you could Select()
the result of Invoke()
ing these functions (or SelectMany()
if you want the output to be flattened out).
Alternatively, you could have a series of
Func<TInput, TResult>
and iterate on the data list, applying all the functions to each element one by one. But then the results would be sorted by each of the 1500 data elements instead of a concatenation of full executions of every function.
Upvotes: 0
Reputation: 37045
It depends on the language you are using. However, the concept that you are looking for is map.
It usually works like this:
map f xs
In an imperative style, this would be:
for (int i = 0; i < xs.size(); i++) {
f(xs[i])
}
I just saw the C# tag.
In C# you can use a functional style, an imperative style or a bit of both. If you use a functional style, you can use LINQ. However, your methods should not modify the underlying objects, since LINQ statements should have no side-effects. For an imperative style, you can just use foreach
.
You can use LINQ to query a collection. For example, this will find all x
in myObjects
such that f(x)
:
var fs = myObjects.Where(x => f(x))
Upvotes: 1