Should numbers be avoided in Javascript function names? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I heard from a JS developer recently that you should avoid using numbers inside function names.
For example:
function test1test() {
// function body
}
I've never come across this before so I was wondering if it's true? If so, why?

There's nothing wrong with having numbers in your function name, it's just a little unconventional. The ultimate goal in function and variable naming is readability and clarity of code, so if you think including a number in your function name make the code more clear, you should make that a priority.
However, for maximum readibility and clarity in most cases, your function names should be camelCase verb phrases to follow the predominant convention.
For instance, you might want to name a function convertToMp3(), in which case it would be silly to instead name the function convertToMpThree(). But you should avoid using names like obj2Array() or format2(), because those don't make your code more clear.

Ok, I'm going to try to answer this in without a my-opinion base...
Refering to W3's article on Javascript's best practices, we find the following statement, regarding to names:
good variable and function names should be easy to understand and tell you what is going on — not more and not less. One trap to avoid is marrying values and functionality in names. A function called isLegalDrinkingAge() makes more sense than isOverEighteen() as the legal drinking age varies from country to country, and there are other things than drinking to consider that are limited by age.
Note the not more and not less. There's no reference on why it should matter to use or not a number in the naming of a function/variable. It is just a case of what will be easily understood when you/others read the code.

doesnt make sense to avoid this in general..
its rather a question of style and when it actually makes sence in your context

The only actual restriction is that you cannot start a member name with a number. Other than that, it's a matter of style. Having said that, I cannot think of a member in the standard library that has a number in it. It's certainly rare to need this, but it can be useful. No need to be too dogmatic about these kinds of things.

Related

Which principle is being violated? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I am not good at naming, I good at feeling.
Suppose we have this hypothetical function:
function computePowerAndPrintResult(int x){
print(x*x);
}
It screams already in the naming of the function ("And") that something wrong here and personally I never write code like this.
Which principle is being violated here? Is it the single-responsibility principle?
Yes. The name is indeed a giveaway. In violation of the single responsibility principle, the function is responsible for two things: computing the square, and printing the result.
Also good naming sense is being violated: at the very least it should be called computeSquareAndPrintResult because Power without specifying the exponent doesn't make much sense. I'd personally call it printSquareOf so you can call it like printSquareOf(x), which reads very naturally.
No it's not. The single responsibility refers to a class. When a class is doing too much then it is violated. When a function is doing to much though you need to break it down.
Now I'm not saying that it's not an indication that it does.
In my mind, you need a class to compute the power, and a class that will manage the printing.
BUT: Assume that I have a need to implement an API that I would call and it would return the PDF of the compute power. I would need an api that would both calculate and print the result.
I would then create the GetSquareValueOutput which would have the single responsibility to orchestrate getting the data from the SquareValueCalculator class and then print with the Printer class.
This last GetSquareValueOutput might as well be called computePowerAndPrintResult and it would not break a thing. I wouldn't choose the name as it hints at a code smell, but in the end it's just a matter of context.
TL;DR: Change the name to printSquare. Then the name is much shorter, is equally accurate at describing what you do, and yet... if you really want worry about the single responsibility principle, you're still breaking it. Which says more about how SRP can easily be overzealously applied, than this being a bad method.
In depth on that name
'computePower' is a bad name for two reasons:
'Power' is a binary operation (X to the Yth power) and you're not really doing that; you've locking Y to '2', and that operation has a common name too: 'square'.
'compute' is usually superfluous. square already implies that calculation is going on. Look at e.g. java's AtomicInteger or BigInteger which have methods named add (really, in the case of BI, should be plus), but the point is, it's not computePlus. Note that it depends on a few factors; for example, in java it is common to start property getters with get, in a class that has an unrelated property or otherwise square is not as clear as one would like (say, its geometrically related, so square could be misunderstood to refer to the shape instead of the mathematical operation), then this is oversimplifying matters as well.
That means that part of the method name ought to be square and not computePower.
Then we have the andPrintResult part. Here Result is superfluous. What else would it be printing, other than the result?
You have 2 options:
This method should be named square and should return that value and not print anything. Make another method to print things.
'and' being a code smell is.. eh. Maybe. Look, you could name this method printSquare which is short, clear, and contains no and, and yet, it's just as much of a violation of the rule as computePowerAndPrintResults.
In many ways printSquare is a straight violation of SRP, but if you change the name to reportSquare, and the code will compute the square and then report it to the configured (injected via dependency injection for example) 'reporter output stream', all of a sudden it's not a violation of SRP, but all we did was redefine some words, the code remained the same.

