In the following scenario:
A factory returns an object of a logic class:

ILogicClass object = factory.GetByRequirements(reqs);

I then want to invoke a method and get some results which are in the same shape for all concrete logic classes:

output = object.GetResults(...)

and then use the result.

Imagine the concrete implementations need different options to produce the result:

GetResult(integer, integer) for one logic class
GetResult(integer, string) for another logic class implementation

Options to skin this particular cat I can come up with are:

GetResult(integer, integer, integer, string)

Which is passing ALL the arguments to the method so each concrete implementation can use the required data and ignore the rest

Pros: Strongly typed

Cons: Every time you add a new parameter, that needs to be implemented on ALL the ILogicClass implementations and most of them won't even use it which is a waste and not elegant.

Another option is:

GetResult(Options opts)

Pros: Strongly typed, no need to redefine the interface and change the concrete types every time something new is required

Cons: Allocation of an extra object and most of its content will be irrelevant for other implementations.

A third option would be:


Pro: you can pass whatever you like without creating extra object or passing irrelevant data

Cons: error prone to runtime exceptions

I appreciate there may be no other solution to this problem, but is there another pattern I have not considered or a better approach to this problem?

  • You might want to add a bit of calling code, as this is where the problem lies. Where are the values coming from? Another option is to make the argument values mutable properties of the logic object. – Frank Hileman May 25 '18 at 0:19

Use generics here to create true type safety, as that is what generics are for after all:

ILogicClass<T1, T2> object = factory.GetByRequirements<T1, T2>(reqs);

output = object.GetResults(ItemOfT1Type, ItemOfT2Type);

This of course assumes that you really only have two parameters for GetResults and that either it's the only method or all other methods would likewise be able to work within the constraints of T1 and T2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.