2

In the C++ world, we often have this kind of API design pattern:

bool foo(int input1, int input2, int& output1, int& output2, ClassA& outputObj); 

The function has a set of input parameters as well as output parameters. The return value indicates if the function succeeds or fails.

An example of this API is:

int input1=0;
int input2=1;
int output1=0;
int output2=1;
ClassA a = new ClassA(...);
bool r = foo(input1, input2, output1, output2, a);

However, in the JavaScript, we have no simple way to simulate "change the primitive argument by reference" behavior. If we wrap the primitive type (number, string etc.) using objects. The API will be ugly.

Any idea about how to design an elegant API using JavaScript with input parameters, output parameters, return values? There might be objects and primitive types in the parameters.

Grevling
  • 456
  • 4
  • 18
Lin Z
  • 171
  • 2
  • 9

1 Answers1

0

Don't pass output variables as parameters. Rather return them as an array:

function foo(input1, input2)  {
    ...
    return [output1, output2, outputObj];
}

You may also return a more descriptive object, for example:

function foo(input1, input2)  {
    ...
    return {importantStuff: output1, somethingElse: output2, completeObject: outputObj};
}

Use throw to indicate error.

Bottom line: the way it's done in C++ is not necessarily the way it should be done in Javascript.

You seem to be expecting Javascript to have references (&), like C++. In Javascript, every object is a reference and these are passed by value.

So, if you have:

var foo = {prop: 'foo'};
function f(x) {
    x.prop = 'bar';
}
f(foo);
console.log(foo);  // Will display {prop: 'bar'}.

In C++ parlance, objects are passed by reference. Read this for full understanding.

Community
  • 1
  • 1
Max
  • 3,384
  • 2
  • 27
  • 26
  • But in many cases, we need to "change" the parameter. For example: foo(machineObj) { //change the state of machineObj machineObj.doSth1(); machineObj.doSth2(); } – Lin Z Oct 15 '13 at 17:41
  • @LinZ: see the link I added to understand semantics of values in Javascript. – Max Oct 15 '13 at 17:55
  • I understand the difference of by value and by reference. My concern is that there is no "elegant" way to achieve the effect of "bool foo(int input1, int input2, int& output1, int& output2, ClassA& outputObj);". In javascript, if you wrap the primitive types in a dictionary, the code in the caller will be verbose. – Lin Z Oct 15 '13 at 21:03
  • @LinZ: Yes, you can't do that. But anyways, returning an array/object is *more obvious*! Parameters are for passing stuff into a function. C++/C/Java trick of passing parameters by reference in order to return them is only used because there is no way to return multiple values otherwise in these languages. In Javascript, there is an easy way (return an array). – Max Oct 15 '13 at 21:09