Fillio iliu
Fillio iliu

Reputation: 15

How can I chain methods depending on user input?

I have a method that I'm using to process images (rotate, filter, resize, etc). It looks like this:

 public Image ProcessImage(Image image, Func<ImageFactory, ImageFactory> process)
    {
        using (var imageFactory = new ImageFactory(preserveExifData: true))
        {
            using (var imageStream = new MemoryStream())
            {
                var loadResult = imageFactory.Load(image);
                var processResult = process(loadResult);
                processResult.Save(imageStream);
                return Image.FromStream(imageStream);
            }
        }
    }

Since I'm using Func<> in this way I can just call the editing method I want like so:

_imageEditor.ProcessImage(_image, im => im.Resize(size))

Which means I can chain methods like:

_imageEditor.ProcessImage(_image, im => im.Resize(size).Rotate(54).Flip(true))

My question is, how can I chain these methods depending on the using input? So if my user wants to rotate and resize at the same time, I could just add the .Resize and .Rotate methods (which by the way, take different parameters).

Sure, I could use a bunch of bools but if I had a ton of editing methods it would become impossible, very very ugly to use.

Is there a way to add methods to this chain, and if so, how would you go about it?

Upvotes: 1

Views: 214

Answers (2)

Enigmativity
Enigmativity

Reputation: 117164

The easiest way to chain methods together is to use the Aggregate LINQ method.

You just need to change your method signature to Image ProcessImage(Image image, params Func<ImageFactory, ImageFactory>[] processes) and then you can do this:

public Image ProcessImage(Image image, params Func<ImageFactory, ImageFactory>[] processes)
{
    using (var imageFactory = new ImageFactory(preserveExifData: true))
    {
        using (var imageStream = new MemoryStream())
        {
            var loadResult = imageFactory.Load(imageStream);
            var processResult = processes.Aggregate(loadResult, (r, p) => p(r));
            processResult.Save(imageStream);
            return Image.FromStream(imageStream);
        }
    }
}

Now you just have to build your Func<ImageFactory, ImageFactory>[] processes from the user's selections.

Upvotes: 1

Peter Duniho
Peter Duniho

Reputation: 70701

Your question isn't 100% clear. You've left a lot of details out. But, it sounds like you are either asking how to successively invoke your methods, passing the result from one invocation to the next, or how to use inputs created at runtime to create this list of invocations, or both.

Without a Minimal, Reproducible Example, I don't have any good way to reproduce your scenario, nor to provide a solution that is specific to that scenario. But, here's a demonstration of the basic techniques you might use to accomplish those goals:

class Program
{
    private static readonly Dictionary<string, Func<int[], Func<A, A>>> _parser =
        new Dictionary<string, Func<int[], Func<A, A>>>()
    {
        { "Init", MakeInitFunc },
        { "Add", MakeAddFunc },
        { "Multiply", MakeMultiplyFunc },
        { "Negate", MakeNegateFunc },
    };

    static void Main(string[] args)
    {
        (string, int[])[] ops =
        {
            ("Init", new [] { 17 }),
            ("Add", new [] { 5 }),
            ("Multiply", new [] { 2 }),
            ("Negate", new int[0]),
        };

        Console.WriteLine(Chain(new A(), OpsToDelegates(ops)).Value);
        Console.WriteLine(Chain(new A(), OpsToDelegates(ops).Reverse()).Value);
    }

    private static IEnumerable<Func<A,A>> OpsToDelegates(IEnumerable<(string Name, int[] Args)> ops)
    {
        foreach (var op in ops)
        {
            yield return _parser[op.Name](op.Args);
        }
    }

    private static A Chain(A a, IEnumerable<Func<A, A>> ops)
    {
        foreach (Func<A, A> op in ops)
        {
            a = op(a);
        }

        return a;
    }

    private static Func<A, A> MakeInitFunc(int[] args)
    {
        return a => a.Init(args[0]);
    }

    private static Func<A, A> MakeAddFunc(int[] args)
    {
        return a => a.Add(args[0]);
    }

    private static Func<A, A> MakeMultiplyFunc(int[] args)
    {
        return a => a.Add(args[0]);
    }

    private static Func<A, A> MakeNegateFunc(int[] args)
    {
        return a => a.Negate();
    }
}

class A
{
    public int Value { get; private set; }

    public A Init(int value) { Value = value; return this; }
    public A Add(int value) { Value += value; return this; }
    public A Multiply(int value) { Value *= value; return this; }
    public A Negate() { Value *= -1; return this; }
}

There are two key elements to the above:

  1. Given a sequence of Func<A, A> delegates, it is possible to chain them together with a simple loop. See the Chain() method for how that can be done.
  2. Given some user input, it is possible to transform that into a sequence of Func<A, A> delegates. There is actually a very wide range of possible ways to approach that particular problem. My example shows a very simple technique, using a dictionary that maps input string values to helper methods that do the actual work of generating the elements of the sequence. See OpsToDelegates() for that.

Combining those two into this simple program, you can see how you can start with just a list of names of operations and parameters to apply them, and turn that into a functional sequence of operations actually applied to an object.

I trust you can take these general ideas and apply them to your particular scenario.

Upvotes: 1

Related Questions