Jump to content

Best Practices


retro-starr

Recommended Posts

I'm curious to find out what people think are the best practices for programming, so I give you this thread! I'd also like to see the reasoning behind your choice.FunctionsThis, I think, is for when you do javascript from the URL, but also as a good visual aid to see where a function or statement ends.

function NAME(){ CODE;};

Switch statementsThis resembles an if statement to me, since you've learned if statements you'd know to put your expression between the parenthesis.

switch(){ case ():  {   CODE;   break;  } default:  {   CODE;  }};

ArrayThe last comma is really optional, but I feel that it gives the sense of possible expansion.

var NAME = [ "VALUE", "VALUE",];

QuotationsSingle vs Double Quotations:If you follow bash scripting nomenclature, singles are used for literal strings and double is used for variables. Now I'm on the fence with this as I'm from a batch scripting background where this wasn't any single quotations so I naturally put double, but if we want to make more javascript like other languages I think this could be a subtle place to do it.

Link to comment
Share on other sites

SpacingTabs vs Spaces:This one is really up-for-grabs; English MLA format says that you use 5 spaces = 1 tab; major projects like Asterisk use 4 spaces = 1 tab; I just use 1 space. The problem with mine is that notepad++ won't do the nice visual lines to help you see the tab formatting, but you save file size. I really thing tabbing is too much, so I think the optimal range would be 2 spaces as it's a nice even number and gives enough visual aid so you can quickly spot the beginning and end.

Link to comment
Share on other sites

FunctionsFor JavaScript that is intended to be used in the URL, I find it a best practice to say that explicitly with the "javascript" URL scheme (to avoid potential redirects to non existant pages or plain user/developer confusion), and then only have a single function be executed at that point. If the function needs to also be declared at the point (i.e. be used only on that spot), self executing anonymous functions are the most appropriate thing to use, i.e.

java script:(function() {/*JavaScript code here*/})();