no-param-reassign: What is a practical, real-life example of a problem caused by reassigning parameters? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I see a lot of questions about best practices for complying with the no-param-reassign linting rule, but no/fewer requests to illustrate the rationale for the rule.
Claims like 'Assignment to variables declared as function parameters can be misleading and lead to confusing behavior' are all well and good, but what are some real-life practical examples of problems caused by not adhering to this rule?
Note that I'm not asking for opinions about whether this rule is good. I am asking for concrete examples of this "confusing behavior" so I can understand the rationale for the rule better.
It's all about the principle of least surprise. The nice thing about modern JavaScript is that for non-parameter variables, if you see a const variable, you don't have to analyze the entire function to know what you can expect its value to be, so you can understand the code more easily. It can put your mind at ease, in short. If something is defined with let or var, then you know you have the mental burden of checking the code for any reassignments. This is why personally I recommend avoiding let or var almost all of the time.
Unfortunately, with parameters, you don't have the opportunity to declare whether they're reassignable. It is a rare practice to reassign parameters since the semantics of a parameter and assignable variable are now conflated. Personally, I don't think it's a huge deal for shorter functions, but where mutation can really bite you is in longer functions where you can't see all the code on the screen. Imagine you're trying to debug this code. You see an error being thrown like "Invalid purchase price". You find that error message at the bottom of a long function:
async function purchase(price, tax, roundUp) {
// ...
if (typeof price !== 'number') {
throw new Error('Invalid purchase price');
}
}
OK, you might say, let's see if anyone's not passing a number into purchase. So you find all references to purchase, and trace back where the first parameter comes from in all cases, and oddly you come to the conclusion that your code is haunted because you're never passing a non-numeric price to the code. However, you probably forgot that price could have changed at any time in the function, so you missed scrolling up and finding:
price = price + tax;
Someone passed a non-number into tax, causing an error on a check for the price parameter, which might take us some time to figure out.
Imagine how much clearer the code is if we saw:
const totalPrice = price + tax;
/* ... */
if (typeof totalPrice !== 'number') {
throw new Error('Invalid purchase price');
}
We'd know now that we need to check both the price and tax parameters.
This is the sort of "confusing behavior" they're talking about and why discouraging the atypical practice can be valuable.

