-2

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?

6
  • LINQ allows you to work on collections while abstracting the boilerplate code. I suggest you to read this article by Martin Fowler (some of his examples are in C#). Commented Sep 28, 2015 at 9:14
  • Do the methods all have the same parameters and return values? Or does the result of one method get sent to the next? Example code could help. Commented Sep 28, 2015 at 14:04
  • The methods have all the same parameters and return values Commented Sep 28, 2015 at 14:14
  • 1
    please don't cross-post: stackoverflow.com/questions/32819062/… Commented Sep 28, 2015 at 22:35
  • A little more information about your use case would be helpful. Please see how to ask a good question. Commented Sep 29, 2015 at 0:51

1 Answer 1

-1

I don't think there is a design pattern for this. It's much too simple to be a pattern, I believe.

You have a list of objects and a list of functions, and you want the cartesian product of those two lists, e.g.

objects := [10, 20, 30] functions := [add1, subtract1] product := functions.product(objects) // product looks like this: // [(add1, 10), (subtract1, 10), (add1, 20), (subtract1, 20), (add1, 30), (subtract1, 30)] product.map((fn, o) => fn(o)) // => [11, 9, 21, 19, 31, 29] 

In C#, it would look a bit like this (I don't really know C#, so take it with a grain of salt):

using System; using System.Collections.Generic; using System.Linq; class Prog { static int add1(int i) => i + 1; static int sub1(int i) => i - 1; public static void Main(string[] args) { var objs = new List<int> { 10, 20, 30 }; var funs = new List<Func<int, int>> { add1, sub1 }; var result = from obj in objs from fun in funs select fun(obj); result.ToList().ForEach(Console.WriteLine); // 11 // 9 // 21 // 19 // 31 // 29 } } 
4
  • add1/sub1 would be more like static int add1(int i) { return i + 1 } or static Func<int, int> add1 = i => i + 1; Commented Sep 29, 2015 at 0:42
  • Why? The OP explicitly talked about methods, your second suggestion is a field, not a method. And your first suggestion is exactly what I wrote, only more verbose. Commented Sep 29, 2015 at 6:57
  • @KaseySpeakman That is a new C# 6.0 syntax. Commented Sep 29, 2015 at 7:25
  • @svick Oh. Jörg W Mittag: My bad. I thought you made a mistake since you said you didn't know C# well. I haven't use this new fangled syntax yet. Commented Sep 29, 2015 at 13:14

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.