Function Parameters As An Object: Acceptable Coding Style?

I am not sure if this topic comes under “coding style” and I could not see where it has been addressed here & elsewhere.

The traditional named function definition is an ordered set of comma-separated parameters.

function calculate(
      ) {
  return gramMass1 / molecWgt1 / vol1 * vol2 * molecWgt2 / 

For defined functions with a considerable number of parameters, as above, this requires that the arguments be well-ordered in the calling instance.

But suppose instead of function definitions with long parameter lists and their order to memorize, just define the function with an object parameter and the parameters are made properties of the object. One only needs to memorize the property names, which relative easy to do, and now the order of the properties (parameters) is unimportant when calling the function.

function calculate(parameters) {
  return parameters.gramMass1 / parameters.molecWgt1 / 
		parameters.vol1 * parameters.vol2 * parameters.molecWgt2 / 

	gramMass1: 34.1,
	gramMass2: 2.1,
	molecWgt1: 170.2,
	molecWgt2: 62.78,
	vol1: 0.5,
	vol2: 1.5

This is not innovative of course. The purpose of this post is to ask whether this is an acceptable coding style in general. Are there drawbacks? Would your development team supervisor or enterprise coding standards manual encourage/discourage/insist on/forbid this?

In general, you only want to wrap data in objects like that if the data is frequently packaged together. The whole idea of Object Oriented programming is a big concept but its very much worth looking into.

It’s a common coding style: React for instance uses it all over the place. It’s especially nice when a function takes arguments of all the same type (numbers in your case) because their positions can’t accidentally get switched.

But if you find yourself passing the same “shape” of object everywhere to different functions, you should consider a proper class/prototype with methods/ Using anonymous “dumb” objects for everything is a major antipattern. If you can use TypeScript annotations (and you probably can), you can use that to type your dumb objects to make sure they’re well-formed.

You should probably reconsider the signature of your calculate() function to only work on one mass at a time, then a separate function that takes two arguments instead of glomming them all into one.

1 Like