You must be logged in to do that (write wiki)
Last updated November 02, 2009 13:35, by Bruce Schubert
Feedicon  

Campbell Prediction System

Programming Guidelines

Version 1.0

Bruce Schubert

Revision History

Name Date Reason for Changes Version
Bruce Schubert November 1, 2009 Created. Based on NASA WorldWind guidelines 1.0

Adapted from the NASA World Wind Multi-Platform Design and Coding Guidelines

General

  • Our required target platforms are OS X, Windows XP and Vista, and the most popular versions of Linux. All code and all products must run on all those systems.
  • Read the CPS Software Architecture Document and ew section for a description of World Wind architecture, design and usage. Read the overview pages of each World Wind package for descriptions of those. These descriptions contain critical information that is not repeated elsewhere. To avoid making mistakes, everyone working on World Wind must read them before using or modifying the code.
  • The project's development IDE is NetBeans 6.7.1. TODO: Define the global and local library links, formatting rules, etc.
  • Most major classes need a no-argument constructor so that the declarative instantiation mechanism can work. CPS objects should avoid constructors with arguments so that they can be created generically by name. This means they should self-configure if at all possible, drawing their parametrized info from Configuration. They should also contain an interface to set the configuration details programmatically.
  • Make field and variable names clear and easy to read. Don't label them with "my" or "m_" or some other goofy notation. Within a class refer to all member fields with "this", e.g., this.tileCount.
  • The buffers one must use to pass arrays of info to JOGL must have their byte order set to that of the machine they're used on. Call nativeByteOrder() on NIO buffers when you deal with them, use the methods in com.sun.opengl.util.BufferUtil.
  • Favor immutability (all fields final) in classes representing some small entity like a Point or Vector. Immutable classes are fully thread safe and generally less error prone.
  • Don't worry too much about frequent memory allocations. Java is now so optimized for this that allocating an object on the heap has similar performance to allocating it on the stack, and this includes the cost of garbage collection. There is still a cost to executing any code, however, so be smart about allocation frequency.
  • Configuration items typically have two values and thus two attribute names: a DEFAULT value that is used if not overridden, and a non-default value that can be set programmatically (in Configuration) to a current value without losing the ability to recover the default value.
  • Classes such as BasicDataFileStore and the logger are effectively singletons but they are not defined in their class definition as such. Their singleton nature comes from their 1:1 association with the truly singleton WorldWind class, which provides access to instances of these "singleton" classes.
  • Do not use classes that are not available in the standard 1.5 JRE. Don't incur additional or external dependencies. The only 3rd-party libraries we rely on are NASA WorldWind, VisAD, Weka and JOGL.
  • Do not use GUI builders to generate interfaces for examples or applications. They prevent others from being able to maintain the code.
  • Protect OpenGL state within a rendering unit, such as a layer, by bracketing state changes within try/finally clauses. The util.OpenGLStackHandler utility class makes this easy. It manages both attribute state and matrix stack state. The goal is to isolate any OpenGL state changes to the rendering unit, both when the unit succeeds and when it fails.
  • CPS never crashes. Always catch exceptions at least at the highest entry point from the runtime, e.g., UI listeners, thread run() methods.
  • Within a rendering pass World Wind does not touch the disk or the network. Always fork off a thread to do that. Use the TaskManager and Retriever systems to start threads during rendering. These are set up to govern thread usage to avoid swamping the local machine and the server.
  • Too much micromanagement of state makes the code brittle. Try to design so that the right thing "just happens" once things are set up, and the effect of something going wrong is benign. For example, Layers fork off Retriever objects to retrieve data from the network. But they don't try to keep track of these. If the retriever succeeds then the data will be available the next time the layer looks for it. The fact that it's not there because of a timeout or something tells the layer to ask for it again if it needs it.

Exceptions

  • CPS objects running in the Main thread pass exceptions through to the application layer unless there's good reactive/corrective behavior that can be applied within CPS lower layers.
  • Log any exceptions prior to throwing them. Use the same message for the log as for the exception.
  • Ensure all exception messages are generated using the i18n method details below.
  • Public methods validate their arguments and throw the appropriate exception, typically InvalidArgumentException, and identify the exception message the parameter name and the problem -- null, out of range, etc. See the message resouce file, util.MessageStrings.propoerties, for common messages and their identifiers.
  • In Retriever threads, do not catch Throwable. Catch and react to Exception if there's a good reactive/corrective behavior to apply, otherwise allow them to pass up the stack. Retriever threads should have an uncaught Exception handler specified for the thread. The method should log the Exception or Throwable and then return.
  • Private and protected methods whose calling client can't be trusted validate their arguments and throw an appropriate exception.
  • The audience for exceptions is not primarily the user of the client program, but the application or World Wind developer. Throw exceptions that would let them know immediately that they're using faulty logic or data.

