Assume I have an object Car, with five parameters, { numwheels, color, mileage, horsepower, maxSpeed }. I have a method that needs 3 of these values. Which of the 2 options is said to be best practice ? Is it better to pass enclosing object and reduce the number of parameters, OR just pass in bare-minimal data to a method (eg: numwheels and color will not be accessed in method 2) ?
Option 1 pass whole object:
void compute(Car c, Person p) {
return c.mileage + c.horsepower + c.maxSpeed + p.age;
}
Option 2: pass in just the method values.
void compute(int mileage, int horsepower, int maxSpeed, int age) {
return mileage + horsepower + maxSpeed + age.;
}
Note: assume for some reason, compute cannot be a part of Car class. Please answer with that assumption in mind.
Reaching 6 parameters is below average, so the common sense that set the bar around 3 or 4, and “for sure, nothing beyond 6”, can be read on the actual coding. Methods with 10 arguments or more appear in less that 20% of projects.
The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification - and then shouldn't be used anyway.
There is no maximum limit to pass parameters or arguments to a user defined function. But for a pre-defined function it depends. Not sure, however some sources say that C functions accept at least 127 parameters.
Reference data type parameters, such as objects, are also passed into methods by value. This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the object's fields can be changed in the method, if they have the proper access level.
It's better to pass the enclosed object because any change in the number of parameters required in the computation wouldn't affect the method signature in future.
You can, in fact, accept an interface type, say, Vehicle
instead. This allows the same method to compute data on Bike
, Jet
etc. later on.
public int compute(Vehicle veh) {
return veh.computePerformance();
}
where Car
implements the method as
public int computePerformance() {
return mileage + horsepower + maxSpeed;
}
The idea is to write code that easily lends itself to extensibility.
I would suggest a third option: add a method "compute" to Car.
This is called "Tell, don't ask".
See http://martinfowler.com/bliki/TellDontAsk.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With