Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a bad practice to declare an Array in arguments?

Tags:

javascript

validationError([elem1,elem2],type,shiftNo);

or

var arr = [elem1,elem2];
validationError(arr,type,shiftNo);

What I mean to ask is approach 1 of calling the function considered bad ( also does it have any performance ramifications). and for that matter is it a bad approach to declare strings, object and functions inside arguments.

like image 816
bhavya_w Avatar asked Dec 12 '22 01:12

bhavya_w


2 Answers

Performance is not an issue, not in a language like JS, Ruby or whatnot. So all we can do is think about code readability. And this case is not strongly related to JS, so will be my examples.

move = ["E2", "E4"];
if chessboard.valid(move, player) {
  ...
}

This clearly states: "if the move (E2 E4) is valid for this chessboard, then...", you don't even need to look at the docs to know that. If we write that without assigning our array a name, the result looks a little cryptic (still easy to guess, but harder for such a tiny example):

if chessboard.valid(["E2", "E4"], player) {
  ...
}

What is this supposed to mean? What does valid stand for here? Maybe, it's asking whether these cells contain valid player's pieces? This is a sympthom of a design flaw, more precisely bad naming. It makes bold assumptions about how the chessboard code will be used. We can make it obvious that this array represents a move by renaming the chessboard's method:

if chessboard.valid_move(["E2", "E4"], player) {
  ...
}

This is better, but you may not have an API that allows your code to stay so readable without some additional naming.

So, I suggest a rule of thumb:

  1. If the array will be used more than once, name it.
  2. If the meaning of the array is not obvious from where it goes (function name), name it.
  3. Don't name it, unless points 1 or 2 apply.
like image 88
D-side Avatar answered Dec 13 '22 15:12

D-side


It doesn't make any difference really. Either way, you create a Javascript Array, which basically is an Object and get a reference in return (which you pass to your method). If you don't need to access that array (or other data) later in your code, the second approach is completely fine.

like image 44
jAndy Avatar answered Dec 13 '22 14:12

jAndy