Logging

  • Logging using java.util.logging has the nice feature of capturing the class and method name at the site of the logging call. That's why there is the common idiom of create message, log message, throw exception. Wrapping these three actions in some utility method would lose the class and method-name feature, so don't do that. Don't use any logging system other than that in the JRE.
  • Log all exceptional conditions before rethrowing or throwing a new exception.
  • Ensure all logging uses i18n messages as detailed below.
  • Use level SEVERE for things that prevent the intended action,e.g., file can't be written. Use level WARN for things that don't stop the action but seem exceptional, e.g., a file was retrieved or written redundantly. Use level FINE for simple notifications. Use FINER for method traces. Using the "FINE"series prevents screen display of these when the default JAVA logging settings are used. Since we're a component, we don't communicate such things directly to the application's user; the application does.

Concurrency

  • Use collection classes from the java.util.concurrent package if there's any chance at all that the collection may be accessed from multiple threads.
  • Except for simple atomic variables (but not long or double) the safest way to manage multi-thread access is through the blocking queue classes of java.util.concurrent.
  • Making a class' fields final avoids concurrency problems.

Documentation

  • Use the project's NetBeans build script to generate the product and API documentation.
  • All public and protected classes, methods and fields should be commented for javadoc documentation generation.
  • Descriptions of classes, methods, etc. should start with a capital letter. Parameter descriptions and return-value description should start with a lower-case letter. All descriptions end with a period.
  • If a class overrides methods from {@link Object} such as toString() and equals(), their behavior for the specific class should be described. For equals() that would be the fields compared. For toString() that would be the representation returned.
  • Use links liberally, e.g., {@link WorldWind}. They help the reader get to information fast.

Code Formatting

  • Use the code formatting and style that's in the NetBeans nbproject settings. It makes it possible to review previous code modifications.
  • Use the default code formatting rules specified in NetBeans Tools->Options->Code Formatting for Java.
  • We generally use the traditional Sun coding conventions. Constants are in all upper case with words separated by underscores. Everything else is in camel case. Class names start with an upper case character, variables start in lower case.
  • White space is preferred over packing code into a small space. Please use white space liberally.
  • Set up NetBeans to automatically place the standard GPL license header in newly created files by adding a file named license-gpl-2.0.txt to the Tools->Templates->Licenses folder (BTW: actual location is <user dir>\.netbeans\6.7\config\Templates\Licenses). This license header is selected automatically by the project.license=gpl-2.0 setting in the project's project.properties file. The license file should contain the following contents:
 <#if licenseFirst??>
 ${licenseFirst}
 </#if>
 ${licensePrefix}$Id$
 ${licensePrefix}Copyright (C) 2009, Bruce D. Schubert
 ${licensePrefix}
 ${licensePrefix}This program is free software; you can redistribute it and/or modify it
 ${licensePrefix}under the terms of the GNU General Public License as published by
 ${licensePrefix}the Free Software Foundation; either version 2 of the License, or 
 ${licensePrefix}(at your option) any later version.
 ${licensePrefix}
 ${licensePrefix}This program is distributed in the hope that it will be useful, but
 ${licensePrefix}WITHOUT ANY WARRANTY; without even the implied warranty of
 ${licensePrefix}MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 ${licensePrefix}General Public License for more details.
 ${licensePrefix}
 ${licensePrefix}You should have received a copy of the GNU General Public License
 ${licensePrefix}along with this program.  If not, see <http://www.gnu.org/licenses/>.
 <#if licenseLast??>
 ${licenseLast}
 </#if>  package ${PACKAGE_NAME};

Unfortunately this license set-up is a personal configuration in NetBeans, not project specific.

  • When creating a new file, the Id subversion keyword has to be explicitly set via Version Control --> Set Property --> Property name: svn:keywords, and the term Id included in the text box. If the property is not included in this list then Subversion doesn't replace the property string when updating the file.

Internationalization (i18n)

  • String "constants" are stored in separate resource files (e.g. MessageStrings.properties). These files must end in ".properties" and must be stored in the src directory. Strings are stored with the format: packageOfClass.className.nameOfString=value of the string
  • Access the string constants by using the following pattern: (e.g. Logging.getMessage("myPackage.myClass.targetStringName");).

Books

The books we go back to again and again are the following:

  • Core Java, Horstmann & Cornell, Volumes 1 and 2, Prentice Hall. Be sure to get the editions covering at least J2SE 5. Get the newest edition (currently 8).
  • Effective Java, Second Edition, Joshua Block, Addison Wesley.
  • Java Cookbook, Darwin, O'Reilly

Copyright © 2009 Bruce Schubert, http://www.emxsys.com.

  • Mysql
  • Glassfish
  • Jruby
  • Rails
  • Nblogo
Terms of Use; Privacy Policy;
© 2010, Oracle Corporation and/or its affiliates
(revision 20120518.3c65429)
 
 
Close
loading
Please Confirm
Close