Coding Style

  • Revision slug: Developer_Guide/Coding_Style
  • Revision title: Coding Style
  • Revision id: 435457
  • Created:
  • Creator: Joey Armstrong
  • Is current revision? No
  • Comment

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.

C/C++ practices

  • Have you checked for compiler warnings? Warnings often point to real bugs.
  • In new code, use nullptr for pointers. In old code, using nsnull, NULL or 0 for consistency is allowed.
  • Don't use PRBool and PRPackedBool in C++, use bool instead.
  • When testing a pointer, use (!myPtr) or (myPtr); don't use myPtr != nullptr or myPtr == nullptr.
  • Do not compare x == true or x == false. Use (x) or (!x) instead. x == 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.

Java practices

  • We use the Java Coding Style. Quick summary:
    • FirstLetterUpperCase for class names
    • camelCase for method and variable names
    • One declaration per line
int x, y; // this is BAD!
int a;    // split it over
int b;    // two lines
  • Braces should be placed like so (generally opening braces on same line, closing braces on a new line):
public void func(int arg) {
    if (arg != 0) {
        while (arg > 0) {
            arg--;
        }
    } else {
        arg++;
    }
}
  • Places we differ from the Java coding style:
    • Start class variable names with 'm' prefix (e.g. mSomeClassVariable) and static variables with 's' prefix (e.g. sSomeStaticVariable)
    • import statements:
      • Do not use wildcard imports like `import java.util.*;`
      • Organize imports by blocks separated by empty line: org.mozilla.*, com.*, net.*, org.*, android.*, then java.*
      • Within each import block, alphabetize import names with uppercase before lowercase (so `com.example.Foo` is before `com.example.bar`).
    • 4-space indents
    • spaces, not tabs
    • Don't restrict yourself to 80-character lines. Google's Android style guide suggests 100-character lines. Java code tends to be long horizontally, so use appropriate judgement when wrapping. Avoid deep indents on wrapping. Note that aligning the wrapped part of a line with some previous part of the line (rather than just using a fixed indent) may require shifting the code every time the line changes, resulting in spurious whitespace changes.
  • For more details, see the Coding Style guide for Firefox on Android.
  • The Android Coding Style has some useful guidelines too.

Makefile practices

  • Shell commands are expensive esp for Windows/mingw, so use sparingly.
    • Generate/use pre-computed macro values whenever possible.
    • Use make built-in 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 place dependencies on a directory. Targets become stale when content is added/modified/removed within the directory; this will be addressed by {{ bug(680245) }} when the patch lands.
  • Suffix long if/endif conditionals with #{ & #} so editors can display matching tokens that enclose a block of statements.
    ifdef CHECK_TYPE #{
      ifneq ($(flavor var_type),recursive) #{
        $(warning var should be expandable but detected var_type=$(flavor var_type))
      endif #}
    endif #}
    
  • Launch the 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 no-operation.  Aside from minimal overhead (~traversal) make should return quickly and perform no work.
  • Avoid line continuation within target rules, declare holding macros and populate with values as needed.
  • To format long lines for 80 characters per line, declare macros named for the target and suffixed by their usage -{deps,prereq,tgts}:
    # use: pre-requisites
    export-preqs = \
      foo \
      bar \
      $(NULL)
    
    # use: targets
    export-tgts = \
      fooT \
      $(NULL)
    
    export :: $(export-tgts)
    $(export-tgts): %.in $(export-preqs)
    
  • Write target logic in terms of dependencies to only perform work when needed. Inlining a shell script within make target rules will needlessly do work every time they're invoked.
  • Makefiles should include a dependency on $(GLOBAL_DEPS) so targets will re-generate when a makefile, config.mk, etc is modified.

mozbuild practices

  • In general follow guidelines mentioned in the Python practices section.
  • List assignments should be written with one element per line.  Align closing square brace with start of variable assignment.
var += [
    'foo',
    'bar'
]
  • Use CONFIG['CPU_ARCH'] {=arm} to test for generic classes of architecure rather than CONFIG['OS_TEST'] {=armv7} (re: bug 886689)

Python practices

  • Do not place statements on the same line as if/elif/else conditionals to form a one-liner.
  • Global vars, avoid them at all cost.
  • Exclude outer parenthesis from conditionals.  Use if x > 5: rather than if (x > 5):
  • Use string formatters rather than var + str(val).  var = 'Type %s value is %d' % ('int', 5)
  • Utilize tools like pylint or pychecker to screen sources for common problems.
  • Testing/Unit tests, write them.
  • See also PEP 8 and Code Like a Pythonista.