drawback in using array as parameter? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I always use one array arguments to a function whenever I need more then 3 parameter.
Example: Consider a function call like this.
processSecondStage($stepTitle, $round, $entryId, $formId, $stepType, $stepAfterApproved, $assigneees, $stageToMove);
I always prefer the below one.
processSecondStage(array(
'stepTitle' => $title,
'round' => $round,
'stepAfterApproved' => $stepAfterApproved,
'entryId' => $_entryId,
'assigneees' => (array)$_POST['flow-asignee'],
'stageToMove' => $currentStep,
'formId' => $targetFormId,
'stepType' => 'approval'
));
Advantage (I might be wrong):
a) Can add more number of parameter
b) Readability
c) Order can be changed easily
d) Default parameter handling is easier
Disadvantage :
a) Code length is increase specially in case when we have less then 3-4 arguments.
Can anyone please help me Know more disadvantage of using the array parameter ?
Whenever I change other developer code (like I am going to do now), then I feel that there are some major disadvantage of using array as parameter because if that was not the case then it should have been a standard practice.
Although I have given example of PHP, but I find this in other language also on which I work.
Thank You.
Arrays are useful as a parameter when things you want to pass are closely related and do not make sense separately. A classical example is a Color that is defined by blue, green, red (and maybe gamma). Combining these parameters into an array (or object in javascript) allows you to swap it out easily.
Always using an array as the single parameter of a function makes you loose out on a parameter list an IDE can give you. For someone reading the code, it is quite a hell to figure out what needs to be passed to a function. It also opens the door to future creep (oh, this function was only making me coffee, but if I add another optional parameter it can also make me tea. Oh, and maybe I can let it make me dinner to. Why not add the functionality to order an attack helicopter too).
In a regular parameter list you can pass things by reference (function pushElement(array &$sortableArray, $element)). This is not expected in a regular array, if it is even possible.
The point about default values is kind of a moot point. Normal parameter lists allow type hinting and default values just fine:
function action(string $action = 'tickle', string $target = 'Polar bear') {
print "I {$action} a {$target}";
}
A single parameter as array probably only really shines when passing some kind of static configuration. You keep the configuration of something separate from the actual code using it, making it easier to modify the configuration. At the same time you leverage the fact that you do not have to send 20 parameters in a very specific order.
In your case the parameter list you give is wildly varied and long, which suggests that your function is doing way too much. Part of it should probably be moved to a constructor and part of it should probably be moved to some kind of Form class.
Parts of the topic are very much opinionated...
The problem you describe is not just parameters as a list vs a sequence of parameters. There are several problems that occur (with both in your example).
Tooling
Ordering of parameters
Semantics
Tooling is probably obvious: If you have only arrays as parameters, no IDE will know what is supposed to be inside. Okay, most IDEs won't know.
Ordering of parameters is usually dictated by the name of the function and/or its semantics. If you drawLine the canonical order of the parameters is ($from, $to). If there is no canonical order, there might be something else wrong with the code... (see below)
Semantics: If you have 3+ parameters (especially if you have way more), it is very likely, that the abstraction is wrong. For example let's assume you have a function createShirt($size="m", int $red, int $blue, int $green, Image $logo, $material="wool"): The order of attributes is arbitrary and the object produced (a shirt) may not need all of those parameters, but you can absolutely use this abstraction. I would much prefer the builder pattern, example:
$shirt = ShirtBuilder::create("m") // verifies m is a size
->setColor(new Color($red,$green,$blue)) // has type-hint color
->setImage($logo) // has type-hint
->setMaterial($material)
->build();
It absolutely is more verbose, but it is apparent you only have to call functions that are needed, you can validate set values at any point (read: function call). The build function could verify that the combination is valid and the Shirt object itself could even be immutable.
However, arrays absolutely do have their place and purpose. But usually it is "providing a list of things of the same type". If your array has only string-keys that are from a very small domain, you probably want an object.
Using objects will trigger questions such as "which parameters should belong to this object?". if there is no semantic reason for a true subset of parameters to appear together, you probably want the command pattern (command objects). and IDEs might provide all the wonders that make using those easy
tl;dr:
Using arrays to hold a list of heterogeneous parameters is probably an anti-pattern (might be warranted in some scenario/language).
Functions/methods with more than 3 parameters suggest too little abstraction (there might be reasons). Use appropriate design patterns.

How secure a method should be? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
As I am writing some code, I am wondering how secure my methods should be. Should I trust the user of my class ? Or check everything ? This implies parameters type checking which may not be a good practice as Javascript is supposed to be duck typed.
Basically this leads to the question of trust. Is there a best practice ? Is there an implicit "contract" ?
Example :
CarsCollection.prototype.get = function ( index ) {
return this.collection[index];
};
Or
CarsCollection.prototype.get = function ( index ) {
var self = this;
if ( ! index ) {
throw new ReferenceError();
}
if ( isNaN ( index ) ) {
throw new TypeError();
}
return self.collection[index];
};
You'll find out how robust your methods are by unit testing them. If you write good tests, you'll quickly find that your methods need to be able to handle all kinds of wack input.
It is up to you how far you want to go, but to be clear: don't just assume that the inputs will be valid.
Personally, I validate the hell out of anything that is coming from another class/module/whatever, even if its not third party. You need to make sure that the entry points to each module are robust. I relax a little more within a given class/module, but still make sure to validate enough to prevent errors.
In your sample code, it looks like other pieces of code outside of CarsCollection will be calling the get method. So, you'll want to validate index for sure.
In general things like framework code and reusable libraries are the prime candidate for extensive argument checking because you (and your current and future colleagues) going to use this code a lot.
You don't have to add argument checks everywhere, just use them when it's sensible.
If you want to specify certain behaviour like: should array_delete_value modify the input argument or return a copy with the value removed? Specify it in the comments and add a test that tests for exactly this behaviour.
If you're worried about performance you can write assert-like statements and remove them in your minification step. This is analogous to compiling with asserts off.
Asserts could look like:
argument("index", index).of_type("number").required();
If you downvoted, could you please leave a comment. Did I miss something? Do you have a competing methodology?
I like to make my code as dummy-proof as possible. This reduces the number of WTF's elicited by developers using my API/function/code. Argument-checking is always a good practice, especially in a dynamically-typed language like JavaScript. So there is nothing wrong with what you are doing. Type checking is permissible in JavaScript also. I find it easier to keep track of a function that explicitly states the types of its arguments. This lessens the cognitive load on the user of your API (i.e., not having to deal with foo(5) and foo("5")) and also lessens your own cognitive-load when you are writing the function since you won't have to deal with the idiosyncrasies of JavaScript's types and can be sure that an argument is the type that you expect.
While this doesn't exactly answer your question, it's important to note that the looseness of javascript makes many of your issues a non-issue (unless you want them to be).
If index is falsey, and you look at collection[index], you'll simply get undefined. I'm honestly not sure if that's a feature of arrays/objects or if the falsey value got coerced to a 0, but either way, it's not officially an error.
If index is not a number, the bracket notation will fall back from looking for an array member to an object property. In the worst case, it will return undefined, but in the best case, you can use the dynamic capabilities of objects to your advantage.
Realize that your current check will fail on CarsCollection.get(0), since 0 is falsey.
Also, isNaN handles if its parameter is null or undefined.
So neither of the things you check for are an error. If it was a fatal error, JavaScript would throw an error itself.
Now, to the question itself, my opinion is that javascript is so loose and uncontained, that most checking is unnecessary. If the using function passes bad parameters, the other programmer should figure out why. It's not like you can hide your code from them. The thing I value most is good documentation (check out jsdoc, then use it). If you define your interface well, the programmer can use it. That's just IMO, though.

