Access Keys:
Skip to content (Access Key - 0)

Source Code Conventions

These guidelines should be followed for all new source files added to the repository. If you're making changes to existing source files, make a best guess on what the used convention is and try to follow it. Do avoid reformatting existing source.

Java Source Code Conventions

Some basic ground rules for Java source code:

In general avoid reformatting code unless necessary. Reformatting code is a sure way of getting into an unsortable Subversion merge mess. Only reformat an existing source if you know for certain that no one else is working in the same area (i.e. you're currently the sole owner of the area of code in question). If you do decide to reformat code (you probably shouldn't so stop right there) then always commit the reformatting separate from any and all code changes – otherwise your code changes will be impossible to find from the diffs and are at great risk of being rejected altogether.

Given all of the above, you don't want to reformat existing source files. Therefore, the code conventions below apply only when developing new code on new source files. (The legacy code will get reformatted to conventions by those who will have sole ownership of the codebase at specific periods of time).

1. Always use soft tabs (spaces), never ever use real hard tab characters
2. Indent with 2 spaces (4 spaces for line continuations)
3. Limit source lines at 100 characters
4. For indentation and braces, use ANSI style, i.e.


public class Foo extends Bar implements Acme
{

  protected void doSomething()
  {
    while (x == y)
    {
      something();
      somethingElse();
    }
 
    finalThing();
  }
}

5. Add a license at the top of each source file, before the package declaration

/*
 * OpenRemote, the Home of the Digital Home.
 * Copyright 2008-2011, OpenRemote Inc.
 *
 * See the contributors.txt file in the distribution for a
 * full listing of individual contributors.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

6. Format JavaDoc comments as follows:

  /**
   * Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor 
   * incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud 
   * exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute 
   * irure dolor in reprehenderit in voluptate velit esse 
   *
   * @see org.openremote.controller.foo.Bar
   * @see org.openremote.controller.bar.Foo
   *
   * @param foo     lorem ipsum dolor sit amet
   * @param bar     consectetur adipisicing elit
   * @param acme    Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
   *                Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris 
   *                nisi ut aliquip ex ea commodo consequat.   
   *
   * @return    Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris 
   *            nisi ut aliquip ex ea commodo consequat.  
   *
   */

Alternative formatting for @param, @throws and @return elements is also acceptable:

  /**
   * Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor 
   * incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud 
   * exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute 
   * irure dolor in reprehenderit in voluptate velit esse 
   *
   * @param myLongParamName     
   *            lorem ipsum dolor sit amet
   *
   * @param anotherParamName     
   *            consectetur adipisicing elit
   *
   * @param theFinalParamName    
   *            Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
   *            Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris 
   *            nisi ut aliquip ex ea commodo consequat.   
   *
   * @throws OpenRemoteParameterException
   *            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor 
   *            incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud 
   *            exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute 
   *            irure dolor in reprehenderit in voluptate velit esse 
   */

iOS Source Code Conventions

These guidelines are based on the Zarra Studios public guidelines available at http://www.cimgf.com/zds-code-style-guide/ but have been adapted for the OpenRemote project.

1. Spacing

Code is to be indented 2 spaces and no tabs. If you want to wrap a long line of code then make sure it is colon aligned per Xcode's formatting. However I prefer if you did not wrap the lines. Xcode formats them rather nicely.
Keywords such as if, while, do, switch, etc. should have a space after them.
Wasted vertical space should be avoided. There should be only one empty line between methods.

2. Brackets

Method brackets should be on the following line and flush left. Code should be indented 2 spaces from the opening bracket.
When brackets are needed in a switch they are to be left aligned with the case line and on their own line. NOTE: brackets in switches should be avoided.
All other brackets should inline.

3. Method signatures

Method signatures should be left aligned. There should be a space after the scope (the plus or the minus sign). There should be a space between the method segments.
There should be a space between the class name and the pointer character (*), not after.

4. Booleans

Objective-C uses YES and NO. Therefore true and false are incorrect. Also since nil resolves to NO it is unnecessary to compare it in conditions. For example:

if (someObject == nil) ...

Is redundant and should be written as:

if (!someObject) ...

Likewise, if a method call returns a BOOL then checking it against a BOOL is redundant.

if ([someObject boolValue] == NO) ...

