JavaScript coding guidelines

JavaScript coding guidelines

Andrew Lyons發表於
Number of replies: 23
Core developers的相片 Moodle HQ的相片 Particularly helpful Moodlers的相片 Peer reviewers的相片 Plugin developers的相片 Testers的相片

Hi all,

For the most part, our JavaScript style should mimic that of the general Coding style for Moodle as a whole, but sometimes we need to break away from that. This may be as a result of:

  • the different languages involved (JavaScript versus PHP);
  • different use-cases;
  • different technologies dealt with (e.g. dealing with User Interface components);
  • integration with a range of different third-party libraries involved; and
  • a variety of other miscellaneous reasons.

To that end, I've begun work on a new set of JavaScript coding guidelines for Moodle to try and create a codified set of rules, and guidelines for JavaScript development in Moodle.

The draft document, which is still a work-in-progress, is available on the developer wiki at http://docs.moodle.org/dev/Javascript/Coding_style. This is also raised in MDLSITE-1774 and once the draft is complete, it will be approved (or rejected) in that issue.

I've tried to provide appropriate rationale for many of these proposed changes and it's now at a stage where I believe that it's ready for some early feedback from the community.

There is a talk page for the document, but it would be easier to follow if any issues, suggestions, comments, or criticisms could be discussed in this thread instead so I'd ask that you not use that. For posterity, I'll include the comments to-date in that page in a reply to this forum post.

Thank you in advance,

Andrew

That link again: http://docs.moodle.org/dev/Javascript/Coding_style

評比平均分數: -
In reply to Andrew Lyons

Re: JavaScript coding guidelines

Andrew Lyons發表於
Core developers的相片 Moodle HQ的相片 Particularly helpful Moodlers的相片 Peer reviewers的相片 Plugin developers的相片 Testers的相片

The following is the current state of the Talk page for posterity and reference within this thread.




Thankyou Andrew for working on this - it is sorely needed.

Some points I think we need voting/consensus on:

 


"Contrary to the standard Moodle coding style, we prefer to use camelCase for JavaScript."

Agreed, this needs further discussion and clarification, but I feel it's one of the most important changes.

--Andrew Nicols (talk) 14:46, 16 October 2013 (WST)

"Contrary to the standard Moodle coding style, weAndrew Nicols prefers to use camelCase for JavaScript." You are going to have to work very hard to convince me this is a good idea. We use serveral third-party camelcase libraries in PHP too, and the world has not ended.--Tim Hunt (talk) 16:02, 16 October 2013 (WST)
"You are going to have to work very hard to convince me this is a good idea. We use serveral third-party camelcase libraries in PHP too, and the world has not ended." Thanks Tim. Yes, we may use lots of libraries in PHP which follow this guidance, but most of those libraries are fairly abstracted away and we rarely deal with them. Conversely, with YUI, every time you wish to change a setting for anything that YUI handles, you must use camelCase. With the nature of JS, we frequently have Moodle code sat right next to code changing YUI objects. If you use a Moodle dialogue, you're really using a YUI Panel + YUI Widget + Moodle magic. You're proposing making it such that developers have to use a combination of camelCase and moodlecase in code which sits side-by-side to modify the same object. Also, it's not just me that's wishing to use camelCase for JS. --Andrew Nicols (talk) 16:16, 16 October 2013 (WST)

"be spread across multiple lines for complex types (including all objects and arrays, no matter how simple"

I don't see this as a major sticker - since we minify all code going out now, there's no reason not to and it means that we can get the full blame history much more easily.

--Andrew Nicols (talk) 14:46, 16 October 2013 (WST)

Although you have this rule to make diffs better, in the Number of variable declarations section you have examples that make diffs worse. Can we make it consistent.--
I think it is crazy to require all object literals to be spread over multiple lines. It should be on a case by case basis. We allow that in PHP. Diffs might be clearer if we put a newline after every single token, but you wouldn't want to code like that. git can do quite nice diffs within lines anyway.--Tim Hunt(talk) 16:02, 16 October 2013 (WST)

Tim Hunt (talk) 16:02, 16 October 2013 (WST)


We could be more specific about which yuidoc tags are required (Where is @namespace required?)

That's a hard one - I don't think that we should duplicate the entire yuidoc syntax guide here but perhaps once we get these docs ratified and start to generate real YUIDoc, we will have more of an idea. @namespace isn't required at all, but it is useful in modules with submodules primarily.

