Coding Style

  • Revision slug: Developer_Guide/Coding_Style
  • Revision title: Coding Style
  • Revision id: 7371
  • Created:
  • Creator: Joey Armstrong
  • Is current revision? No
  • Comment 18 words added, 6 words removed

Revision Content

This document attempts to explain the basic styles and patterns that are used in the Mozilla codebase. New code should try to conform to these standards so that it is as easy to maintain as existing code. Of course every rule has an exception, but it's important to know the rules nonetheless!

This is particularly directed at people new to the Mozilla codebase, who are in the process of getting their code reviewed. Before getting a review, please read over this document and make sure your code conforms to the recommendations here.

General practices

  • Don't put an else right after a return. Delete the else, it's unnecessary and increases indentation level.
  • Don't leave debug printfs or dumps lying around.
  • Use Unix-style carriage returns ("\n") rather than Windows/DOS ones ("\r\n").  You can convert patches with DOS newlines to Unix via the 'dos2unix' utility, or your favorite text editor.
  • Use two spaces for indentation.
  • Use JavaDoc-style comments.
  • When fixing a problem, check to see if the problem occurs elsewhere in the same file, and fix it everywhere if possible.
  • End the file with a newline (make sure your patches don't contain files with the text "no newline at end of file" in them).
  • Declare local variables as near to their use as possible.
  • For new files, be sure to use the right license boilerplate per our license policy. (Employees of the Mozilla Foundation and its subsidiaries, including the Mozilla Corporation, should note that, in their case, the Initial Developer is the Mozilla Foundation.)

C/C++ practices

  • Do the changes meet the C++ Portability Guide?
  • Have you checked for compiler warnings? Warnings often point to real bugs.
  • In new code, use NULL for pointers. In old code, using nsnull or 0 for consistency is allowed.
  • When testing a pointer, use (!myPtr) or (myPtr); don't use myPtr != nsnull or myPtr == nsnull.
  • Do not compare x == PR_TRUE or x == PR_FALSE. Use (x) or (!x) instead. x == PR_TRUE, in fact, is different from if (x)!
  • On whether to use nsFoo aFoo (bFoo) or nsFoo aFoo = bFoo: For first tier platforms, although the former is theoretically better, there is probably no reason to prefer it over the latter form. This is good, since everyone agrees, the form with "=" looks better. More data for second tier platforms would be good.
  • To avoid warnings created by variables used only in debug builds, use the DebugOnly<T> helper when declaring them.
  • You should use the static preference API for working with preferences.
  • Forward declare classes in your header files instead of including them whenever possible. For example, if you have an interface with a void DoSomething(nsIContent* aContent) function, forward declare with class nsIContent; instead of #include "nsIContent.h"

JavaScript practices

  • Make sure you are aware of the JavaScript Tips.
  • Do not compare x == true or x == false. Use (x) or (!x) instead. x == true, in fact, is different from if (x)! Compare objects to null, numbers to 0 or strings to "" if there is chance for confusion.
  • Make sure that your code doesn't generate any strict JavaScript warnings, such as:
    • Duplicate variable declaration
    • Mixing return; with return value;
    • Undeclared variables or members. If you are unsure if an array value exists, compare the index to the array's length. If you are unsure if an object member exists, use "name" in aObject, or if you are expecting a particular type you may use typeof(aObject.name) == "function" (or whichever type you are expecting).
  • Use {{ mediawiki.external('value1, value2') }} to create a JavaScript array in preference to using new Array(value1, value2) which can be confusing, as new Array(length) will actually create a physically empty array with the given logical length, while {{ mediawiki.external('value') }} will always create a 1-element array. You cannot actually guarantee to be able to preallocate memory for an array.
  • Use { member: value, ... } to create a JavaScript object; a useful advantage over new Object() is the ability to create initial properties and use extended JavaScript syntax to define getters and setters.
  • If having defined a constructor you need to assign default properties it is preferred to assign an object literal to the prototype property.
  • Use regular expressions, but use them wisely. For instance, to check that aString is not completely whitespace use /\S/.test(aString); only use aString.search if you need to know the position of the result, or aString.match if you need to collect matching substrings (delimited by parentheses in the regular expression). Regular expressions are less useful if the match is unknown in advance, or to extract substrings in known positions in the string. For instance, aString.slice(-1) returns the last letter in aString, or the empty string if aString is empty.

Makefile practices

  • Shell commands are expensive esp for windows/mingw, so use sparingly.
    • Genearte/use pre-computed macro values whenever possible.
    • Use make builtin functions to perform string manipulation in place of $(shell awk/perl/python/sed/tr).
  • Use platform values defined by autoconf.mk & configure.mk in place of $(shell uname [args]).
    • Version/OS conditionals in general are bad but when needed modify configure to generate a static value once for everyone to use.
  • Target rules should be written with dependencies so work will only be performed when needed.
  • Never make generated targes dependent on directories.  Targets become stale whenever any directory content is modified.
  • Launch make command twice to verify dependencies: "make ; make".
    • Make#1 is the workhorse and will generate everything on the initial pass.
    • Make#2 will mostly be a nop.  Aside from minimal overhead (~traversal) make should return quickly and perform no work.

Python practices

COM and pointers

  • Use nsCOMPtr<>
    If you don't know how to use it, start looking in the code for examples. The general rule is that the very act of typing NS_RELEASE should be a signal to you to question your code: "Should I be using nsCOMPtr here?". Generally the only valid use of NS_RELEASE are when you are storing refcounted pointers in a long-lived datastructure.
  • Declare new XPCOM interfaces using XPIDL so they will be scriptable.
  • Use nsCOMPtr for strong references, and nsWeakPtr for weak references.
  • String arguments to functions should be declared as nsAString.
  • Use str.IsEmpty() instead of str.Length() == 0.
  • Don't use QueryInterface directly. Use CallQueryInterface or do_QueryInterface instead.
  • nsresult should be declared as rv. Not res, not result, not foo.
  • For constant strings, use NS_LITERAL_STRING("...") instead of NS_ConvertASCIItoUCS2("..."), AssignWithConversion("..."), EqualsWithConversion("..."), or nsAutoString()
  • Use contractids instead of progids or class IDs.

IDL

Use leading-lowercase, or "interCaps"

When defining a method or attribute in IDL, the first letter should be lowercase, and each following word should be capitalized. For example:

long updateStatusBar();

Use attributes wherever possible

Whenever you are retrieving or setting a single value without any context, you should use attributes. Don't use two methods when you could use one attribute. Using attributes logically connects the getting and setting of a value, and makes scripted code look cleaner.

This example has too many methods:

interface nsIFoo : nsISupports
{
    long getLength();
    void setLength(in long length);
    long getColor();
};

The code below will generate the exact same C++ signature, but is more script-friendly.

interface nsIFoo : nsISupports
{
    attribute long length;
    readonly attribute long color;
};

Use Java-style constants

When defining scriptable constants in IDL, the name should be all uppercase, with underscores between words:

const long ERROR_UNDEFINED_VARIABLE = 1;

See also

For details on interface development, as well as more detailed style guides, see the Interface development guide.

Error handling

Check for errors early and often

Every time you make a call into an XPCOM function, you should check for an error condition. You need to do this even if you know that call will never fail. Why?

  • Someone may change the callee in the future to return a failure condition.
  • The object in question may live on another thread, another process, or possibly even another machine. The proxy could have failed to actually make your call in the first place.

Use the nice macros

Use the NS_ENSURE_SUCCESS(rv, rv) and NS_ENSURE_TRUE(expr, rv) macros in place of if (NS_FAILED(rv)) { return rv; } and if (!expr) { return rv; }, unless the failure is a normal condition (i.e. you don't want it to warn on a debug build).

Return from errors immediately

In most cases, your knee-jerk reaction should be to return from the current function when an error condition occurs. Don't do this:

rv = foo->Call1();
if (NS_SUCCEEDED(rv)) {
  rv = foo->Call2();
  if (NS_SUCCEEDED(rv)) {
    rv = foo->Call3();
  }
}
return rv;

Instead, do this:

rv = foo->Call1();
NS_ENSURE_SUCCESS(rv, rv);

rv = foo->Call2();
NS_ENSURE_SUCCESS(rv, rv);

rv = foo->Call3();
NS_ENSURE_SUCCESS(rv, rv);

Why? Because error handling should not obfuscate the logic of the code. The author's intent in the first example was to make 3 calls in succession, but wrapping the calls in nested if() statements obscured the most likely behavior of the code.

Consider a more complicated example that actually hides a bug:

PRBool val;
rv = foo->GetBooleanValue(&val);
if (NS_SUCCEEDED(rv) && val) {
    foo->Call1();
} else {
    foo->Call2();
}

The intent of the author may have been that foo->Call2() would only happen when val had a false value. In fact, foo->Call2() will also be called when foo->GetBooleanValue(&val) fails. This may or may not have been the author's intent, and it is not clear from this code. Here is an updated version:

PRBool val;
rv = foo->GetBooleanValue(&val);
if (NS_FAILED(rv)) return rv;
if (val) {
    foo->Call1();
} else {
    foo->Call2();
}

In this example, the author's intent is clear, and an error condition avoids both calls to foo->Call1() and foo->Call2();

Possible exceptions: Sometimes it is not fatal if a call fails. For instance, if you are notifying a series of observers that an event has fired, it might be inconsequential that one of these notifications failed:

for (i = 0; i < length; i++) {
    // we don't care if any individual observer fails
    observers[i]->Observe(foo, bar, baz);
}

Another possibility is that you are not sure if a component exists or is installed, and you wish to continue normally if the component is not found.

nsCOMPtr<nsIMyService> service = do_CreateInstance(NS_MYSERVICE_CID, &rv);
// if the service is installed, then we'll use it
if (NS_SUCCEEDED(rv)) {
    // non-fatal if this fails too, ignore this error
    service->DoSomething();

    // this is important, handle this error!
    rv = service->DoSomethingImportant();
    NS_ENSURE_SUCCESS(rv, rv);
}
    
// continue normally whether or not the service exists

C++ strings

Use the Auto form of strings for local values

When declaring a local, short-lived nsString class, always use nsAutoString or nsCAutoString - these versions pre-allocate a 64-byte buffer on the stack, and avoid fragmenting the heap. Don't do this:

nsresult
foo()
{
  nsCString bar;
  ..
}

instead:

nsresult
foo()
{
  nsCAutoString bar;
  ..
}

Be wary of leaking values from non-XPCOM functions that return char* or PRUnichar*

It is an easy trap to return an allocated string from an internal helper function, and then use that function inline in your code without freeing the value. Consider this code:

static
char*
GetStringValue()
{
    ..
    return resultString.ToNewCString();
}

    ..
    WarnUser(GetStringValue());

In the above example, WarnUser will get the string allocated from resultString.ToNewCString() and throw away the pointer. The resulting value is never freed. Instead, either use the string classes to make sure your string is automatically freed when it goes out of scope, or make sure that your string is freed.

Automatic cleanup:

static
void
GetStringValue(nsAWritableCString& aResult) {
    ..
    aResult.Assign("resulting string");
}

    ..
    nsCAutoString warning;
    GetStringValue(warning);
    WarnUser(warning.get());

Free the string manually:

static
char*
GetStringValue() {
    ..
    return resultString.ToNewCString();
}

    ..
    char* warning = GetStringValue();
    WarnUser(warning);
    nsMemory::Free(warning);

Use NS_LITERAL_STRING() to avoid runtime string conversion

It is very common to need to assign the value of a literal string such as "Some String" into a unicode buffer. Instead of using nsString's AssignWithConversion and AppendWithConversion, use NS_LITERAL_STRING() instead. On most platforms, this will force the compiler to compile in a raw unicode string, and assign it directly.

Incorrect:

nsAutoString warning;
warning.AssignWithConversion("danger will robinson!");
..
foo->SetUnicodeValue(warning.get());

Correct:

NS_NAMED_LITERAL_STRING(warning,"danger will robinson!");
..
// if you'll be using the 'warning' string, you can still use it as before:
foo->SetUnicodeValue(warning.get());

// alternatively, use the wide string directly:
foo->SetUnicodeValue(NS_LITERAL_STRING("danger will robinson!").get());

Naming and formatting code

The following norms should be followed for new code, and for Tower of Babel code that needs cleanup. For existing code, use the prevailing style in a file or module, or ask the owner if you are on someone else's turf and it's not clear what style to use.

Whitespace

No tabs. No whitespace at the end of a line.

Line length

80 characters or less (for laptop side-by-side diffing and two-window tiling; also for Bonsai / hgweb and hardcopy printing).

Indentation

Two spaces per logic level.

Note that class visibility and goto labels do not consume a logic level, but switch case labels do. See examples below.

Control structures

Use K&R bracing style: left brace at end of first line, cuddle else on both sides.

Class and function definitions are not control structures; left brace goes by itself on the second line and without extra indentation, in general.

Always brace controlled statements, even a single-line consequent of an if else else. This is redundant typically, but it avoids dangling else bugs, so it's safer at scale than fine-tuning.

Break long conditions after && and || logical connectives. See below for the rule for other operators.

Examples:

if (...) {
} else if (...) {
} else {
}

while (...) {
}

do {
} while (...);

for (...; ...; ...) {
}

switch (...) {
  case 1: {
    // When you need to declare a variable in a switch, put the block in braces
    int var;
    break;
  }
  case 2:
    ...
    break;
  default:
    break;
}

Control keywords if, for, while, and switch are always followed by a space to distinguish them from function calls which have no trailing space. 

C++ namespaces

Mozilla project C++ declarations should be in the "mozilla" namespace. Modules can define their own namespaces under "mozilla", with short all-lowercase names, but are not allowed to add declarations to the "mozilla" namespace.

No "using" statements are allowed in header files, except inside class definitions or functions. (We don't want to pollute the global scope of compilation units that use the header file.)  Introduce typedefs so as to avoid writing namespace-prefixed type names in non-namespaced classes. For example:

class MyClass
{
public:
  typedef mozilla::TimeStamp TimeStamp;
  TimeStamp mStartTime;
  TimeStamp mEndTime;
};

Be wise about the visibility of these typedefs.  They should be private or protected unless there's a good reason to make them public.  For example, a public Array::size_type makes sense, but a public MyClass::TimeStamp above probably doesn't.

using namespace ...; is only allowed in .cpp files after all #includes. Prefer to wrap code in namespace ... { ... }; instead if possible.

Don't indent code inside namespace ... { ... }.  You can prevent this inside emacs by setting the "innamespace" offset:

(c-set-offset 'innamespace 0)

C++ classes 

namespace mozilla {
class MyClass : public X
              , public Y
{
public:
  MyClass() : mVar(0) { ... };
  
private:
  int mVar;
};
} // namespace mozilla

Existing classes in the global namespace are named with a short prefix (e.g. "ns") as a psuedo-namespace.

For small functions in a class declaration, it's OK to do the above. For larger ones use something similar to method declarations below.

Methods and functions

In C/C++, method names should be capitalized and use CamelCase.

int
MyFunction(...)
{
  ...
}

int
MyClass::Method(...)
{
  ...
}

Getters that never fail and never return null are named Foo(), while all other getters use GetFoo(). nsresult GetFoo(Foo** aOutFoo) is preferred over Foo* GetFoo(nsresult* aRv). (See {{ bug("223255") }} for more information.)

In JavaScript, functions should use camelCase but should not capitalize the first letter. Methods should use the named function expression syntax so that stack traces read better:

doSomething: function MyObject_doSomething(aFoo, aBar) {
  ...
}

In-line functions should have spaces around braces, except before commas or semicolons:

function valueObject(aValue) { return { value: aValue }; }

JavaScript objects

var foo = { prop1: "value1" };

var bar = {
  prop1: "value1",
  prop2: "value2"
}; 

Constructors for objects should be capitalized and use CamelCase:

function ObjectConstructor()
{
  this.foo = "bar";
}

Mode line

Files should have Emacs and vim mode line comments as the first two lines of the file, which should set indent-tabs-mode to nil. For new files, use this, specifying two-space indentation:

/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */

Make sure to use the correct "Mode" in the first line—don't use "C++" in JavaScript files.

Declarations

Canonical C++ style favors T* p for a typename T and a declarator name p. This style requires programmer discipline to avoid T* p, q; where T* p; T* q; was intended. For new C++ code, this is the best style to use. Watch out for existing modules that use T *p style still (e.g., the SpiderMonkey JS engine).

Operators

Overlong expressions not joined by && and || should break so the operator starts on the second line and starts in the same column as the start of the expression in the first line. This applies to ?:, binary arithmetic operators including +, and member-of operators (in particular the . operator in JS, see the Rationale).

Rationale: operator at the front of the continuation line makes for faster visual scanning, because there is no need to read to end of line. Also there exists a context-sensitive keyword hazard in JS, see https://bugzilla.mozilla.org/show_bug.cgi?id=442099#c19, which can be avoided by putting . at the start of a continuation line in long member expression.

In JavaScript, == is preferred to ===.

Unary keyword operators, such as typeof and sizeof, should have their operand parenthesized; e.g. typeof("foo") == "string".

Literals

Double-quoted strings (e.g. "foo") are preferred to single-quoted strings (e.g. 'foo') in JavaScript, except to avoid escaping of embedded double quotes or when assigning inline event handlers.

Use \uXXXX unicode escapes for non-ASCII characters. The character set for XUL, DTD, script, and properties files is UTF-8, which is not easily readable.

Prefixes

Follow these naming prefix conventions:

Variable prefixes
  • k=constant (e.g. kNC_child). Not all code uses this style; some uses ALL_CAPS for constants.
  • g=global (e.g. gPrefService)
  • a=argument (e.g. aCount)
  • C++ Specific Prefixes
    • s=static member (e.g. sPrefChecked)
    • m=member (e.g. mLength)
  • JavaScript Specific Prefixes
    • _=member (variable or function) (e.g. _length or _setType(aType))
    • k=enumeration value (e.g. const kDisplayModeNormal = 0)
    • on=event handler (e.g. function onLoad())
Convenience constants for interface names should be prefixed with nsI:
const nsISupports = Components.interfaces.nsISupports;
const nsIWBN = Components.interfaces.nsIWebBrowserNavigation;
Global functions/macros/etc
  • Macros begin with NS_, and are all caps (e.g. NS_IMPL_ISUPPORTS)
  • Global functions with extern "C" linkage begin with NS_ (e.g. NS_InitXPCOM).

Usage of PR_(MAX|MIN|ABS|ROUNDUP) macro calls

On certain platforms (eg: FreeBSD which uses gcc42, due to licensing issues with recent gcc versions), the PR_(MAX|MIN|ABS|ROUNDUP) macro calls trigger compiler bugs that cause wrong results in some cases (see bug 603880, comment 7). All PR_(MAX|MIN|ABS|ROUNDUP) calls in C++ code (other than that in NSS/NSPR) have been replaced by the equivalent NS_(MAX|MIN|ABS|ROUNDUP) inline calls by bug 645398 and bug 661584. All new code in Firefox/core/toolkit needs to |#include "nsAlgorithm.h"| and use the NS_foo varients instead of PR_foo.

{{ languages( { "ja": "ja/Mozilla_Coding_Style_Guide" } ) }}

Revision Source

<p>This document attempts to explain the basic styles and patterns that are used in the Mozilla codebase. New code should try to conform to these standards so that it is as easy to maintain as existing code. Of course every rule has an exception, but it's important to know the rules nonetheless!</p>
<p>This is particularly directed at people new to the Mozilla codebase, who are in the process of getting their code reviewed. Before getting a review, please read over this document and make sure your code conforms to the recommendations here.</p>
<h3 name="General_C.2FC.2B.2B_Practices">General practices</h3>
<ul> <li>Don't put an <code>else</code> right after a <code>return</code>. Delete the <code>else</code>, it's unnecessary and increases indentation level.</li> <li>Don't leave debug <code>printf</code>s or <code>dump</code>s lying around.</li> <li>Use Unix-style carriage returns ("<code>\n</code>") rather than Windows/DOS ones (<code>"\r\n</code>").  You can convert patches with DOS newlines to Unix via the 'dos2unix' utility, or your favorite text editor.</li> <li>Use two spaces for indentation.</li> <li>Use <a class="external" href="http://java.sun.com/j2se/javadoc/writingdoccomments/">JavaDoc-style comments</a>.</li> <li>When fixing a problem, check to see if the problem occurs elsewhere in the same file, and fix it everywhere if possible.</li> <li>End the file with a newline (make sure your patches don't contain files with the text "no newline at end of file" in them).</li> <li>Declare local variables as near to their use as possible.</li> <li>For new files, be sure to use the right <a class=" external" href="http://www.mozilla.org/MPL/boilerplate-1.1/" title="http://www.mozilla.org/MPL/boilerplate-1.1/">license boilerplate</a> per our <a class=" external" href="http://www.mozilla.org/MPL/license-policy.html" title="http://www.mozilla.org/MPL/license-policy.html">license policy</a>. (Employees of the Mozilla Foundation and its subsidiaries, including the Mozilla Corporation, should note that, in their case, <a class=" external" href="http://weblogs.mozillazine.org/gerv/archives/2010/02/mpl_initial_developer_for_mozilla_employ.html" title="http://weblogs.mozillazine.org/gerv/archives/2010/02/mpl_initial_developer_for_mozilla_employ.html">the Initial Developer is the Mozilla Foundation.</a>)</li>
</ul>
<h4>C/C++ practices</h4>
<ul> <li>Do the changes meet the <a href="/en/C%2B%2B_Portability_Guide" title="en/C++_Portability_Guide">C++ Portability Guide</a>?</li> <li><strong>Have you checked for compiler warnings?</strong> Warnings often point to real bugs.</li> <li>In new code, use <code>NULL</code> for pointers. In old code, using <code>nsnull</code> or <code>0</code> for consistency is allowed.</li> <li>When testing a pointer, use <code>(</code><code>!myPtr</code><code>)</code> or <code>(myPtr)</code>; don't use <code>myPtr != nsnull</code> or <code>myPtr == nsnull</code>.</li> <li>Do not compare <code>x == PR_TRUE</code> or <code>x == PR_FALSE</code>. Use <code>(x)</code> or <code>(!x)</code> instead. <code>x == PR_TRUE</code>, in fact, is different from if <code>(x)</code>!</li> <li>On whether to use <code>nsFoo aFoo (bFoo)</code> or <code>nsFoo aFoo = bFoo</code>: For first tier platforms, although the former is theoretically better, there is probably no reason to prefer it over the latter form. This is good, since everyone agrees, the form with "=" looks better. More data for second tier platforms would be good.</li> <li>To avoid warnings created by variables used only in debug builds, use the <a href="/En/Namespace/Mozilla/DebugOnly%3CT%3E" title="En/Namespace/Mozilla/DebugOnly&lt;T>"><code>DebugOnly&lt;T&gt;</code></a> helper when declaring them.</li> <li>You should <a href="/en/Preferences/Using_preferences_from_application_code" title="en/Preferences/Using preferences from application code">use the static preference API</a> for working with preferences.</li> <li>Forward declare classes in your header files instead of including them whenever possible. For example, if you have an interface with a <code>void DoSomething(nsIContent* aContent)</code> function, forward declare with <code>class nsIContent;</code> instead of <code>#include "nsIContent.h"</code></li>
</ul>
<h4>JavaScript practices</h4>
<ul> <li>Make sure you are aware of the <a href="/en/JavaScript_Tips" title="en/JavaScript Tips">JavaScript Tips</a>.</li> <li>Do not compare <code>x == true</code> or <code>x == false</code>. Use <code>(x)</code> or <code>(!x)</code> instead. <code>x == true</code>, in fact, is different from if <code>(x)</code>! Compare objects to <code>null</code>, numbers to <code>0</code> or strings to <code>""</code> if there is chance for confusion.</li> <li>Make sure that your code doesn't generate any strict JavaScript warnings, such as: <ul> <li>Duplicate variable declaration</li> <li>Mixing <code>return;</code> with <code>return value;</code></li> <li>Undeclared variables or members. If you are unsure if an array value exists, compare the index to the array's length. If you are unsure if an object member exists, use <code>"name" in aObject</code>, or if you are expecting a particular type you may use <code>typeof(aObject.name) == "function"</code> (or whichever type you are expecting).</li> </ul> </li> <li>Use <code>{{ mediawiki.external('value1, value2') }}</code> to create a JavaScript array in preference to using <code>new Array(value1, value2)</code> which can be confusing, as <code>new Array(length)</code> will actually create a physically empty array with the given logical length, while <code>{{ mediawiki.external('value') }}</code> will always create a 1-element array. You cannot actually guarantee to be able to preallocate memory for an array.</li> <li>Use <code>{ member: value, ... }</code> to create a JavaScript object; a useful advantage over <code>new Object()</code> is the ability to create initial properties and use extended JavaScript syntax to define getters and setters.</li> <li>If having defined a constructor you need to assign default properties it is preferred to assign an object literal to the prototype property.</li> <li>Use regular expressions, but use them wisely. For instance, to check that <code>aString</code> is not completely whitespace use <code>/\S/.test(aString);</code> only use <code>aString.search</code> if you need to know the position of the result, or <code>aString.match</code> if you need to collect matching substrings (delimited by parentheses in the regular expression). Regular expressions are less useful if the match is unknown in advance, or to extract substrings in known positions in the string. For instance, <code>aString.slice(-1)</code> returns the last letter in <code>aString</code>, or the empty string if <code>aString</code> is empty.</li>
</ul>
<h3 name="General_C.2FC.2B.2B_Practices">Makefile practices</h3>
<ul> <li>Shell commands are expensive esp for windows/mingw, so use sparingly. <ul> <li>Genearte/use pre-computed macro values whenever possible.</li> <li>Use make builtin functions to perform string manipulation in place of $(shell awk/perl/python/sed/tr).</li> </ul> </li> <li>Use platform values defined by autoconf.mk &amp; configure.mk in place of <code>$(shell uname [args])</code>. <ul> <li>Version/OS conditionals in general are bad but when needed modify configure to generate a static value once for everyone to use.</li> </ul> </li> <li>Target rules should be written with dependencies so work will only be performed when needed.</li> <li>Never make generated targes dependent on directories.  Targets become stale whenever any directory content is modified.</li> <li>Launch make command twice to verify dependencies: "make ; make". <ul> <li>Make#1 is the workhorse and will generate everything on the initial pass.</li> <li>Make#2 will mostly be a nop.  Aside from minimal overhead (~traversal) make should return quickly and perform no work.</li> </ul> </li>
</ul>
<h3 name="General_C.2FC.2B.2B_Practices">Python practices</h3>
<ul> <li>Do not place statements on the same line as <code>if/elif/else</code> conditionals to form a one-liner.</li> <li>Global vars, avoid them at all cost.</li> <li>Exclude outer parenthesis from conditionals.  Use <code>if x&gt;5: </code>rather than <code>if (x&gt;5):</code></li> <li>Use string formatters rather than var + str(val).  <code>var = 'Type %s value is %d' % ('int', 5)</code></li> <li>Utilize tools like <a class=" external" href="http://pypi.python.org/pypi/pylint" title="http://pypi.python.org/pypi/pylint">http://pypi.python.org/pypi/pylint</a> or <a class=" external" href="http://pychecker.sourceforge.net/" title="http://pychecker.sourceforge.net/">http://pychecker.sourceforge.net</a> to screen sources for common problems.</li> <li>Testing/Unit tests, write them.</li> <li>See also</li> <pre class="bz_comment_text" id="comment_text_10"><a href="http://www.python.org/dev/peps/pep-0008/">http://www.python.org/dev/peps/pep-0008/</a>
<a href="http://python.net/%7Egoodger/projects/pycon/2007/idiomatic/handout.html">http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html</a>
</pre>
</ul>
<h3 name="COM_and_pointers">COM and pointers</h3>
<ul> <li>Use <code>nsCOMPtr&lt;&gt;</code><br> If you don't know how to use it, start looking in the code for examples. The general rule is that the very act of typing <code>NS_RELEASE</code> should be a signal to you to question your code: "Should I be using <code>nsCOMPtr</code> here?". Generally the only valid use of <code>NS_RELEASE</code> are when you are storing refcounted pointers in a long-lived datastructure.</li> <li>Declare new XPCOM interfaces using <a href="/en/XPIDL" title="en/XPIDL">XPIDL</a> so they will be scriptable.</li> <li>Use <a href="/en/nsCOMPtr" title="en/nsCOMPtr">nsCOMPtr</a> for strong references, and <a href="/en/Weak_reference" title="en/Weak_reference">nsWeakPtr</a> for weak references.</li> <li>String arguments to functions should be declared as <code>nsAString</code>.</li> <li>Use <code>str.IsEmpty()</code> instead of <code>str.Length() == 0</code>.</li> <li>Don't use <code>QueryInterface</code> directly. Use <code>CallQueryInterface</code> or <code>do_QueryInterface</code> instead.</li> <li>nsresult should be declared as rv. Not res, not result, not foo.</li> <li>For constant strings, use <code>NS_LITERAL_STRING("...")</code> instead of <code>NS_ConvertASCIItoUCS2("...")</code>, <code>AssignWithConversion("...")</code>, <code>EqualsWithConversion("...")</code>, or <code>nsAutoString()</code></li> <li>Use <a class="link-news" href="news://news.mozilla.org/3994AE3E.D96EF810@netscape.com">contractids</a> instead of progids or class IDs.</li>
</ul>
<h3 name="IDL">IDL</h3>
<h4 name="Use_leading-lowercase.2C_or_.22interCaps.22">Use leading-lowercase, or "interCaps"</h4>
<p>When defining a method or attribute in IDL, the first letter should be lowercase, and each following word should be capitalized. For example:</p>
<pre>long updateStatusBar();
</pre>
<h4 name="Use_attributes_wherever_possible">Use attributes wherever possible</h4>
<p>Whenever you are retrieving or setting a single value without any context, you should use attributes. Don't use two methods when you could use one attribute. Using attributes logically connects the getting and setting of a value, and makes scripted code look cleaner.</p>
<p>This example has too many methods:</p>
<pre>interface nsIFoo : nsISupports
{
    long getLength();
    void setLength(in long length);
    long getColor();
};
</pre>
<p>The code below will generate the exact same C++ signature, but is more script-friendly.</p>
<pre>interface nsIFoo : nsISupports
{
    attribute long length;
    readonly attribute long color;
};
</pre>
<h4 name="Use_java-style_constants">Use Java-style constants</h4>
<p>When defining scriptable constants in IDL, the name should be all uppercase, with underscores between words:</p>
<pre>const long ERROR_UNDEFINED_VARIABLE = 1;
</pre>
<h4>See also</h4>
<p>For details on interface development, as well as more detailed style guides, see the <a href="/En/Developer_Guide/Interface_development_guide" title="En/Developer Guide/Interface development guide">Interface development guide</a>.</p>
<h3 name="Error_handling">Error handling</h3>
<h4 name="Check_for_errors_early_and_often">Check for errors early and often</h4>
<p>Every time you make a call into an XPCOM function, you should check for an error condition. You need to do this even if you know that call will never fail. Why?</p>
<ul> <li>Someone may change the callee in the future to return a failure condition.</li> <li>The object in question may live on another thread, another process, or possibly even another machine. The proxy could have failed to actually make your call in the first place.</li>
</ul>
<h4 name="Use_the_nice_macros">Use the nice macros</h4>
<p>Use the <code>NS_ENSURE_SUCCESS(rv, rv)</code> and <code>NS_ENSURE_TRUE(expr, rv)</code> macros in place of <code>if (NS_FAILED(rv)) { return rv; }</code> and <code>if (!expr) { return rv; }</code>, <em>unless</em> the failure is a normal condition (i.e. you don't want it to warn on a debug build).</p>
<h4 name="Return_from_errors_immediately">Return from errors immediately</h4>
<p>In most cases, your knee-jerk reaction should be to return from the current function when an error condition occurs. Don't do this:</p>
<pre class="brush: cpp">rv = foo-&gt;Call1();
if (NS_SUCCEEDED(rv)) {
  rv = foo-&gt;Call2();
  if (NS_SUCCEEDED(rv)) {
    rv = foo-&gt;Call3();
  }
}
return rv;
</pre>
<p>Instead, do this:</p>
<pre class="brush: cpp">rv = foo-&gt;Call1();
NS_ENSURE_SUCCESS(rv, rv);

rv = foo-&gt;Call2();
NS_ENSURE_SUCCESS(rv, rv);

rv = foo-&gt;Call3();
NS_ENSURE_SUCCESS(rv, rv);
</pre>
<p>Why? Because error handling should not obfuscate the logic of the code. The author's intent in the first example was to make 3 calls in succession, but wrapping the calls in nested if() statements obscured the most likely behavior of the code.</p>
<p>Consider a more complicated example that actually hides a bug:</p>
<pre class="brush: cpp">PRBool val;
rv = foo-&gt;GetBooleanValue(&amp;val);
if (NS_SUCCEEDED(rv) &amp;&amp; val) {
    foo-&gt;Call1();
} else {
    foo-&gt;Call2();
}
</pre>
<p>The intent of the author may have been that foo-&gt;Call2() would only happen when val had a false value. In fact, foo-&gt;Call2() will also be called when foo-&gt;GetBooleanValue(&amp;val) fails. This may or may not have been the author's intent, and it is not clear from this code. Here is an updated version:</p>
<pre class="brush: cpp">PRBool val;
rv = foo-&gt;GetBooleanValue(&amp;val);
if (NS_FAILED(rv)) return rv;
if (val) {
    foo-&gt;Call1();
} else {
    foo-&gt;Call2();
}
</pre>
<p>In this example, the author's intent is clear, and an error condition avoids both calls to foo-&gt;Call1() and foo-&gt;Call2();</p>
<p><em>Possible exceptions:</em> Sometimes it is not fatal if a call fails. For instance, if you are notifying a series of observers that an event has fired, it might be inconsequential that one of these notifications failed:</p>
<pre class="brush: cpp">for (i = 0; i &lt; length; i++) {
    // we don't care if any individual observer fails
    observers[i]-&gt;Observe(foo, bar, baz);
}
</pre>
<p>Another possibility is that you are not sure if a component exists or is installed, and you wish to continue normally if the component is not found.</p>
<pre class="brush: cpp">nsCOMPtr&lt;nsIMyService&gt; service = do_CreateInstance(NS_MYSERVICE_CID, &amp;rv);
// if the service is installed, then we'll use it
if (NS_SUCCEEDED(rv)) {
    // non-fatal if this fails too, ignore this error
    service-&gt;DoSomething();

    // this is important, handle this error!
    rv = service-&gt;DoSomethingImportant();
    NS_ENSURE_SUCCESS(rv, rv);
}
    
// continue normally whether or not the service exists
</pre>
<h3 name="Strings">C++ strings</h3>
<h4 name="Use_the_Auto_form_of_strings_for_local_values">Use the <code>Auto</code> form of strings for local values</h4>
<p>When declaring a local, short-lived <code>nsString</code> class, always use <code>nsAutoString</code> or <code>nsCAutoString</code> - these versions pre-allocate a 64-byte buffer on the stack, and avoid fragmenting the heap. Don't do this:</p>
<pre class="brush: cpp">nsresult
foo()
{
  nsCString bar;
  ..
}
</pre>
<p>instead:</p>
<pre class="brush: cpp">nsresult
foo()
{
  nsCAutoString bar;
  ..
}
</pre>
<h4 name="Be_wary_of_leaking_values_from_non-XPCOM_functions_that_return_char.2A_or_PRUnichar.2A">Be wary of leaking values from non-XPCOM functions that return char* or PRUnichar*</h4>
<p>It is an easy trap to return an allocated string from an internal helper function, and then use that function inline in your code without freeing the value. Consider this code:</p>
<pre class="brush: cpp">static
char*
GetStringValue()
{
    ..
    return resultString.ToNewCString();
}

    ..
    WarnUser(GetStringValue());
</pre>
<p>In the above example, WarnUser will get the string allocated from <code>resultString.ToNewCString()</code> and throw away the pointer. The resulting value is never freed. Instead, either use the string classes to make sure your string is automatically freed when it goes out of scope, or make sure that your string is freed.</p>
<p>Automatic cleanup:</p>
<pre class="brush: cpp">static
void
GetStringValue(nsAWritableCString&amp; aResult) {
    ..
    aResult.Assign("resulting string");
}

    ..
    nsCAutoString warning;
    GetStringValue(warning);
    WarnUser(warning.get());
</pre>
<p>Free the string manually:</p>
<pre class="brush: cpp">static
char*
GetStringValue() {
    ..
    return resultString.ToNewCString();
}

    ..
    char* warning = GetStringValue();
    WarnUser(warning);
    nsMemory::Free(warning);
</pre>
<h4 name="Use_NS_LITERAL_STRING.28.29_to_avoid_runtime_string_conversion">Use NS_LITERAL_STRING() to avoid runtime string conversion</h4>
<p>It is very common to need to assign the value of a literal string such as "Some String" into a unicode buffer. Instead of using <code>nsString</code>'s <code>AssignWithConversion</code> and <code>AppendWithConversion</code>, use <code>NS_LITERAL_STRING()</code> instead. On most platforms, this will force the compiler to compile in a raw unicode string, and assign it directly.</p>
<p>Incorrect:</p>
<pre class="brush: cpp">nsAutoString warning;
warning.AssignWithConversion("danger will robinson!");
..
foo-&gt;SetUnicodeValue(warning.get());
</pre>
<p>Correct:</p>
<pre class="brush: cpp">NS_NAMED_LITERAL_STRING(warning,"danger will robinson!");
..
// if you'll be using the 'warning' string, you can still use it as before:
foo-&gt;SetUnicodeValue(warning.get());

// alternatively, use the wide string directly:
foo-&gt;SetUnicodeValue(NS_LITERAL_STRING("danger will robinson!").get());
</pre>
<h3 name="Naming_and_Formatting_code">Naming and formatting code</h3>
<p><em>The following norms should be followed for new code, and for Tower of Babel code that needs cleanup. For existing code, use the prevailing style in a file or module, or ask the owner if you are on someone else's turf and it's not clear what style to use.<br>
</em></p>
<h4 name="Whitespace">Whitespace</h4>
<p>No tabs. No whitespace at the end of a line.</p>
<h4 name="Line_Length">Line length</h4>
<p>80 characters or less (for laptop side-by-side diffing and two-window tiling; also for Bonsai / hgweb and hardcopy printing).</p>
<h4 name="Whitespace">Indentation</h4>
<p>Two spaces per logic level.</p>
<p>Note that class visibility and goto labels do not consume a logic level, but switch case labels do. See examples below.</p>
<h4 name="Control_Structures">Control structures</h4>
<p>Use K&amp;R bracing style: left brace at end of first line, cuddle else on both sides.</p>
<div class="note">Class and function definitions are not control structures; left brace goes by itself on the second line and without extra indentation, in general.</div>
<p>Always brace controlled statements, even a single-line consequent of an <code>if else else</code>. This is redundant typically, but it avoids dangling else bugs, so it's safer at scale than fine-tuning.</p>
<p>Break long conditions after <code>&amp;&amp;</code> and <code>||</code> logical connectives. See below for the rule for other operators.</p>
<p>Examples:</p>
<pre class="brush: cpp">if (...) {
} else if (...) {
} else {
}

while (...) {
}

do {
} while (...);

for (...; ...; ...) {
}

switch (...) {
  case 1: {
    // When you need to declare a variable in a switch, put the block in braces
    int var;
    break;
  }
  case 2:
    ...
    break;
  default:
    break;
}</pre>
<p>Control keywords <code>if</code>, <code>for</code>, <code>while</code>, and <code>switch</code> are always followed by a space to distinguish them from function calls which have no trailing space. </p>
<h4 name="Namespaces">C++ namespaces</h4>
<p>Mozilla project C++ declarations should be in the "mozilla" namespace. Modules can define their own namespaces under "mozilla", with short all-lowercase names, but are not allowed to add declarations to the "mozilla" namespace.</p>
<p>No "using" statements are allowed in header files, except inside class definitions or functions. (We don't want to pollute the global scope of compilation units that use the header file.)  Introduce typedefs so as to avoid writing namespace-prefixed type names in non-namespaced classes. For example:</p>
<pre class="brush: cpp">class MyClass
{
public:
  typedef mozilla::TimeStamp TimeStamp;
  TimeStamp mStartTime;
  TimeStamp mEndTime;
};
</pre>
<p>Be wise about the visibility of these typedefs.  They should be private or protected unless there's a good reason to make them public.  For example, a public <code>Array::size_type</code> makes sense, but a public <code>MyClass::TimeStamp</code> above probably doesn't.</p>
<p><code>using namespace ...;</code> is only allowed in .cpp files after all <code>#include</code>s. Prefer to wrap code in <code>namespace ... { ... };</code> instead if possible.</p>
<p>Don't indent code inside <code>namespace ... { ... }</code>.  You can prevent this inside emacs by setting the "innamespace" offset:</p>
<pre>(c-set-offset 'innamespace 0)
</pre>
<h4 name="Classes">C++ classes </h4>
<pre class="brush: cpp">namespace mozilla {
class MyClass : public X
              , public Y
{
public:
  MyClass() : mVar(0) { ... };
  
private:
  int mVar;
};
} // namespace mozilla

</pre>
<p>Existing classes in the global namespace are named with a short prefix (e.g. "ns") as a psuedo-namespace.</p>
<p>For small functions in a class declaration, it's OK to do the above. For larger ones use something similar to method declarations below.</p>
<h4 name="Methods">Methods and functions</h4>
<p>In C/C++, method names should be capitalized and use CamelCase.</p>
<pre class="brush: cpp">int
MyFunction(...)
{
  ...
}

int
MyClass::Method(...)
{
  ...
}
</pre>
<p>Getters that never fail and never return null are named <code>Foo()</code>, while all other getters use <code>GetFoo()</code>. <code>nsresult GetFoo(Foo** aOutFoo)</code> is preferred over <code>Foo* GetFoo(nsresult* aRv)</code>. (See {{ bug("223255") }} for more information.)</p>
<p>In JavaScript, functions should use camelCase but should not capitalize the first letter. Methods should use the named function expression syntax so that stack traces read better:</p>
<pre class="brush: js">doSomething: function MyObject_doSomething(aFoo, aBar) {
  ...
}
</pre>
<p>In-line functions should have spaces around braces, except before commas or semicolons:</p>
<pre class="brush: js">function valueObject(aValue) { return { value: aValue }; }
</pre>
<h4 name="Mode_Line">JavaScript objects</h4>
<pre class="brush: js">var foo = { prop1: "value1" };

var bar = {
  prop1: "value1",
  prop2: "value2"
}; 
</pre>
<p>Constructors for objects should be capitalized and use CamelCase:</p>
<pre class="brush: js">function ObjectConstructor()
{
  this.foo = "bar";
}
</pre>
<h4 name="Mode_Line">Mode line</h4>
<p>Files should have Emacs and vim mode line comments as the first two lines of the file, which should set indent-tabs-mode to nil. For new files, use this, specifying two-space indentation:</p>
<pre>/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
</pre>
<p>Make sure to use the correct "Mode" in the first line—don't use "C++" in JavaScript files.</p>
<h4 name="Operators">Declarations</h4>
<p>Canonical C++ style favors <code>T* p</code> for a typename <code>T</code> and a declarator name <code>p</code>. This style requires programmer discipline to avoid <code>T* p, q;</code> where <code>T* p; T* q;</code> was intended. For new C++ code, this is the best style to use. Watch out for existing modules that use <code>T *p</code> style still (e.g., the SpiderMonkey JS engine).</p>
<h4 name="Operators">Operators</h4>
<p>Overlong expressions not joined by <code>&amp;&amp;</code> and <code>||</code> should break so the operator starts on the second line and starts in the same column as the start of the expression in the first line. This applies to <code>?:</code>, binary arithmetic operators including <code>+</code>, and member-of operators (in particular the <code>.</code> operator in JS, see the Rationale).</p>
<p>Rationale: operator at the front of the continuation line makes for faster visual scanning, because there is no need to read to end of line. Also there exists a context-sensitive keyword hazard in JS, see <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=442099#c19" rel="nofollow" target="_blank">https://bugzilla.mozilla.org/show_bug.cgi?id=442099#c19</a>, which can be avoided by putting . at the start of a continuation line in long member expression.</p>
<p>In JavaScript, <code>==</code> is preferred to <code>===</code>.</p>
<p>Unary keyword operators, such as <code>typeof</code> and <code>sizeof</code>, should have their operand parenthesized; e.g. <code>typeof("foo") == "string"</code>.</p>
<h4>Literals</h4>
<p>Double-quoted strings (e.g. <code>"foo"</code>) are preferred to single-quoted strings (e.g. <code>'foo'</code>) in JavaScript, except to avoid escaping of embedded double quotes or when assigning inline event handlers.</p>
<p>Use <a href="/en/JavaScript/Guide/Obsolete_Pages/Unicode" title="en/Core_JavaScript_1.5_Guide/Unicode"><code>\uXXXX</code> unicode escapes</a> for non-ASCII characters. The character set for XUL, DTD, script, and properties files is UTF-8, which is not easily readable.</p>
<h4 name="Prefixes">Prefixes</h4>
<p>Follow these naming prefix conventions:</p>
<h5 name="Variable_prefixes">Variable prefixes</h5>
<ul> <li>k=constant (e.g. <code>kNC_child</code>). Not all code uses this style; some uses <code>ALL_CAPS</code> for constants.</li> <li>g=global (e.g. <code>gPrefService</code>)</li> <li>a=argument (e.g. <code>aCount</code>)</li> <li>C++ Specific Prefixes<br> <ul> <li>s=static member (e.g. <code>sPrefChecked</code>)</li> <li>m=member (e.g. <code>mLength</code>)</li> </ul> </li> <li>JavaScript Specific Prefixes<br> <ul> <li>_=member (variable or function) (e.g. <code>_length</code> or <code>_setType(aType)</code>)</li> <li>k=enumeration value (e.g. <code>const kDisplayModeNormal = 0</code>)</li> <li>on=event handler (e.g. <code>function onLoad()</code>)</li> </ul> </li>
</ul>
<div class="note">Convenience constants for interface names should be prefixed with <code>nsI</code>:<br>
<code>const nsISupports = Components.interfaces.nsISupports;<br>
const nsIWBN = Components.interfaces.nsIWebBrowserNavigation;</code></div>
<h5 name="Global_functions.2Fmacros.2Fetc">Global functions/macros/etc</h5>
<ul> <li>Macros begin with <code>NS_</code>, and are all caps (e.g. <code>NS_IMPL_ISUPPORTS</code>)</li> <li>Global functions with extern "C" linkage begin with NS_ (e.g. <code>NS_InitXPCOM</code>).</li>
</ul>
<h3>Usage of PR_(MAX|MIN|ABS|ROUNDUP) macro calls</h3>
<p>On certain platforms (eg: FreeBSD which uses gcc42, due to licensing issues with recent gcc versions), the PR_(MAX|MIN|ABS|ROUNDUP) macro calls trigger compiler bugs that cause wrong results in some cases (see <a class=" link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=603880#c7">bug 603880, comment 7</a>). All PR_(MAX|MIN|ABS|ROUNDUP) calls in C++ code (other than that in NSS/NSPR) have been replaced by the equivalent NS_(MAX|MIN|ABS|ROUNDUP) inline calls by <a class=" link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=645398">bug 645398</a> and <a class=" link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=661584">bug 661584</a>. All new code in Firefox/core/toolkit needs to |#include "nsAlgorithm.h"| and use the NS_foo varients instead of PR_foo.</p>
<p>{{ languages( { "ja": "ja/Mozilla_Coding_Style_Guide" } ) }}</p>
Revert to this revision