# Design Pattern: Algorithm varies according to the input arguments

I will give a simple example to help you understand my question. Suppose we have a rectangle and a Utility class with a method that creates a buffer arround a shape.

The `.createBuffer` method has required and optional arguments:

• optional: direction (for example "inside" or "outside", default is "outside")

... maybe more arguments ...

Every combination of arguments needs a different algorithm.

Which design pattern is appropriate for solving similar problems?

• Check out the builder pattern ... here is a random SO post about this pattern : stackoverflow.com/q/5007355/2001247 Commented Apr 15, 2014 at 15:49
– gnat
Commented Apr 15, 2014 at 15:58
• Design patterns are all about extension and reusability. You need neither or at least you don't sound like you need it. Commented Apr 15, 2014 at 20:30

It's not clear to me that you need any design pattern -- at least not in the sense of the "Gang of Four" book.

From your description of the problem:

Every combination of arguments needs a different algorithm

what you need is some way to get from input -> output where input is "combination of arguments" and output is "algorithm". This is essentially just a hash table (or a function), in which:

• keys: some property of the specific arguments present
• values: algorithms (the exact implementation could be functions, objects, etc. depending on which language you're using and how convenient each choice is).

The second part of your problem -- "The .createBuffer method has required and optional arguments" -- isn't well-specified enough to give a sure answer, and will also depend on your choice of language. If your language supports optional arguments and default values, this problem nearly solves itself:

``````def createBuffer(self, radius, direction="outside")
...
``````

If you're in Java, you can use reference types and check for `null`, converting them to default values where necessary. Or even better, try this -- it helps clarify your intention to use nullable types to other programmers!

``````public void createBuffer(float radius, Optional<Direction> direction) {
if ( direction.isAbsent() ) {
direction = new Direction("outside");
}
....
}
``````

As others mentioned, you could also throw the Builder pattern at it, but personally I wouldn't unless I was sure that I needed it, because a single method with a single type signature is simpler and easier to use.

I would go with a builder pattern. Where shape is the shape to be buffered, 5 is the required radius, I made up some other things that you may want your buffer to have.

``````var bufferedShape = new BufferBuilder(shape, 5)
.Inside()
.SinglePixel()