Naming convention to use for singletons in javascript [duplicate] - javascript

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I know there is a lot of controversy (maybe not controversy, but arguments at least) about which naming convention is the best for JavaScript.
How do you name your variables, functions, objects and such?
I’ll leave my own thoughts on this out, as I haven’t been doing JavaScript for long (a couple of years, only), and I just got a request to create a document with naming conventions to be used in our projects at work. So I’ve been looking (googling) around, and there are so many different opinions.
The books I’ve read on JavaScript also use different naming conventions themselves, but they all agree on one bit: “Find what suits you, and stick to it.” But now that I’ve read so much around, I found that I like some of the other methods a bit better than what I’m used to now.

I follow Douglas Crockford's code conventions for JavaScript. I also use his JSLint tool to validate following those conventions.

As Geoff says, what Crockford says is good.
The only exception I follow (and have seen widely used) is to use $varname to indicate a jQuery (or whatever library) object. E.g.
var footer = document.getElementById('footer');
var $footer = $('#footer');

You can follow the Google JavaScript Style Guide.
In general, use functionNamesLikeThis (lower camel case), variableNamesLikeThis, ClassNamesLikeThis (upper camel case), EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS.
See a nice collection of JavaScript Style Guides And Beautifiers.

One convention I'd like to try out is naming static modules with a 'the' prefix. Check this out. When I use someone else's module, it's not easy to see how I'm supposed to use it. E.g.,
define(['Lightbox'],function(Lightbox) {
var myLightbox = new Lightbox() // I am not sure whether this is a constructor (non-static) or not
myLightbox.show('hello')
})
I'm thinking about trying a convention where static modules use 'the' to indicate their preexistence. Has anyone seen a better way than this? It would look like this:
define(['theLightbox'],function(theLightbox) {
theLightbox.show('hello') // Since I recognize the 'the' convention, I know it's static
})

I think that besides some syntax limitations; the naming conventions reasoning are very much language independent. I mean, the arguments in favor of c_style_functions and JavaLikeCamelCase (upper camel case) could equally well be used the opposite way; it's just that language users tend to follow the language authors.
Having said that, I think most libraries tend to roughly follow a simplification of Java's upper camel case. I find Douglas Crockford advice tasteful enough for me.

That's an individual question that could depend on how you're working.
Some people like to put the variable type at the beginning of the variable, like "str_message". And some people like to use underscore between their words ("my_message") while others like to separate them with upper-case letters ("myMessage").
I'm often working with huge JavaScript libraries with other people, so functions and variables (except the private variables inside functions) got to start with the service's name to avoid conflicts, as "guestbook_message".
In short: English, lower-cased, well-organized variable and function names is preferable according to me. The names should describe their existence rather than being short.

Related