is incorrect and should be written:

if (![someObject boolValue]) ...

5. Variable names

Variable names should be descriptive of what they represent. Single letter variable name should never be used, except for incrementers.

6. Empty methods

Any method that is empty or just calls super should be removed from the source code as they are redundant.
In case a method is required by the implementation of a protocol and nothing should be done, a single comment line must be used to indicate this is intentional.

7. Comments

Comments should be rare. Code is easier to read than comments. Comments go stale, code doesn't. The only comments should be along the lines of:

/* We are doing this in a strange way because the normal solution resulted in ...
 * Therefore this solution is the correct one.
 */

If the code is self explanatory (as it should be with descriptive variable names and methods) then comments are not necessary.

8. dealloc

-dealloc is important and should be placed directly below the -init methods of any class. If there are no -init methods then it should be the first method after class level methods.

9. @synthesize and @dynamic

Both @synthesize and @dynamic are boiler-plate code. They should be put at the top of the class just below the @implementation. Each @synthesize and @dynamic should be on a single line.

10. @property

Property definitions should be used in place of iVars. As of Xcode 3.2.5, we should no longer be declaring iVars at all. This will help to insure proper memory management. In addition, direct iVar access should be avoided except during initialization of the variable and in the -viewDidUnload and -dealloc methods.

11. Protocols

Protocol implementations should be separated out by #pragma marks.

12. Code width

Code should not be set to an arbitrary width. We have wide monitors and an editor that smart wraps the code. Do not limit code to 80 columns or any other arbitrary width unless it is to be printed.

GWT tips / guidelines

Not really coding conventions per se but some explanations on how we architect some of the features implemented in the modeler.

File upload in wizards

Summary: have a wizard that takes a file uploaded by user and allows creation of "objects" in the designer. The file is first loaded and the GUI updated with the information read from the file. Upon confirmation, the import happens and the wizard window is closed.
With current technology, the file must be sent to the server for processing and cannot be directly processed on the client side. This is something that might change in the future.

Have a FileUpload element in the form for the user to select a file. The import button submits the form.
The form must be configured as follows:

    uploadForm.setEncoding(FormPanel.ENCODING_MULTIPART);
    uploadForm.setMethod(FormPanel.METHOD_POST);
    uploadForm.setAction(GWT.getModuleBaseURL() + "fileUploadController.htm?method=importLutron");

The name after the method= part being specific to each wizard. This names corresponds to the method name in the FileUploadController class that will handle that particular import.

The import routine processes the file and extracts the information required to:

  • display appropriate information to the user to decide what to import
  • have enough information for the creation of objects by the final import routine
    This information is packaged in a JSON structure that is returned as the response of the POST request.

Import: you must set the response content to text/html for the JSON structure to be correctly retrieved by GWT. This is done with

      response.setHeader("content-type", "text/html");

The most efficient way to process and use the returned JSON structure in the GWT client is the use JavaScript Overlays.

This is for instance the top level overlay used by the Lutron Homeworks import wizard:

public class LutronImportResultOverlay extends JavaScriptObject {

  // Overlay types always have protected, zero-arg ctors
  protected LutronImportResultOverlay() { } 
    
  // Typically, methods on overlay types are JSNI
  public final native String getErrorMessage() /*-{ return this.errorMessage; }-*/;

  public final native ProjectOverlay getProject() /*-{ return this.project; }-*/;

  public static native LutronImportResultOverlay fromJSONString(String jsonString) /*-{
    return eval('(' + jsonString + ')');
  }-*/;
  
}

Note that this object also includes an errorMessage field. This is the mechanism used to report errors occurring on server side (e.g. bad file format) to the client.

Having this in place, the return of the form submit can be handled with code such as

    uploadForm.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
    
      @Override
      public void onSubmitComplete(SubmitCompleteEvent event) {
        LutronImportResultOverlay importResult = LutronImportResultOverlay.fromJSONString(event.getResults());
...

Added by Administrator , last edit by Eric Bariaux on Feb 07, 2012 15:22

© 2008-2011 OpenRemote Inc. OpenRemote is a trademark of OpenRemote, Inc.
Adaptavist Theme Builder (3.3.3-conf210) Powered by Atlassian Confluence 2.10.3, the Enterprise Wiki.
Free theme builder license