COM, pointers and strings

  • 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 EmptyString() and EmptyCString() instead of NS_LITERAL_STRING("") or nsAutoString empty;.
  • Use str.IsEmpty() instead of str.Length() == 0.
  • Use str.Truncate() instead of str.SetLength(0) or str.Assign(EmptyString()).
  • 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:

bool 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:

bool val;
rv = foo->GetBooleanValue(&val);
NS_ENSURE_SUCCESS(rv, 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 (size_t 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, or four spaces in Python code.

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 should avoid adding nested namespaces under "mozilla" unless they are meant to contain names which have a high probability of colliding with other names in the code base (e.g., Point, Path, etc.).  Such symbols can be put under module-specific namespaces under "mozilla", with short all-lowercase names.  Other global namespaces besides "mozilla" are not allowed.

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.)

using namespace ...; is only allowed in .cpp files after all #includes. Prefer to wrap code in namespace ... { ... }; instead if possible.  using namespace ...; should always specify the fully qualified namespace.  That is, to use Foo::Bar do not write using namespace Foo; using namespace Bar;, write using namespace Foo::Bar;

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

(c-set-offset 'innamespace 0)

Anonymous namespaces

We prefer using 'static' instead of anonymous C++ namespaces. This may change once there is better debugger support (on Windows especially) for placing breakpoints, etc on code in anonymous namespaces. You may still use anonymous namespaces for things that can't be hidden with 'static' (such as types, or certain objects that need to be passed to template functions).

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=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

Make sure to use the correct "Mode" in the first line—don't use "C++" in JavaScript files. The exception is Python code, in which we use four spaces for indentations.

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 id="General_C.2FC.2B.2B_Practices" 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>").&nbsp; 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://www.oracle.com/technetwork/java/javase/documentation/index-137868.html">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/headers/" title="http://www.mozilla.org/MPL/headers/">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>.</li>
</ul>
<h4 id="C.2FC.2B.2B_practices">C/C++ practices</h4>
<ul>
  <li><strong>Have you checked for compiler warnings?</strong> Warnings often point to real bugs.</li>
  <li>In new code, use <code>nullptr</code> for pointers. In old code, using <code>nsnull</code>, <code>NULL</code> or <code>0</code> for consistency is allowed.</li>
  <li>Don't use <code>PRBool</code> and <code>PRPackedBool</code> in C++, use <code>bool</code> instead.</li>
  <li>When testing a pointer, use <code>(</code><code>!myPtr</code><code>)</code> or <code>(myPtr)</code>; don't use <code>myPtr != </code><code>nullptr</code> or <code>myPtr == </code><code>nullptr</code>.</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>!</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&gt;"><code>DebugOnly&lt;T&gt;</code></a> helper when declaring them.</li>
  <li>You should <a href="/en/Mozilla/Preferences/Using_preferences_from_application_code" title="en/Preferences/Using preferences from application code">use the static preference API</a>&nbsp;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 id="JavaScript_practices">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 id="Java_practices">Java practices</h3>
<ul>
  <li>We use the <a class="external text" href="http://www.oracle.com/technetwork/java/codeconvtoc-136057.html" rel="nofollow">Java Coding Style</a>. Quick summary:
    <ul>
      <li>FirstLetterUpperCase for class names</li>
      <li>camelCase for method and variable names</li>
      <li>One declaration per line</li>
    </ul>
  </li>
</ul>
<pre>
int x, y; // this is BAD!
int a;    // split it over
int b;    // two lines
</pre>
<ul>
  <li>Braces should be placed like so (generally opening braces on same line, closing braces on a new line):</li>
</ul>
<pre>
public void func(int arg) {
    if (arg&nbsp;!= 0) {
        while (arg &gt; 0) {
            arg--;
        }
    } else {
        arg++;
    }
}
</pre>
<ul>
  <li>Places we differ from the Java coding style:
    <ul>
      <li>Start class variable names with 'm' prefix (e.g. mSomeClassVariable) and static variables with 's' prefix (e.g. sSomeStaticVariable)</li>
      <li>import statements:
        <ul>
          <li>Do not use wildcard imports like `import java.util.*;`</li>
          <li>Organize imports by blocks separated by empty line: org.mozilla.*, com.*, net.*, org.*, android.*, then java.*</li>
          <li>Within each import block, alphabetize import names with uppercase before lowercase (so `com.example.Foo` is before `com.example.bar`).</li>
        </ul>
      </li>
      <li>4-space indents</li>
      <li>spaces, not tabs</li>
      <li>Don't restrict yourself to 80-character lines. Google's Android style guide suggests 100-character lines. Java code tends to be long horizontally, so use appropriate judgement when wrapping. Avoid deep indents on wrapping. Note that aligning the wrapped part of a line with some previous part of the line (rather than just using a fixed indent) may require shifting the code every time the line changes, resulting in spurious whitespace changes.</li>
    </ul>
  </li>
  <li>For more details, see the <a href="https://wiki.mozilla.org/Fennec/NativeUI/CodingStyle" title="https://wiki.mozilla.org/Fennec/NativeUI/CodingStyle">Coding Style guide for Firefox on Android</a>.</li>
  <li>The <a class="external text" href="http://source.android.com/source/code-style.html" rel="nofollow">Android Coding Style</a> has some useful guidelines too.</li>
</ul>
<h3 id="General_C.2FC.2B.2B_Practices" 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>Generate/use pre-computed macro values whenever possible.</li>
      <li>Use make built-in functions to perform string manipulation in place of $(shell awk/perl/python/sed/tr).</li>
    </ul>
  </li>
  <li>Use platform values defined by <code>autoconf.mk</code> &amp; <code>configure.mk</code> 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 place dependencies on a directory. Targets become stale when content is added/modified/removed within the directory; this will be addressed by {{ bug(680245) }} when the patch lands.</li>
  <li>Suffix long <code>if</code>/<code>endif</code> conditionals with #{ &amp; #} so editors can display matching tokens that enclose a block of statements.
    <pre>
ifdef CHECK_TYPE #{
  ifneq ($(flavor var_type),recursive) #{
    $(warning var should be expandable but detected var_type=$(flavor var_type))
  endif #}
endif #}
</pre>
  </li>
  <li>Launch the <code>make</code> command twice to verify dependencies:&nbsp;"<code>make ; make</code>".
    <ul>
      <li>Make #1 is the workhorse and will generate everything on the initial pass.</li>
      <li>Make #2 will mostly be a no-operation.&nbsp; Aside from minimal overhead (~traversal) make should return quickly and perform no work.</li>
    </ul>
  </li>
  <li>Avoid line continuation within target rules, declare holding macros and populate with values as needed.</li>
  <li>To format long lines for 80 characters per line, declare macros named for the target and suffixed by their usage -{deps,prereq,tgts}:
    <pre>
# use: pre-requisites
export-preqs = \
  foo \
  bar \
  $(NULL)

# use: targets
export-tgts = \
  fooT \
  $(NULL)

export :: $(export-tgts)
$(export-tgts): %.in $(export-preqs)
</pre>
  </li>
  <li>Write target logic in terms of dependencies to only perform work when needed. Inlining a shell script within make target rules will needlessly do work every time they're invoked.</li>
  <li>Makefiles should include a dependency on <code>$(GLOBAL_DEPS)</code> so targets will re-generate when a <code>makefile</code>, <code>config.mk</code>, etc is modified.</li>
</ul>
<h3 id="General_C.2FC.2B.2B_Practices" name="General_C.2FC.2B.2B_Practices">mozbuild practices</h3>
<ul>
  <li>In general follow guidelines mentioned in the Python practices section.</li>
  <li>List assignments should be written with one element per line.&nbsp; Align closing square brace with start of variable assignment.</li>
</ul>
<pre>
var += [
    'foo',
    'bar'
]</pre>
<ul>
  <li>Use CONFIG['CPU_ARCH'] {=arm} to test for generic classes of architecure rather than CONFIG['OS_TEST'] {=armv7} (re: bug 886689)</li>
</ul>
<h3 id="General_C.2FC.2B.2B_Practices" 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.&nbsp;&nbsp;Use <code>if x &gt; 5:&nbsp;</code>rather than <code>if (x &gt; 5):</code></li>
  <li>Use string formatters rather than var + str(val).&nbsp; <code>var = 'Type %s value is %d'&nbsp;% ('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"><code>pylint</code></a> or <a class="external" href="http://pychecker.sourceforge.net" title="http://pychecker.sourceforge.net"><code>pychecker</code></a> to screen sources for common problems.</li>
  <li>Testing/Unit tests, write them.</li>
  <li>See also <a class="external" href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a> and <a class="external" href="http://python.net/%7Egoodger/projects/pycon/2007/idiomatic/handout.html">Code Like a Pythonista</a>.</li>
</ul>
<h3 id="COM_and_pointers" name="COM_and_pointers">COM, pointers and strings</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>EmptyString()</code> and <code>EmptyCString()</code> instead of <code>NS_LITERAL_STRING("")</code> or <code>nsAutoString empty</code>;.</li>
  <li>Use <code>str.IsEmpty()</code> instead of <code>str.Length() == 0</code>.</li>
  <li>Use <code>str.Truncate()</code> instead of <code>str.SetLength(0)</code> or <code>str.Assign(EmptyString())</code>.</li>
  <li>Don't use <code>QueryInterface</code> directly. Use <code>CallQueryInterface</code> or <code>do_QueryInterface</code> instead.</li>
  <li><code>nsresult</code> should be declared as <code>rv</code>. 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 id="IDL" name="IDL">IDL</h3>
<h4 id="Use_leading-lowercase.2C_or_.22interCaps.22" 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 id="Use_attributes_wherever_possible" 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&nbsp;: 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&nbsp;: nsISupports
{
    attribute long length;
    readonly attribute long color;
};
</pre>
<h4 id="Use_java-style_constants" 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 id="See_also">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 id="Error_handling" name="Error_handling">Error handling</h3>
<h4 id="Check_for_errors_early_and_often" 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 id="Use_the_nice_macros" 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 id="Return_from_errors_immediately" 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)) {
&nbsp;&nbsp;rv = foo-&gt;Call2();
&nbsp;&nbsp;if (NS_SUCCEEDED(rv)) {
&nbsp;&nbsp;&nbsp;&nbsp;rv = foo-&gt;Call3();
&nbsp;&nbsp;}
}
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">
bool 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">
bool val;
rv = foo-&gt;GetBooleanValue(&amp;val);
<code class="cpp plain">NS_ENSURE_SUCCESS(rv, rv);</code>
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 (size_t 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 id="Strings" name="Strings">C++ strings</h3>
<h4 id="Use_the_Auto_form_of_strings_for_local_values" 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 id="Be_wary_of_leaking_values_from_non-XPCOM_functions_that_return_char.2A_or_PRUnichar.2A" 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 id="Use_NS_LITERAL_STRING.28.29_to_avoid_runtime_string_conversion" 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 id="Naming_and_Formatting_code" 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.</em></p>
<h4 id="Whitespace" name="Whitespace">Whitespace</h4>
<p>No tabs. No whitespace at the end of a line.</p>
<h4 id="Line_Length" 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 id="Whitespace" name="Whitespace">Indentation</h4>
<p>Two spaces per logic level, or four spaces in Python code.</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 id="Control_Structures" name="Control_Structures">Control structures</h4>
<p>Use&nbsp;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.&nbsp;</p>
<h4 id="Namespaces" name="Namespaces">C++ namespaces</h4>
<p>Mozilla project C++ declarations should be in the "mozilla" namespace.&nbsp; Modules should avoid adding nested namespaces under "mozilla" unless they are meant to contain names which have a high probability of colliding with other names in the code base (e.g., Point, Path, etc.).&nbsp; Such symbols can be put under module-specific namespaces under "mozilla", with short all-lowercase names.&nbsp; Other global namespaces besides "mozilla" are not allowed.</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.)</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.&nbsp; <code>using namespace ...; </code>should always specify the fully qualified namespace.&nbsp; That is, to use <code>Foo::Bar </code>do not write <code>using namespace Foo; </code><code>using namespace Bar;</code>, write <code>using namespace Foo::Bar;</code></p>
<p>Don't indent code inside <code>namespace ... { ... }</code>.&nbsp; You can prevent this inside emacs by setting the "innamespace" offset:</p>
<pre>
(c-set-offset 'innamespace 0)
</pre>
<h4 id="Anonymous_namespaces">Anonymous namespaces</h4>
<p>We prefer using 'static' instead of anonymous C++ namespaces. This may change once there is better debugger support (on Windows especially) for placing breakpoints, etc on code in anonymous namespaces. You may still use anonymous namespaces for things that can't be hidden with 'static' (such as types, or certain objects that need to be passed to template functions).</p>
<h4 id="Classes" name="Classes">C++ classes&nbsp;</h4>
<pre class="brush: cpp">
namespace mozilla {

class MyClass&nbsp;: 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 id="Methods" 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:&nbsp;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 id="JavaScript_objects" name="JavaScript_objects">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 id="Mode_Line" 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=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

</pre>
<p>Make sure to use the correct "Mode" in the first line—don't use "C++" in JavaScript files. The exception is Python code, in which we use four spaces for indentations.</p>
<h4 id="Operators" name="Operators">Declarations</h4>
<p>Canonical C++&nbsp;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++&nbsp;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&nbsp;engine).</p>
<h4 id="Operators" name="Operators">Operators</h4>
<p>Overlong expressions not joined by <code>&amp;&amp;</code>&nbsp;and <code>||</code>&nbsp;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 id="Literals">Literals</h4>
<p>Double-quoted strings (e.g. <code>"foo"</code>)&nbsp;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 id="Prefixes" name="Prefixes">Prefixes</h4>
<p>Follow these naming prefix conventions:</p>
<h5 id="Variable_prefixes" 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>&nbsp;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
    <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
    <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 id="Global_functions.2Fmacros.2Fetc" 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 id="Usage_of_PR_(MAX.7CMIN.7CABS.7CROUNDUP)_macro_calls">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