javascript code obfuscation tool [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
Is there a recommended javascript code obfuscation tool?
I have searched it in stackoverflow,and someone suggest the 'YUI compressor'.
However it just do the following:
remove the annotatation/white space/new line
replace local variable
or something ele.
But It does not replace the property of one object.
Say I have a code like this:
var a=obj.fun();
var b=obj.pro;
I want something like this:
var xxx,yy,zz;
xxx=obj['yy']();
yy=obj['zz'];
Then even people re-format my code,he can not even know the propery/methods of one object unless he re-do the method/property replacement.
This is just an example, I just want the tool do more obfuscation other than just compress.
Any suggestion?
Try the Google Closure Compiler. In advanced mode it also refactors parts of your code and creates some performance improvements that way.
Javascript is a dynamically typed language, interacting with the browser, so it's almost impossible to do a proper analysis to find where an object can pop up in the code.
For these reasons you cannot safely rename the properties of an object.
You should try the google closure compiler, it provides three levels of writing:
The first one is WHITESPACE_ONLY
The second one is SIMPLE_OPTIMIZATIONS
The third one is ADVANCED_OPTIMIZATIONS
WHITESPACE_ONLY removes comments, trim line breaks and unnecessary spaces. The output code is identical to the source JavaScript.
SIMPLE_OPTIMIZATIONS also renames local variable and function parameters.
ADVANCED_OPTIMIZATIONS is the most aggresive, besides the optimization in the above two levels, it also does:
global variable renaming
remove uncalled functions
function inlining
For the give example:
//INPUT CODE
function unusedFunction(note) {
alert(note['text']);
}
function displayNoteTitle(note) {
alert(note['title']);
}
var flowerNote = {};
flowerNote['title'] = "Flowers";
displayNoteTitle(flowerNote);
WHITESPACE_ONLY result is :
//WHITESPACE_ONLY OUTPUT CODE
function unusedFunction(note){alert(note["text"])}function displayNoteTitle(note){alert(note["title"])}var flowerNote={};flowerNote["title"]="Flowers";displayNoteTitle(flowerNote);
SIMPLE_OPTIMIZATIONS result is:
//SIMPLE_OPTIMIZATIONS OUTPUT CODE
function unusedFunction(a){alert(a.text)}function displayNoteTitle(a){alert(a.title)}var flowerNote={title:"Flowers"};displayNoteTitle(flowerNote);
ADVANCED_OPTIMIZATIONS result is:
//ADVANCED_OPTIMIZATIONS OUTPUT CODE
alert("Flowers");
I think the SIMPLE_OPTIMIZATIONS and ADVANCED_OPTIMIZATIONS meet your need.
with my limited knowledge on this subject. I would like to suggest the google closure compiler:
http://code.google.com/closure/compiler/docs/api-tutorial3.html
It says there that they do property renaming

Categories