--Andrew Nicols (talk) 14:46, 16 October 2013 (WST)

I agree. Just make the word YUIDoc a link to a separate page that explains (could even go to YUI's site.)--Tim Hunt (talk) 16:02, 16 October 2013 (WST)

 


with a maximum length of 150

Okay, that can probably be dropped... but we should make the value in our .jshintrc match the value we wish this to be (180 chars is the figure mentioned in the standard style IIRC)

--Andrew Nicols (talk) 14:46, 16 October 2013 (WST)


"In the case of object property assignation, there should be a space after the colon, but not before."

Property assignation is not really the same as an operator so I feel that these should be separate rules. Most JSON resources out there follow this standard -- see http://www.freeformatter.com/json-formatter.html#ad-output for example. Unless we have good reason, why should we break from this? It's also the format described by the RFC: http://www.ietf.org/rfc/rfc4627.txt (Section 8). Additionally, when writing in natural language, you don't write:

E-mail : fred@example.com

You write it as:

E-mail: fred@example.com

--Andrew Nicols (talk) 14:46, 16 October 2013 (WST)

What you propose is correct. Interstingly, some languages (e.g. French I think) do put a space before colons, so this is a cultural thing, but Moodle code is English.--Tim Hunt (talk) 16:02, 16 October 2013 (WST)

Some instructions on how to use YUIdoc / shifter to check the format of the JS/comments would be welcomed.

There is already documentation on how to use Shifter, and YUIDoc. We could admittedly do with more. If others wish to contribute, I'd very happy to have help there ;)

--Andrew Nicols (talk) 14:46, 16 October 2013 (WST)

In reply to Andrew Lyons

Re: JavaScript coding guidelines

Dan Poltawski發表於
Count me as another person against camel case. We get a lot of problems with developers naming things against Moodle style and I am not keen to see the ambiguity here between JS and php.

Actually, when reviewing drag and drop from Davo in lib/form/dndupload.js, we converted functions to all have underscores and variable names to all be lowercase longer words. The end result for me was that I found it much easier to understand the code (knowing Moodle style php well, and js not so well).

YUI uses camel case for functions and variable names and personally I find that tricker to understand and our rule to have underscores only in function names really helps with knowing what is what. Applying it to JS made me appreciate our _ rule more!

Again, looking at that lib/form/dndupload.js as an example, I don't see the interaction between YUI and moodle code to be particularly problematic.
In reply to Dan Poltawski

Re: JavaScript coding guidelines

Gareth J Barnard發表於
Core developers的相片 Particularly helpful Moodlers的相片 Plugin developers的相片

I actually like camelCase as have used it for years in Java, C++, VB.Net etc.

For example:

function calculateDesertCrossingTime(noOfCamels, dungLossPerHour)

is easier to read than:

function calculatedesertcrossingtime(noofcamels, dunglossperhour)

and shorter than:

function calculate_desert_crossing_time(no_of_camels, dung_loss_per_hour)

I have to switch from my normal coding style to 'Moodle Mode' twitch twitch ;).

Cheers,

Gareth

P.S. The examples in the YUI3 Cookbook (the bible for YUI 微笑 ) are camel case -> https://github.com/evangoer/yui3-cookbook/blob/master/examples/tools/test_case.js

In reply to Gareth J Barnard

Re: JavaScript coding guidelines

Dan Poltawski發表於

I have to switch from my normal coding style to 'Moodle Mode' twitch twitch ;).

Right, and so I think that having different rules for javascript and php will not help you stay in touch with Moodle style.

It is not a discussion on whether camelCase is a worthwhile practice for naming, its is a viable alternative to our current naming convention, used widely in the industry - but it is not the current Moodle style.

The point of the coding style is to be consistent and followed by all developers, no matter what their personal preference is.

評比平均分數:Useful (1)
In reply to Dan Poltawski

Re: JavaScript coding guidelines

Gareth J Barnard發表於
Core developers的相片 Particularly helpful Moodlers的相片 Plugin developers的相片
It is not a discussion on whether camelCase is a worthwhile practice for naming, its is a viable alternative to our current naming convention, used widely in the industry - but it is not the current Moodle style.

If camel case is "used widely in the industry" but is not the current Moodle style then why is that the case? Should Moodle follow industrial practice and standards or be in someways unique? Should Moodle coding style transition to that of general industry and thus reduce developer context switching?

