JavaScript:SpiderMonkey:Coding Style: Difference between revisions

Jump to navigation Jump to search
Line 83: Line 83:
  if(condition)            /* bad */
  if(condition)            /* bad */
  if (condition)            /* OK */
  if (condition)            /* OK */
* An opening brace is placed on the same line as the preceding statement.
* In a conditional, if the consequent (and, if present, the alternate) is a single statement, no braces are used.
  if (condition)           /* bad */
  if (today == "Tuesday")
{
    puts("I don't have my wallet on me.");
}
  else
if (condition) {          /* OK */
    puts("I would gladly pay you on Tuesday for a hamburger today.");
  }
However, if ''either'' the consequent or alternate is a block of multiple statements, braces are used on both.
* Do not put compound statements in one line. Indent the controlled statement on the next line, for clarity and break-pointing.
  if (canSwingFromWeb) {
if (condition) break;     /* bad */
     p->swingFromWeb();
if (condition)            /* OK */
  } else {
    break;
    JS_ASSERT(p->isSpiderPig());
* If a statement or condition covers multiple lines, use braces for all the controlled statements (even if the else part fits on one line, brace it too).
     p->doWhateverSpiderPigDoes();
  if (condition)           /* bad */
     CallThisMethod(argument1,
                    argument2);
  if (condition) {          /* OK */
     CallThisMethod(argument1,
                    argument2);
  }
  }
* Conditions with multi-line tests should put the brace on the new line to provide a visual separation between the condition and the body.
  types::TypeSet *types = frame.extra(lhs).types;
  if (JSOp(*PC) == JSOP_SETPROP && id == types::MakeTypeId(cx, id) &&
      types && !types->unknownObject() &&
      types->getObjectCount() == 1 &&
      types->getTypeObject(0) != NULL &&
      !types->getTypeObject(0)->unknownProperties())
  {
      JS_ASSERT(usePropCache);
      types::TypeObject *object = types->getTypeObject(0);
      types::TypeSet *propertyTypes = object->getProperty(cx, id, false);
      ...
  } else {
      ...
  }
However, if there is already a visual separation between the condition and the body, putting the { on a new line isn't necessary:
  if (forHead->pn_kid1 && NewSrcNote2(cx, cg, SRC_DECL,
                                      (forHead->pn_kid1->isOp(JSOP_DEFVAR))
                                      ? SRC_DECL_VAR
                                      : SRC_DECL_LET) < 0) {
      return false;
  }
* <code>for</code> loop heads go on one line where possible; when not possible, initializer part, update, and termination parts each go on separate lines
* <code>for</code> loop heads go on one line where possible; when not possible, initializer part, update, and termination parts each go on separate lines
  for (int i = 0;
  for (int i = 0;
Confirmed users
1,345

edits

Navigation menu