somid3
somid3

Reputation: 680

what pattern to use for multi-argument method?

I have a method with the following signature: foo (Sample sample, Aliquot aliquot)

"foo" needs to alter a Sample object, either the first argument or from the second argument it can extract its Sample. For example:

foo (Sample sample, Aliquot aliquot) {
    Sample out = null;
    if (sample != null)
       out = sample
    else
       out = aliquot.getSample()

    return out;
}

But that is so un-elegant, other than reading the API a developer does not know the reference of the first argument overrides the Sample of the second argument.

Now, I could change "foo" to foo (SomeMagicalObject bar) where SomeMagicalObject is a tuple for Sample and Aliquot and holds some logic ... etc.

But I am wondering, are there some patterns for this question?

Upvotes: 1

Views: 140

Answers (3)

Eric McNeill
Eric McNeill

Reputation: 1814

Depends on what the bigger picture is, but if you don't control the Sample object you could always just do this without a method:

Sample foo = (sample != null) ? sample : aliquot.getSample();

Upvotes: 0

Andy White
Andy White

Reputation: 88375

I would either change it to foo(Sample sample), and make the caller pass in a Sample object, or change it to foo(Aliquot aliquot), and make the caller set the Sample on the Aliquot.

You're right that if you allow both ways, it will be confusing to the caller as to which one is required. Remove the unknown and force the caller to do it one way or the other.

Upvotes: 2

Noel Ang
Noel Ang

Reputation: 5109

sample.foo( aliquot );

Upvotes: 0

Related Questions