In reply to Gareth J Barnard

Re: JavaScript coding guidelines

Tim Hunt發表於
Core developers的相片 Documentation writers的相片 Particularly helpful Moodlers的相片 Peer reviewers的相片 Plugin developers的相片

Many things can be used widely at the same time.

Engish is spoken widely. Spanish is spoken widely. That is not a reason for all English speakers to learn Spanish, or vice versa.

The lower-case with underscores coding style is widely used, just like camel case.

Acutally, it would be really intersting if an organisation with access to a lot of code (e.g. Ohloh or github) could find a way to count the user of CamelCase vs. under_scores, to see if either is really more common.

Also, I just found this interesting article: http://whathecode.wordpress.com/2011/02/10/camelcase-vs-underscores-scientific-showdown/. The follow up at http://whathecode.wordpress.com/2013/02/16/camelcase-vs-underscores-revisited/ comes out even more strongly in_favour_of_underscores.

評比平均分數:Useful (1)
In reply to Dan Poltawski

Re: JavaScript coding guidelines

Andrew Lyons發表於
Core developers的相片 Moodle HQ的相片 Particularly helpful Moodlers的相片 Peer reviewers的相片 Plugin developers的相片 Testers的相片

Thanks Dan,

I realise that this may introduce a little bit of ambiguity here, but I'd argue that there is already some ambiguity in play between ourselves and the upstream YUI project, so making a decisio here would clarify where the ambiguity lies. I'd prefer that we have a difference at the language barrier, rather than between us and a heavily exposed and highly used upstream library. I don't think it's unreasonable to impose slightly different standards between different languages (JavaScript and PHP).

Partially because of this language change, I don't think that too many developers will get confused if we are clear about the distinctions between the two. For newer developers who are looking at surrounding code when they make changes, the surrounding JS will be easier to follow if we use all camelCase rather than mixed camelCase and moodlecase; whilst our PHP is already fairly consistent.

Bearing in mind that functions are basically stored as variables in JavaScript, how would say that we fit into this Moodle coding guidelines?

It's possible to define a variable as one type (e.g. null, or a String) , and then redefine it as a function later, and then perform different actions dependent on the value of the variable name (e.g. a callback). While this may seem quite convoluted, you do see this quite frequently in YUI where we can provide a function, or a string, or a node as a selector - for example http://yuilibrary.com/yui/docs/api/classes/Node.html#method_next. If we use a variable to represent a selector, and we set different values for that selector based on various options, we could end up with a function stored in a non-underscored variable. Equally, we may start doing similar things for our code to make it easier for people to make use of our libraries. This would break with the current Moodle style guidelines so we need to address this anyway.

Andrew

In reply to Andrew Lyons

Re: JavaScript coding guidelines

Damyon Wiese發表於
Re CamelCase - well there is no ambiguity IMO - the coding style page has always applied to php and js as much as possible. That does not mean it has been followed.

I think that it's crazy to have different styles for JS and php. If you are mostly working on JS I can see that it may be desirable to match the YUI style because all of the YUI examples etc are written in that style - but when you have to jump between php and JS it is confusing and ugly to have different styles. The php style wasn't chosen to match any other style/library - it was chosen because it was decided that this is what made the code the clearest and most consistent. Apart from matching YUI style and individuals personal preference, both of which are irrelevant IMO, I don't see any reason that the js should be different from the php style.

-1000 for camel case.

In reply to Damyon Wiese

Re: JavaScript coding guidelines

Damyon Wiese發表於
Also - re: mixing styles when calling yui code from js code.

There are not so many cases when this occurs - because alot of the yui functions are only a single word - and even when they are not - the code does not look horrible because of this difference.

The module for editpdf I wrote strictly follows the moodle style for functions and the mixing of YUI and moodle functions in this module still looks readable and clear IMO:

