Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design question: pass the fields you use or pass the object?

I often see two conflicting strategies for method interfaces, loosely summarized as follows:

// Form 1: Pass in an object.
double calculateTaxesOwed(TaxForm f) { ... }

// Form 2: Pass in the fields you'll use.
double calculateTaxesOwed(double taxRate, double income) { ... }

// use of form 1:
TaxForm f = ...
double payment = calculateTaxesOwed(f);

// use of form 2:
TaxForm f = ...
double payment = calculateTaxesOwed(f.getTaxRate(), f.getIncome());

I've seen advocates for the second form, particularly in dynamic languages where it may be harder to evaluate what fields are being used.

However, I much prefer the first form: it's shorter, there is less room for error, and if the definition of the object changes later you won't necessarily need to update method signatures, perhaps just change how you work with the object inside the method.

Is there a compelling general case for either form? Are there clear examples of when you should use the second form over the first? Are there SOLID or other OOP principles I can point to to justify my decision to use one form over the other? Do any of the above answers change if you're using a dynamic language?

like image 656
Kyle Kaitan Avatar asked Jul 07 '09 14:07

Kyle Kaitan


1 Answers

In all honesty it depends on the method in question.

If the method makes sense without the object, then the second form is easier to re-use and removes a coupling between the two classes.

If the method relies on the object then fair enough pass the object.

There is probably a good argument for a third form where you pass an interface designed to work with that method. Gives you the clarity of the first form with the flexibility of the second.

like image 162
Andrew Barrett Avatar answered Nov 01 '22 01:11

Andrew Barrett