Reasoning behind the default jQuery alias ($) [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I've been thinking a lot about the way that jQuery is implemented in Javascript code. Libraries such as jQuery and Prototype bind to an alias by default; for these examples, they use the dollar sign $. (Underscore, appropriately, uses an underscore character _.)
I understand how this works. I also understand that many libraries provide a noConflict mode.
My question is, why do these libraries use an alias by default?
From what I've seen, aliases like these only seem to let a programmer type less characters when calling a function, which seems trivial. (Honestly - I'm a little biased, because I don't have issues typing long variable names.) I thought that maybe it was for filesize purposes, but with the proliferation of minifiers, it seems like it'd be a moot point (and a form of premature optimization).
On the flip side, the aliases seem to cause a lot of confusion for people using these libraries.
Now, I'm not really arguing against the use of aliases - I'm just wondering why it's the default option for these libraries. Currently, to avoid an alias, we explicitly have to declare that we don't want to use it. Are there specific benefits that I'm missing about the use of aliases for library calls? The only advantage that I could readily think of is if you somehow wrote cross-library code - to swap libraries, you simply swap the alias. I don't think I've ever seen this done, though.
Anyone know the reasoning behind this? I, for one, would really love to know.
"From what I've seen, aliases like these only seem to let a programmer type less characters when calling a function, which seems trivial."
That's what the people who designed VB thought too. "What's this
for (int i=0; i<10;i+=2){
}
Stuff! What's wrong with:
For i as Integer = 0 To 10 Step 2
Next i
So I save 13 keystrokes! That's trivial."
It's not trivial when this is what we do all. day. long.
Take the jQuery Cycle plugin: http://malsup.github.com/jquery.cycle.all.js. It has 400 instances of $. If you were to use jQuery instead of $, that would be an extra 2000 keystrokes. It's the reason why IDEs now perform autocomplete of parens, etc. etc. etc.
Using jQuery and Prototype together is not good idea. Ideally there must be only 1 javascript framework for the site, and a lot of calls to it. So the best (default) choice is to use shorthand alias for it's main function.
Anyway, if you need to use several libraries/frameworks together on the same page, and you want to avoid conflicts, you can use noConflict mode.

How specific should my classes in a game be? (Or anywhere else for that matter) [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I made two games so far, one was a simple 2D MMO, and another one was a 2D portal clone with some more features.
Anyway, I noticed that my class design in those two games varied a bit:
In the MMO, I'd create a class called "Enemy", and this class would take some arguments such as image and attack_power.
In the Portal-like game, I'd create classes for every kind of object specifically, for example "Box" or "Wall" or "Doors". Then, these would take only position as an argument, and inside I'd flag them for movable, physics with true/false, and then I would have an update function which would act upon these objects.
What is the best approach to this kind of problem? How specific should I be, and should I use something completely different?
I made those games in Python and Javascript.
That depends on the purposes of each class, on the language which you're using, on what you're trying to achieve, the specific problems you're trying to solve, and a zillion other factors - every problem and every program is different.
I'd recommend doing some research around the SOLID prinicples of OO design, these principles are more like guidelines than rules, but understanding them and being able to apply them to a real problem might help you achieve 'good' class design - http://davesquared.net/2009/01/introduction-to-solid-principles-of-oo.html
There is no "best" approach, since there are no universal right or wrong ways to solve a problem, and a perfect solution is not always possible or desirable when you factor in other real world issues which you might come across along the way.
The kinds of questions you might think about asking yourself could be along the lines of
What does my program actually do? Often, the most useful classes emerge when you start to think about the way your program works. For example, your movable Box class may end up doing very little to the point where it's easier to represent it as a simple struct, but you might find a use for a BoxMover class which is packed full of 'move' logic, and knows how to move Boxes around.
How do the different entities in my program behave? You don't mention very many details about your classes, so only you would know whether they do different things, but if you end up with dozens of almost-identical classes (particularly where the differences are restricted to data) then you may have gone too far.
What do I actually want to do with the classes? Its important to think about interfaces; the focus of OO design is more about the way your classes are used than the data which your classes store. (e.g. contrary to popular belief, a Square may have absolutely nothing in common with a Rectangle). Likewise, a class which has nothing more than single-line get-set functions for its interface is probably not making your life any easier, or bringing you any closer to finding a good solution.
What is the best approach to this kind of problem?
Some game developers would say that OOP is not the type of programming you would use for games. They would have a global data store, and use procedural code to access the global data store.
You're the only one who can really answer this question. Did your classes help or hinder your game programming?
How specific should I be, and should I use something completely different?
As specific as you need to be to model the game. In my opinion, since you finished the games, you had a good model. As you get more development experience, you'll have seen more models that you can use.

hashbang slash or no slash? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
Should we do site.com/#!/blog or site.com/#!blog?
I understand there's no actual difference, however as a community of webdevelopers there should still be a conventional standard so that users can easily remember the url. If there's no already established standard, ideally someone will post an answer in favor of one and someone will post another in favor of another and one will get a lot more votes than the other...
Personally I prefer: site.com/#!blog simply because it's shorter. However I've seen many other sites use the other variant.
By the way, if your first instinct is to instruct us to not use hashbangs, then this question is not for you, please leave us alone.
You forgot the third option of site.com#!blog.
If you want to get all semantical, the question becomes "what does a '/' represent in a url?"
Does it represent a physical
directory? [site.com#!blog]
When navigating a file system, folders are separated with slashes. This is the natural behavior on the web as well, but routing has changed this.
Does it represent a hierarchy of
content? [site.com/#!blog]
outing introduced hierarchy of content. Instead of question marks and ampersands, query vars were separated with slashes creating a deep link structure based on what the developers feel is important.
Does it represent a separation of
context within your url? [site.com/#!/blog]
Stack Overflow is a good example of what I mean by "separation of context". The URL of this question is [http://stackoverflow.com/questions/5414972/hashbang-slash-or-no-slash/]. The slash between the question ID and the question title isn't there because there is a file inside a folder named 5414972. There is only one question with the ID 5414972 so it isn't necessary for hierarchy either. It was a conscious choice to use a slash to separate the ID and the name rather than using any other delimiter such as a hyphen, underscore, or even no delimiter at all. A delimiter that isn't a slash would probably make the two variables resemble one. By putting slashes on either sides of the hash bang, the url becomes:
url prefix > ajax crawling notation > the specific page
rather than
url prefix > ajax crawling notation and the specific page.
Depending on what you answer yes to (and yes, it's subjective), you will have your answer. I think it's a little silly to try and get the entire world to agree on a standard for this when we still can't decide on how we should format dates.
As for that last little comment about resentment towards the "hash bang", I think you are imagining this. Who wouldn't like "hash bangs" when they sound so similar to "flash bangs"?
One slash is like one ant: when you see it, you expect to see another.
site.com/#!/blog is correct iff there's a site.com/#!/blog/latest , site.com/#!/blog/archive/october, or something like that in our future.
Just my €0.014185.
This depends on what you're doing. If you are basically just trying to ajaxify your site structure, then IMO it makes sense to include that root /, so /#!/blog. Popups, jumping through tabs, etc can use the other structure.
I don't believe there should be a conventional standard for this. There's a reason such tools as mod_rewrite exist: there are infinite solutions to infinite problems and attempting to standardize something as complex as URLs is impossible.
Also, for anyone wondering what a legitimate use is for hashbangs: http://code.google.com/web/ajaxcrawling/
An advantage of using the slash is easier parsing. Without having to worry about whether a particular browser returns a "" or a "#" in case of a missing ("") or empty hash ("#"), you can simply take the first slash as your starting point: You don't have to worry about what's before it.
var tokens = window.location.hash.split("/").shift();
tokens becomes an array of tokens with [#]! already out of the way. Especially handy when you use a hierarchy of slash-delimited tokens in your hashes.
But of course, you should still check the stripped token to make sure it is a valid hashbang.

JavaScript naming conventions [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I know there is a lot of controversy (maybe not controversy, but arguments at least) about which naming convention is the best for JavaScript.
How do you name your variables, functions, objects and such?
I’ll leave my own thoughts on this out, as I haven’t been doing JavaScript for long (a couple of years, only), and I just got a request to create a document with naming conventions to be used in our projects at work. So I’ve been looking (googling) around, and there are so many different opinions.
The books I’ve read on JavaScript also use different naming conventions themselves, but they all agree on one bit: “Find what suits you, and stick to it.” But now that I’ve read so much around, I found that I like some of the other methods a bit better than what I’m used to now.
I follow Douglas Crockford's code conventions for JavaScript. I also use his JSLint tool to validate following those conventions.
As Geoff says, what Crockford says is good.
The only exception I follow (and have seen widely used) is to use $varname to indicate a jQuery (or whatever library) object. E.g.
var footer = document.getElementById('footer');
var $footer = $('#footer');
You can follow the Google JavaScript Style Guide.
In general, use functionNamesLikeThis (lower camel case), variableNamesLikeThis, ClassNamesLikeThis (upper camel case), EnumNamesLikeThis, methodNamesLikeThis, and SYMBOLIC_CONSTANTS_LIKE_THIS.
See a nice collection of JavaScript Style Guides And Beautifiers.
One convention I'd like to try out is naming static modules with a 'the' prefix. Check this out. When I use someone else's module, it's not easy to see how I'm supposed to use it. E.g.,
define(['Lightbox'],function(Lightbox) {
var myLightbox = new Lightbox() // I am not sure whether this is a constructor (non-static) or not
myLightbox.show('hello')
})
I'm thinking about trying a convention where static modules use 'the' to indicate their preexistence. Has anyone seen a better way than this? It would look like this:
define(['theLightbox'],function(theLightbox) {
theLightbox.show('hello') // Since I recognize the 'the' convention, I know it's static
})
I think that besides some syntax limitations; the naming conventions reasoning are very much language independent. I mean, the arguments in favor of c_style_functions and JavaLikeCamelCase (upper camel case) could equally well be used the opposite way; it's just that language users tend to follow the language authors.
Having said that, I think most libraries tend to roughly follow a simplification of Java's upper camel case. I find Douglas Crockford advice tasteful enough for me.
That's an individual question that could depend on how you're working.
Some people like to put the variable type at the beginning of the variable, like "str_message". And some people like to use underscore between their words ("my_message") while others like to separate them with upper-case letters ("myMessage").
I'm often working with huge JavaScript libraries with other people, so functions and variables (except the private variables inside functions) got to start with the service's name to avoid conflicts, as "guestbook_message".
In short: English, lower-cased, well-organized variable and function names is preferable according to me. The names should describe their existence rather than being short.

What good is JSLint if jQuery fails the validation [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
So I have been exploring different methods to clean up and test my JavaScript. I figured just like any other language one way to get better is to read good code. jQuery is very popular so it must have a certain degree of good coding.
So why when I run jQuery through JSLint's validation it gives me this message:
Error:
Problem at line 18 character 5:
Expected an identifier and instead saw
'undefined' (a reserved word).
undefined,
Problem at line 24 character 27:
Missing semicolon.
jQuery = window.jQuery = window.$ =
function( selector, context ) {
Problem at line 24 character 28:
Expected an identifier and instead saw
'='.
jQuery = window.jQuery = window.$ =
function( selector, context ) {
Problem at line 24 character 28:
Stopping, unable to continue. (0%
scanned).
This was done using JSLint and jquery-1.3.1.js
JSLint tests one particular person's (Douglas Crockford) opinions regarding what makes good JavaScript code. Crockford is very good, but some of his opinions are anal retentive at best, like the underscore rule, or the use of the increment/decrement operators.
Many of the issues being tagged by JSLint in the above output are issues that Crockford feels leads to difficult to maintain code, or they are things that he feels has led him to doing 'clever' things in the past that can be hard to maintain.
There are some things Crockford identifies as errors that I agree with though, like the missing semicolons thing. Dropping semicolons forces the browser to guess where to insert the end-of-statement token, and that can sometimes be dangerous (it's always slower). And several of those errors are related to JSLint not expecting or supporting multiple assignments like jQuery does on line 24.
If you've got a question about a JSLint error, e-mail Crockford, he's really good about replying, and with his reply, you'll at least know why JSLint was implemented that way.
Oh, and just because a library is popular doesn't mean it's code is any good. JQuery is popular because it's a relatively fast, easy to use library. That it's well implemented is rather inconsequential to it's popularity among many. However, you should certainly be reading more code, we all should.
JSLint can be very helpful in identifying problems with the code, even if JQuery doesn't pass the standards it desires.
JSLint helps you catch problems, it isn't a test of validity or a replacement for thinking. jQuery is pretty advanced as js goes, which makes such a result understandable. I mean the first couple of lines are speed hacks, no wonder the most rigid js parser is going have a couple of errors.
In any case, the assumption that popular code is perfectly correct code or even 'good' is flawed. JQuery code is good, and you can learn a lot of from reading it. You should still run your stuff through JSLint, if only because it's good to hear another opinion on what you've written.
From JSLint's description:
JSLint takes a JavaScript source and scans it. If it finds a problem, it returns a message describing the problem and an approximate location within the source. The problem is not necessarily a syntax error, although it often is. JSLint looks at some style conventions as well as structural problems. It does not prove that your program is correct. It just provides another set of eyes to help spot problems.
JSLint defines a professional subset of JavaScript, a stricter language than that defined by Edition 3 of the ECMAScript Language Specification. The subset is related to recommendations found in Code Conventions for the JavaScript Programming Language.
"jQuery is very popular so it must have a certain degree of good coding."
One would like to hope this is the case with jQuery, but unfortunately it's not really true. jQuery is useful and popular, but it is not a well written JavaScript library. David Mark recently posted a scathing critique of jQuery in comp.lang.javascript that examines a large number of examples of the poor code found in jQuery:
http://groups.google.com/group/comp.lang.javascript/msg/37cb11852d7ca75c?hl=en&
If you're not actively developing jQuery itself, why even run JSLint over it at all? If it works, it works, and you don't have to worry about it.
The jQuery developers' goals are not the same as your goals. jQuery is built for speed and compactness and achieving those goals trumps readability and maintainability.
Crockford's tests in JSLint have more to do with achieving something that he would feel comfortable taking home to meet his mother, which is a valid concern if you will be married to your code for some time.
The purpose of JsLint is clearly stated in the FAQ [1]:
"JSLint defines a professional subset of JavaScript, a stricter language than that defined by Edition 3 of the ECMAScript Language Specification. The subset is related to recommendations found in Code Conventions for the JavaScript Programming Language."
Now if you are confused: ECMA3 is already a subset of the JS capabilities provided by any of todays JS interpreters (see [2] for an overview of the relation between JavasScript and ECMAScript versions)
To answer the quesition "what good is JSlint":
* use JsLint to verify you are using a "safe" subset of Javascript that is unlikly to break accross JS implementations.
* use Jslint to verify you followed the crockford code conventions [4]
[1] http://www.jslint.com/lint.html
[2] https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/JavaScript_Overview#Relationship_between_JavaScript_Versions_and_ECMAScript_Editions
[3] https://developer.mozilla.org/en/New_in_JavaScript_1.7#Avoiding_temporary_variables
[4] http://javascript.crockford.com/code.html
I've found one case where JSLint is very, very useful: when you grab one of those big-arse libraries that float around the 'Net, then another, then again one other, you soon find yourself loading 50k of Javascript on every new page load (caching may help, but it's not a cure-all solution).
What would you do then? Compress those libraries. But your host doesn't do compression for non-html file! So what? You use a Javascript compressor.
The best I've found is Dean Edward's; I used it to compress John Fraser's Showdown (a Markdown for Javascript library), but unfortunately, the compression broke the code. Since Showdown isn't supported anymore, I had to correct it myself - and JSlint was invaluable for that.
In short, JSlint is useful to prepare your JS code for heavy duty compression.
If you like to daisy-chain methods like jQuery allows you, you might appreciate YUI3.
JQuery is of course not the best thing in the world. That's already clear when you look at the notation. The dollar parentheses combination is really bad for your eyes. Programming should be clear and simple. JQuery is far from that. That reason is enough for me not to use it. That it's not properly written doesn't surprise me and only underscores my thoughts on this JavaScript library.

Categories

Resources