mod/assign/feedback/editpdf/yui/src/editor/js/*

In reply to Andrew Lyons

Re: JavaScript coding guidelines

Dan Poltawski發表於

I don't think its an unreasonable suggestion, but I don't think the case is strong enough for divergence.

Like others have said, the ambiguity we have is from people not following the existing guidelines (and perhaps not making the point clearly enough that the same rules apply to JS).

Bearing in mind that functions are basically stored as variables in JavaScript, how would say that we fit into this Moodle coding guidelines?

With underscores - as I was trying to say above, I actually found using underscores to declare that this 'function' rather than a variable is in fact a method helped me personally with readability. Even in the case of a callback I think it works. An example of that from the drag and drop code: init_page_events: function() { this.Y.on('dragenter', this.drag_enter_page, 'body', this); this.Y.on('dragleave', this.drag_leave_page, 'body', this); },

I found that once we changed that those drag_enter_page and drag_leave_page to underscores, it really helped me see the callbacks better!

Can you provide a code example where you think this falls down?

In reply to Andrew Lyons

Re: JavaScript coding guidelines

Joseph Rézeau發表於
Core developers的相片 Particularly helpful Moodlers的相片 Plugin developers的相片 Testers的相片 Translators的相片

Which talk page are you talking about?

In reply to Joseph Rézeau

Re: JavaScript coding guidelines

Andrew Lyons發表於
Core developers的相片 Moodle HQ的相片 Particularly helpful Moodlers的相片 Peer reviewers的相片 Plugin developers的相片 Testers的相片

Sorry Joseph,

At Dan's suggestion I removed it. The comments which were there are now pasted above.

Andrew

In reply to Andrew Lyons

Re: JavaScript coding guidelines

Dan Poltawski發表於
Re: Documentation and comments

I'm not clear where the difference is to general Moodle style here? Like YUIdoc, we will auto-generate phpdoc documentation. So the rules about /**/ etc are the same. The only difference I can determine is the need to use YUIDoc syntax rather than phpdoc?
In reply to Dan Poltawski

Re: JavaScript coding guidelines

Andrew Lyons發表於
Core developers的相片 Moodle HQ的相片 Particularly helpful Moodlers的相片 Peer reviewers的相片 Plugin developers的相片 Testers的相片

There is not much of a difference, it's more that YUIDoc is fussier and will try to generate documentation for any docblock starting /**, and will ignore any which do not and I felt that this needed to be highlighted.

In reply to Andrew Lyons

Re: JavaScript coding guidelines

Jason Fowler發表於

The more I read the responses here, the more I find myself against the idea of keeping the Moodle Style over the YUI style. Although we will rarely modify the core YUI libraries, our javascript will be making calls to those functions already defined in camelCase. So to not use camelCase in our javascript will result in the JS being a mix of contributed_functions and libraryFunctions, with no way of reconciling the two.

So my vote goes to camelCase.

In reply to Andrew Lyons

Re: JavaScript coding guidelines

Jérôme Mouneyrac發表於

To me writing YUI code is quite different from writing PHP code. It make sense to me to write the Moodle YUI code with the YUI style. 

My hypothesis:
* YUI experts could be please to see Moodle follows the YUI coding style, it may encourage them to have a look to the Moodle YUI code.
* YUI beginners may be please to know that Moodle follows the YUI coding style so they can export their knowledge of the coding style on other YUI project
* to me it's easier to blame Moodle for having it's own YUI style than if it was following the YUI standards

Most of the JS code you'll find on Internet use camelCase too. So my vote goes to camelCase.

評比平均分數:Useful (1)
In reply to Andrew Lyons

Re: JavaScript coding guidelines

Andrew Lyons發表於
Core developers的相片 Moodle HQ的相片 Particularly helpful Moodlers的相片 Peer reviewers的相片 Plugin developers的相片 Testers的相片

Jerome has just asked me about other group's coding-style guidelines, particularly with respect to the camelCase debate.

Here are a selection from other major projects:

ECMA (Standards maintainer for JavaScript)

URLhttp://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf

Not explicitly defined, but examples of code all use lowerCamelCase

Douglas Crockford (author of JSON)

URL: http://javascript.crockford.com/code.html

Not explicitly defined, but he always uses lowerCamelCase for variables, with UpperCamelCase for constructors.

Mozilla

URL: https://developer.mozilla.org/en-US/docs/Developer_Guide/Coding_Style

Naming in general: CamelCase

Naming in JavaScript: lowerCamelCase (UpperCamelCase for constructors)

jQuery

URL: http://contribute.jquery.org/style-guide/js/

Variable naming in JavaScript: lowerCamelCase

Google

URL: http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml

Variable naming in JavaScript: lowerCamelCase for variables; UPPER_WITH_UNDERSCORES for constants