(omitting the space between "java" and "script" of course)SwitchI don't use parenthesis around cases, as they're needless (everything up to ":" is a single expression, so there's no priorities to worry about, as may be the case with a ternary operator for example) and IMHO make the code less readable in the case of "case" (subconciously I'm thinking "Is that a ':' after a control strucure? Wasn't there supposed to be a "{" here instead? Oh wait, it's case... case needed ':'." and that's a lot of thinking per "case").Last commaWhether we're talking arrays or object literals, the last comma is actually forbidden, but is forgiven by most browsers. Same deal with omitting ";" after statements and omitting "var" in front of variable declarations - browsers forgive those things, have a de facto standardised behaviour if you do them, but those things are (or on the very least "were") forbidden by the spec, and are therefore not best practices.QuotesI usually use single quotes being influenced from PHP, and I've used JavaScript too little to notice or care about a difference in the behaviour of single and double quotes... AFAIK, there's no such thing as "variable interpolation in strings" in JavaScript, so that doesn't play a role here as it does in PHP. [searching...] MDC doesn't speak of any difference, so I can only assume it's irrelevant in all cases which one you use, as long as you're consistent... I guess single quotes have the added benefit of making JavaScript code "attribute compatible" in that you can put it in an achors' "href" attribute with no escaping of quotes. Then again, you still need to escape "<", "&" and ">".SpacingI usually use tabs, but I'll switch to 4 spaces occasionally, as some coding standards would like it. I use tabs mostly because they're quickest to type and take least space, but in some communities they prefer spaces because different editors do different things with tabs in different places... well, all of the ones I've used make "tab" a synonym for "symetry", which always works out fine if your line starts off with nothing but tabs, and doesn't have tabs anywhere else. But seeing how in some coding standards developers prefer to make the sides of an equal sign be symetric across mutliple lines, I guess more often than not, a space indeed works out better in most editors for this case. Personally, I don't find a symetric equals sign to improve readability, and in fact can actually decrease it on some more extreme cases (where the space is so much that you end up reading all variables and values to make sure the one value you're checking is over the right variable).

Link to comment
Share on other sites

VariablesJust like boen_robot said, always declare variables. You can take it a step further and initialize (set them equal to null) them at the top of the document just like in C++ (prototyping), though this is extraneous.

var NAME = VALUE;

There is no way to void or null an already existing variable! Once you set it, you can't delete it, only replace it.

Link to comment
Share on other sites

VariablesDon't declare variables with the var. Every variable defined with it is a global variable thus meaning it can interfere with other scripts running. Instead create a namespace, an object to execute your script or to hold your variables.

var myScript1 = {  time: 203292,  day: "Monday",  myFruit: "Strawberry"}

Then when you want to use that variable you can just go myScript1.time.Brackets/BlocksWhen using brackets its better practise to put the first bracket on the same line as its statement.

var bark = function(){ alert("woof");}

It's better to do it like this because of Javascript's semicolon insertion (the mechanism that allows you to not have to put a semicolon at the end of each statement (Though you should!)).

return {  name: "Apoc"}

becomes

return;{  name: "Apoc"};

Thus ignoring the object to return.

Link to comment
Share on other sites

VariablesEven a "namespace" in the context of JavaScript is really a variable holding other variables, and THAT variable is to be declared with "var", so at least one use of "var" is basically a must.Personally, I think this namespace policy only makes sence if you plan on writing portable code i.e. a library (not necesarily a generic jQuery like library) or a plug-in for a library. For code that is to be there and now, you might as well write it there and now. Same goes for PHP, though in the case of PHP, naming collision with APIs and "code for now" is harder, since an API can enclose its stuff in classes at which point they're no longer subject to conflicts with variables (only with other classes).In JavaScript, if you aren't writing portable code and despite that want to make your parts not conflict with each other (e.g. if you have separate script elements that may contain variable names that may have been used by another script elements), you can wrap up each script part in an anonymous self executing function, i.e.

(function() {/*JavaScript code here*/})();

That way, when each such part is over, all variables within it will be destroyed.If you keep all of your "code for now" in a single script block like I do, using the above is redunant.Brackets/BlocksI can see how this makes sence for object literals, but it's irrelevant when it comes to function declarations. The difference between having the opening bracket in a function declaration on the same line or not is like the difference between a space and a tab - a matter of style.Still, I have to say that my preference is also having the "{" in function declarations on the same line, mostly because I find it slightly more readable. If a conding standard required me to write it otherwise, I'll bend though.As for the object literal, I'd generalize this into "Write the opening bracket of an object literal on the line on which the expression of which it is a part of is", e.g. write

return { name: "Apoc"};

instead of

return { name: "Apoc"};

Link to comment
Share on other sites

I've been writing C-style code since the 1980s, and I am accustomed to using tabs. I agree with the general principle that 1 tab is fewer characters than 3-5 spaces, which means that a script is more compact.And then I found myself switching code editors, and a lot of my tabs did not line up as planned, especially ones that I used to line up comments and such. So, depending on the project, I may use 3 spaces instead of a tab. If I forget, there is always global search-and-replace.I think it is madness not to use curly braces when a conditional or loop initializer is followed by only a single statement. For one thing, there's too much thinking involved. Should I do it? Should I not? If I always do it, then I'm always right. For another, it's entirely likely that I'll come back later and add more statements. I don't want to bother with also adding the braces.I set up curly braces in the old K&R style:

initializer {   statements;}

But only because I learned it that way. A lot of new styles have developed, and their users think they increase readability. I think it's what you're used to. No doubt the most important think is to be consistent.I got accustomed to semicolons writing C and Perl and now PHP, so it's hard NOT to write them. I also do a lot of snippet testing in my error console. It has only one line, so semicolons are required. If you haven't tried it, you can paste a LOT of code into your error console, so it's a nice convenience. But none of it will work without those semicolons.

Link to comment
Share on other sites

And then I found myself switching code editors, and a lot of my tabs did not line up as planned, especially ones that I used to line up comments and such. So, depending on the project, I may use 3 spaces instead of a tab. If I forget, there is always global search-and-replace.
*Has Python nightmares*
Link to comment
Share on other sites

And then I found myself switching code editors, and a lot of my tabs did not line up as planned, especially ones that I used to line up comments and such. So, depending on the project, I may use 3 spaces instead of a tab. If I forget, there is always global search-and-replace.
You mean like
statemet;[tab]//commentlongerStatemet;[tab]//comment

?Yeah, I've had that too... I usually use tabs only when indenting the line itself, not for indenting on the line. I'd use spaces for other cases, e.g. I'll have

if (expression) {[tab]statemet;[space][space][space][space][space][space][space]//comment[tab]longerStatement;[space]//comment}

Link to comment
Share on other sites

I think 1 space = 1 tab is much too little. The indentation is too subtle. I'm not sure what I use right now, but I'd suspect about 5 spaces = 1 tab. When I declare a function/logic statement--really anything that requires enclosure by curly braces--I prefer to put the first curly brace on the same line.

myFunc = function() {	 // function }if (...) {}switch(myVar) {}//multiple if statements:if (...) {} elseif (...) {} else {} //...it flows better for me.

Link to comment
Share on other sites

Crockford has made me feel bad for using the "bad parts".
haha me too. But I've been eliminating those very quickly by reading blogs on various JS patternsIf you want to learn good syntactical practices in JS, you should work with Crockford's JS compiler called JSLint. Also read the Appendix chapters of his book "The Good Parts" since he writes about what these practices are. The tool however doesn't look for efficiency and maintainability (like reducing global variables).For example, when declaring variables, it is best to declare them at the top of a function with one var statement so you dont run into hoisting issues. There is a good article on Nettuts about variable hoisting in JS.
Link to comment
Share on other sites

haha me too. But I've been eliminating those very quickly by reading blogs on various JS patternsIf you want to learn good syntactical practices in JS, you should work with Crockford's JS compiler called JSLint. Also read the Appendix chapters of his book "The Good Parts" since he writes about what these practices are. The tool however doesn't look for efficiency and maintainability (like reducing global variables).For example, when declaring variables, it is best to declare them at the top of a function with one var statement so you dont run into hoisting issues. There is a good article on Nettuts about variable hoisting in JS.
wow, that's pretty interesting article. I've tried to get in the habit of declaring/initializing all my variables at the top of the function/method too, although only for readability issues, but that makes a much more compelling argument. Thanks for sharing the link!On a side note, I've read The Good Parts too, but know I feel fondness over it after hearing everyone mention it and I think I want to read it again. To the OP, I just started reading this book recently, and I like it a lot as far as getting some insight into certain practices and good habits. It might give you a good amount of possible considerations, although I would take some of the authors suggestions with a grain of salt.http://www.amazon.com/Clean-Code-Handbook-...5754&sr=8-1
Link to comment
Share on other sites

haha me too. But I've been eliminating those very quickly by reading blogs on various JS patternsIf you want to learn good syntactical practices in JS, you should work with Crockford's JS compiler called JSLint. Also read the Appendix chapters of his book "The Good Parts" since he writes about what these practices are. The tool however doesn't look for efficiency and maintainability (like reducing global variables).For example, when declaring variables, it is best to declare them at the top of a function with one var statement so you dont run into hoisting issues. There is a good article on Nettuts about variable hoisting in JS.
I finished it the other day, I loved it, thats where most of my points are from.
Link to comment
Share on other sites

I felt The Good Parts was a bit confusing at times. Some parts were an easy read and others were not. I feel like I would have to read it again to understand some of the concepts that I brushed over, like augmenting native objects and inheritance.One thing that he kept saying in the book and in his video in the YUI theatre is that JS has a lot of expressive power. I still don't know what he means by 'expressive power'. Do any of you?

Link to comment
Share on other sites

If by "augmenting native objects" you mean reprototyping, sophox has a few words that might help.Naturally, if you Google "JavaScript expressive power," you get bunch of Crockford references. A kind of agreement I found, including Wikipedia, says it's the ability to do what you need to do with a minimum of fuss. Not all languages support regular expressions, or closures, or even self-executing functions, all of which make programming pretty nice. Can you imagine some of the crazy string matching you'd have to do without regex? Gah. Reprototyping simplifies a lot of things.Some things are more candy than useful, and some things are subject to taste. And I'm not sure if, say, all the built-in libraries that PHP has make it more expressive than JavaScript. That may be a level of abstraction beyond the stuff Crockford or anyone else means. Probably you want to look at the core of the thing.For another look, here's a widely-cited article on the subject.

Link to comment
Share on other sites

Yup, that is what I meant by augmenting native objects. I think that is how Crockford describes it too. Maybe they are just synonymous. That was a great article on re-prototyping. Rereading parts of the book might make more sense now. I like how Sophox first created isInt as a function and then reprototyped it as a method of the Number and String objects.Regarding best practices, you might want to read the book JavaScript patterns. I think it goes into the various ways of architecting JS in your applications for code maintainability, readability, scalability, and modularity. I just got the book so I haven't read much of it yet, but according to Rey Bango, he mentions it as one of the top books to read on his blog post of "Getting up to speed in JS".

Link to comment
Share on other sites

I don't end my functions with my return statements unless they need to return something, and a return statement won't always be necessarily at the end of a function. I'm not sure what you mean by your reference to expansion? You say it a lot. Good functions should do one thing, and do it well. They should not be looked at as things needing continued expansions to their scope of responsibility.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...