Variable naming in Objective C (http://google-styleguide.googlecode.com/svn/trunk/objcguide.xml#Variable_Names): lowerCamelCase

Variable namin gin C++ (http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Variable_Names): lower_with_underscores

Apple

URL: http://www.sourceformat.com/pdf/javascript-coding-standard-apple.pdf

Variable naming in JavaScript: Not specifically listed, but all examples use lowerCamelCase

Mahara

URL: https://wiki.mahara.org/index.php/Developer_Area/Coding_guidelines

Variable naming in PHP: lower_case_with_underscores (UpperCamelCase for classes)

Variable naming in JavaScript: Follows Douglas' Crockfords conventions (above)

MediaWiki

URL: http://www.mediawiki.org/wiki/Manual:Coding_conventions/JavaScript

Variable naming in PHP: lowerCamelCase (UpperCamelCase for class names)

Variable naming in JavaScript: lowerCamelCase (UpperCamelCase for constructors)

Drupal

URL: https://drupal.org/node/172169

Variable naming in PHP: lower_case_with_underscores

Variable naming in JavaScript: lowerCamelCase

Wordpress

URL: http://make.wordpress.org/core/handbook/coding-standards/javascript/

Variable naming in PHP: lower_case_with_underscores (never camelCase)

Variable naming in JavaScript: lowerCamelCase (UpperCamelCase for constructors)

 

Summary

All of the above projects use lowerCamelCase for their JavaScript, with several of them using other variants for other languages (primarily lower_with_underscore).

Helpfully, the YUI project does not explicitly state their variable naming preferences, but all examples use lowerCamelCase.

Andrew

評比平均分數:Useful (4)
In reply to Andrew Lyons

Re: JavaScript coding guidelines

David Monllaó發表於

Hi,

I'm with camelCase too. I don't think that this should be about how much I like one or the another, should be about make devs life easier and avoid mixing styles. In my opinion it makes more sense to have different coding styles for different languages than to mix lower_underscore + node.setHTML in the same language. We can not require XML files to use lower_underscore tag names...

Being used to work with ZF and Symfony moodle's coding style is not ideal, IMO we should avoid doing the same with JS.

In reply to Andrew Lyons

Re: JavaScript coding guidelines

Tim Hunt發表於
Core developers的相片 Documentation writers的相片 Particularly helpful Moodlers的相片 Peer reviewers的相片 Plugin developers的相片

OK. You have just convinced me. +1 camel case.

Now, can you get jshint or codechecker to check that?

評比平均分數:Useful (1)
In reply to Tim Hunt

Re: JavaScript coding guidelines

Andrew Lyons發表於
Core developers的相片 Moodle HQ的相片 Particularly helpful Moodlers的相片 Peer reviewers的相片 Plugin developers的相片 Testers的相片

JSHint has an option for testing camelCase: http://www.jshint.com/docs/options/#camelcase

This option allows you to force all variable names to use either camelCase style or UPPER_CASE with underscores.

We can enable it, but it will lead to a great number of linting errors because we haven't followed things til now. We will additionally need to provide a deprecation layer for any API functions we rename to inform other developers of the changes (easy).

In reply to Andrew Lyons

Re: JavaScript coding guidelines

Gareth J Barnard發表於
Core developers的相片 Particularly helpful Moodlers的相片 Plugin developers的相片

+1 for camelCase

And I know it's against the coding guidelines, but I think in general that variables should be allowed to have hyphens in them.  Some already do but when you have something meaningful like 'defaultimagecontainerbackgroundcolour' things can get a little harder to read!

In reply to Gareth J Barnard

Re: JavaScript coding guidelines

Andrew Lyons發表於
Core developers的相片 Moodle HQ的相片 Particularly helpful Moodlers的相片 Peer reviewers的相片 Plugin developers的相片 Testers的相片

Hi Gareth,

I'm afraid I'm 99.9% sure that isn't possible. Hyphens are punctuation, and under the ECMA specification, an identifier name cannot consist of punctuation, including hyphens. See the bottom of page 16 onwards of http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf.

Andrew

In reply to Andrew Lyons

Re: JavaScript coding guidelines

Gareth J Barnard發表於
Core developers的相片 Particularly helpful Moodlers的相片 Plugin developers的相片

According to page 17, underscores are allowed.  So that would be an option along with allowing them in the PHP guidelines too.