OMaxy


omaxy » development » developer-guidelines

Coding Standards & Best Practices

 
Keywords: java coding standards, coding conventions, guidelines, best practices, coding style, recommendations.

Introduction

This document consolidates the best practices and recommendations of the Java developers community gained from the past ten years of language use and experience with other languages containing some companion information describing style guidelines for the HTML/JSP/JavaScript code.

The recommendations are based on established standards collected from a number of sources (adapted from Code Conventions for the Java Programming Language), individual experience, local requirements/needs, as well as suggestions, thoughts and phrases given in [2], [3], [4] and [4]. Where there's conflict, this style rules for the purposes of this guide. This guide may still be incomplete (in fact, it may never be finished).

TODO: Incorporate http://wiki.services.openoffice.org/wiki/Coding_Standards.

Why Coding Standards?

If you don't know why coding standards are important read these explanations first.

A foolish consistency is the hobgoblin of little minds. Use common sense and BE CONSISTENT. Design for extensibility. You are gonna need it. [Rationale: Long and painful experience.]

Coding standards:

  • improve readability by ensuring a “common look and feel” to the code regardless of how many people have worked on it. community gained from the past five years of language use (and experience with other
  • improve understandability by ensuring that basic documentation is always present
  • improve maintainability by improving the predictability of the code

If you're editing code, take a few minutes to look at the code around you and determine its style. If they use spaces around all their arithmetic operators, you should too. If their comments have little boxes of hash marks around them, make your comments have little boxes of hash marks around them too.

The point of having style guidelines is so that people can concentrate on what you are saying, rather than on how you are saying it. We present global style rules here so people know the vocabulary, but local style is also important. If code you add to a file looks drastically different from the existing code around it, it throws readers out of their rhythm when they go to read it. If everyone follows the standards, you feel comfortable using your colleague's code because it seems like your own code.

The content of a style guide might cause debate and disagreement, but it is essential to stick to a consistent style.There is nothing worse then spaghetti and messy or sloppy code (especially when it is time to change the way something works).

One of guide's key insights is that code is read much more often than it is written. The guidelines provided here are intended to improve the readability of code and make it consistent across the wide spectrum of code. "Readability counts".

A style guide is about consistency. The most important code style rule is that when you modify somebody else's code, you preserve the coding style in that file. Even when it hurts. The only thing worse than an "incorrectly" styled source file is an inconsistently styled one! Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is most important.

But most importantly: know when to be inconsistent -- sometimes the style guide just doesn't apply. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don't hesitate to ask!

Sometimes conventions rely more on taste than reason. In that case look at it this way:

It's irrelevant if people drive on the right or left side of the road. As long as they all do the same.

It is not implying there will be fatal accidents if your fellow programmers use different styles. But it will definitely contribute to the success for your project if you are able to agree on some standards.

Two good reasons to break a particular rule:

  1. When applying the rule would make the code less readable, even for someone who is used to reading code that follows the rules.
  2. To be consistent with surrounding code that also breaks it (maybe for historic reasons) -- although this is also an opportunity to clean up someone else's mess (in true XP style).

There is no "best" style that everyone should be following. Actually, the best style, is a consistent style. If you are part of a team or if you are contributing code to a project, you should follow the existing style that is being used in that project.

Code readability is a universal subject in the world of computer programming. It's one of the first things we learn as developers. Readable and maintainable code is something to be proud of in a finished product. We can share it with others, contribute to other projects, and reuse code from applications we wrote months or even years ago.

So just make your code simpler, cleaner, easier to read and following a convention/coding standard. When you code something you should keep it in mind that some other coder may work on it in future.

Principles

General

  1. Adhere to the style of original.
  2. Adhere to the Principle of Least Astonishment.
    Simpicity, clarity, completeness, consistency, robustnes.
  3. Do it right the first time. Don't create development debt.
  4. Document any deviations.

DRY Principle

  • DRY stands for Don't Repeat Yourself. Also known as DIE: Duplication is Evil.
"Every piece of knowledge must have a single, unambiguous, authoritative representation within a system."
The purpose for most applications (or computers in general) is to automate repetitive tasks. This principle should be maintained in all code, even web applications. The same piece of code should not be repeated over and over again.

OO Design Principles

Code Lay-out

Tabs or Spaces?

  • ALWAYS use hard tab character instead of multiple spaces. Tabulations against the evil Spacebar Empire.
  • Any decent editor (even vi) allows you to set tab size. Usually tab take 4 spaces in size. But you can choose anything you want as we use tabs!

Indentation

  • Use 1 tab per indentation level (everywhere in Java, JavaScript, XML).
  • Continuation indent is 2 tabs (e.g. wrapping method parameters, long strings etc).
  • Do not leave trailing whitespaces in code and blank lines.
if (!Phase.isStoregeBeforeActivation()) {
    phase = (phase == Phase.ACTIVATION) ? Phase.STORAGE // One indent here because it is simply start of inner block of code.
            : (phase == Phase.STORAGE) ? Phase.ACTIVATION // Continuation indent of above line, so 2 tabs.
                    : phase; // Again continuation of above line so 2 tabs + 2 tabs.
}

String sql = "SELECT COUNT(*) FROM user_" + userId + " u "
        + "WHERE u.user_name = " + userName; // Continuation of the above line, so indenting with 2 tabs.

Note the positions of :?+ in the example above when line is wrapped - they should start the line (to be visible), not to end it. FIXME: This conflicts with Google Styleguide.

Maximum Line Length and Wrapping

There is no line hard limits but you should try not exceed a common line length. The key issue is readability. But if you need a limit aim for 100 characters if it is convenient, it is not recommended to use more than 160 characters. There shouldn't be need for wrapping a line. Do not overuse chaining of methods, try to split expression and use local variables facilitating in self-documenting the code. Never join lines with several statements.

Wrapping Arrays

If you have simple array declare it on one line, for more complex arrays and especially those that will change often use a break after each value, always after a comma, lining up with the first element with an continuation indent of 2 tabs. You should always include a dangling comma in arrays, especially when exceeding one line, to reduce the patched lines, when adding values to the array later. Example:

String[] exportFileExtensions = new String[] {
        ".csv",
        ".txt",
        ".pdf",
};

Wrapping Method Declarations

If you have so many parameters (usually more then tree) - refactor to to use separate classes for them.

Wrapping Control Structures

If you have too many conditions in one control structure, refactor them out to local variables before the start of the structure to improve readability.

Line Termination

Prefer to use standard Unix text format. Lines must end only with a linefeed (LF) if file is going to be viewed/edited on linux.

Lines should not contain trailing spaces. In order to facilitate this convention, most editors can be configured to strip trailing spaces, such as upon a save operation. However, if you are editing an existing file and are planning to submit your changes, please switch off that feature so that whitespace changes do not pollute SCM history (other developers will have trouble viewing what you've done if every other line has been edited for whitespace).

Avoid Deep Nesting

Too many levels of nesting can make code harder to read and follow. For the sake of readability, it is usually possible to make changes to your code to reduce the level of nesting, such as extraction to separate method.

Braces

  • Open brace at end of line.
    Curly braces go on the same line as the code construct they belong to (at whatever they're opening).
  • Close brace appears by itself on the line.
    The trailing brace is on its own line and lined up vertically with the keyword.
  • Always use a block statemens (curly brace scope) in an in controll flow constructs, even if they contain a single statement.

Blank Lines and Code Grouping

  • Use blank between logical sections inside a method to improve readability. To group logical sections, logically related pieces of code, structural code groups or for code blocks (list of statements surrounded by curly braces), e.g. before "{" after "}", but not when parent block started/ended. Separate blocks could be organized along the lines of type of activity: e.g. declaring/initializing variables, checking parameters, computing results, returning results, and printing debug output or logging statements. So you should surround with blank lines variables declaration/initialization, logging statements etc. This practice is applied recursively for subblocks within other blocks (e.g. while loop in the method).
  • Between the local variable and its first statement.
  • Use blank lines before comments, return/continue/break/exit (remember returning results above?).
  • BUT: Do not leave blank lines after indentation start and before indentation end, e.g. after open brace and before closing brace, as indentation already emphasizes the visual separation of each block of code. The opening brace should always be written on the line beside the class/method/control structure and no empty line should follow it.
  • Only keep very related/simple lines of code right up next to each other, making paragraphs in a sense.
  • End file with one (and only one) new line.
    Do not append extra (more then one) blank lines.
    For PHP, there must not be a closing '?>' (PHP) or more white-spaces/empty lines in the end of the file. Also use full syntax.
public class Foo {
    private static final Logger LOG = LoggerFactory.getLogger(Foo.class);

    /**
     * Creates instance of {@code Foo} if it is visible and within coordinates.
     *
     * @param a Indicates if foo is visible.
     * @param x X coordinate.
     * @param y Y coordinate.
     * @param z Z coordinate.
     * 
     * @return New instance or {@code null} if not visible and out of coordinates.
     * 
     * @throws OutOfFooException If such coordinates are not acceptable for {@code Foo}.
     *
     * @todo (reporterDeveloper1)[assigneeDeveloper2] Refactor this method breaking into smaller parts as it is too long, complex and has deep nesting.
     */
    public Foo createFoo(boolean a, int x, int y, int z) throws OutOfFooException {
        Foo foo = null;

        doSomethingTo(x);
        doSomethingElseTo(x);
        andThen(x);

        nowDoSomethingWith(y);

        andNowWith(z);

        do {
            try {
                if (x > 0) {
                    int someVariable = a ?  x : y;
                } else if (x < 0) {
                    // Group comment follows by blank line to indicate that it applies to all the code below.

                    int someVariable = (y + z);

                    someVariable = x = x + y;

                    foo = new Foo(someVariable);

                    foo.setX(x);
                    foo.setY(y);

                    foo.execute();
                } else {
                    LOG.info("Counting items...");

                    for (int i = 0; i < 5; i++) {
                        // TODO: [reporterAndAssigneeDeveloper3] Ensure it is possible to do something here.
                        doSomething(i);
                    }

                    LOG.info("Finished counting items...");
                }

                switch (a) {
                    case 0:
                        doCase0();

                        break;
                    default:
                        doDefault();
                }
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);

                processException(e.getMessage(), x + y, z, a);

                return null;
            } finally {
                cleanSomethingUp();
            }
        } while (true);

        while (x < 50000) {
            x++;
        }
    }

    private static class InnerClass implements I1, I2 {
        public void bar() throws E1, E2 {
        }
    }

    public Person(
            @InjectProperty("firstName") String firstName, 
            @InjectProperty("lastName")  String lastName
        ) {
        this.firstName = Assert.hasText(firstName);
        this.lastName = Assert.hasText(lastName);
    }
}

Note correct indentation, blank lines both in the code and comments and brace style. Blank lines and spaces make reading the source code much easier and faster.

Whitespace in Expressions and Statements

The use of whitespace should follow longstanding English reading conventions. Such that, there will be one space after each comma and colon (and semi-colon where applicable), but no spaces immediately inside the right and left sides of parenthesis. In short, we advocate readability within reason. Additionally, braces should always appear on the same line as their preceding argument.

Add whitespace before colon (:) in for-loop (as it means "in" here and should be separated as in natural language):

for (String color : colors)

for (String color: colors)

Also surround colon (:) with spaces in ternary operator to balance both switches:

boolean isAuthorized = (user != null) ? user.isAuthenticated() : user.isManager();

But put colon without space before it switch/case statements as in above example.

Compound statements (multiple statements on the same line) are generally discouraged. Wrap them at least. Wrap at '?' and ':' so that related statements are one above another:

boolean isAuthorized = (user != null)
        ? user.isAuthenticated()
        : user.isManager()
                ? user.isCorporate()
                : user.isCeo();

Encodings

  • UTF-8

Imports

  1. Do not use wildcards in import.
    Import statements be fully qualified e.g. import java.util.List and not java.util.*
  2. Should be sorted alphabetically, separated in groups (each group separated with a blank line):
    • static imports group (should rarely be used)
    • java, javax, then org and com package import groups
    • other imports
    import static java.lang.Math.min;
    import static java.lang.Math.max;
    
    import java.util.List;
    
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    import com.google.gwt.user.server.rpc.RemoteServiceServlet;
    
    import de.schlichtherle.io.File;
    import nl.nusoap.Soap;
    
  3. Always remove unused imports (don't comment them out).

Comments

Though a pain to write, they are absolutely vital to keeping our code readable. The following rules describe what you should comment and where. But remember: while comments are very important, the best code is self-documenting. Giving sensible names to types and variables is much better than using obscure names and then trying to explain them through comments. Need for comments is usually treated as "code smells" suggesting that the code needs improvement, because it isn't clear enough to stand alone. First action is to improve the code to be more clear. Whatever you cannot make clear in code, you then comment. Describe concepts in comments.

When writing your comments, write for your audience: the next contributor who will need to understand your code. Be generous — the next one may be you!

  1. Source code comments should be written in clear, concise, English sentences.
  2. Coding is about communicating your intent.
  3. "Purpose of the comment is to explain code that doesn't explain itself." Don't use comment when you can use function or variable.
  4. Write comments for those who use and for those who maintain your code. Assume familiarity with Java but not with your application.
  5. Code should be commented to indicate what the code does (the intent, purpose or usage), rather than how it works internally, which can help you find bugs when those two don’t match. It's usually not difficult to see what a single line of code does. The tricky thing is to see why it's doing what it does.
  6. Comments need not be only to explain the code. The code is usually the solution, comments should explain the problem.
  7. Describe why the code is doing what it's doing, not what it does. What were you thinking when you wrote this code?
  8. "Good comments don't repeat the code or explain it. They clarify its intent. Comments should explain, at a higher level of abstraction than the code, what you’re trying to do.'  (Code Complete, McConnell)
  9. "Comments often are used as a deodorant." ("Refactoring: Improving the Design of Existing Code, Martin Fowler)
  10. Comments should explain the context that each routine fits into. Good code can make clear how it works, but not how it fits into the larger picture.
  11. Comments should not be used to teach the reader how to program. Assume the reader knows as much about the programming language as you do.
  12. Comments should not be used to describe obvious code. The purpose of comments is to increase your code readability. Often using good variable and method names make the code easier to read than if too many comments are present.
  13. Comments that contradict the code are worse than no comments. Always make a priority of keeping the comments up-to-date when the code changes!
  14. Comments should be complete sentences. If a comment is a phrase or sentence, its first word should be capitalized, unless it is an identifier that begins with a lower case letter (never alter the case of identifiers!).
  15. Avoid sentence fragments. Start sentences with a properly capitalized word, and end them with punctuation. Block comments generally consist of one or more paragraphs built out of complete sentences, and each sentence should have trailing punctuation.
  16. Write in English only, Strunk and White applies.
  17. Avoid obvious comments. But answer the question why you are doing it. Commenting the code is great; however, it can be overdone or just be plain redundant. When the code text is obvious, it's really not productive to repeat it within comments, but always add comments when they are really useful. Better spend time thinking about proper variable/method name for it to be self-describing. And of course for simple getters/setters the description can be omitted.
  18. Never "comment out" code without also including a description of why you did so. If the code isn’t necessary it should be deleted. It's hard enough reading live code. SCM systems hold old code.
  19. Keep comments and code in sync.
  20. Do not use "clutter" comments, such as an entire line of asterisks. Instead, use a single blank line line to separate comments from code.
  21. Use active voice and omit needless words. Use forceful, clear, concise language.
  22. Comments should not include humorous remarks. Your comments may seem funny to you when you type them, but they won't to the person who has to understand and fix your code during a late-night debugging session.
  23. Include Task-List keyword flags to enable comment filtering.
  24. All comments should pass spell checking. Misspelled comments indicate sloppy development.

Block Comments

  •  Use standard to hide code without removing it if it may be needed. Remember your SCM may do better job to keep history of your changes.

Inline Comments

  1. Do not put inline comment on the same line as a statement (trailing), but right above it.
  2. Comments lines should begin with // indented at the same level as the code they are documenting.
  3. Comments should be indented to the same margin as the code they pertain to.
  4. Inline comments are unnecessary and in fact distracting if they state the obvious.
  5. If line deserves comment, it most oftent should be treated as logical block with comment and so have to have blank lines around.

Documentation Strings (JavaDoc)

  1. Use consistent format and organization for all JavaDoc comments.
  2. Use fixed ordering for JavaDoc tags.
  3. Describe programming interface before your write the code. This can be your "design phase".
  4. Write summary descriptions that stand alone.
    First sentance must summarize behaviour.
  5. Write in third person narrative form. E.g. "Gets...", "Sets...", "Allocates...".
  6. Omit the subject in summary description:
    Not: "This method clears the foo".
    Instead: "Clears the foo."
    Class and method descriptions should start with a sentence written in the third person declarative voice.
  7. Complex algorithms or implementation should be described in-depth in the class or method headers.
  8. Document all your methods even the private ones if they are complex. Document it in a concise fashion, as other developers will have to go through your code. Some people may argue that ...the source code should speak for itself, but usually it's not that simple. Of course that well made code is essential, but a short overall description of the method is essential as well. Don't expect everyone to read each line of code to understand what's going on.
  9. Wrap keywords with {@code SomeClass} tag.
  10. Consider use of @link and @see tags.
  11. Provide summary description and overview of each package.
  12. Two great pitfalls regarding documenting source code are over-commenting and cryptic commenting.
  13. The whole idea behind commenting is to give a hint to next developer of what's going on. So all Java Docs should bring a short description of why in addition (or not) of what they do. Usually focusing on the why and not on the what/how makes comments shorter.
  14. Always when necessary, specially when you're doing a business logic that may not be obvious at a first sight.
  15. @author either should be used consistently in the code or should not be used at all. Especially if your SCM explains much more who has done what with the specific class than just a name.

Unit tests are also documentation. The unit tests show how to create the objects, how to exercise the objects, and what the objects will do. This documentation, like the acceptance tests belonging to the customer, has the advantage that it is executable. The tests don’t say what we think the code does: they show what the code actually does.

Naming Conventions

  1. First and foremost, be consistent.
  2. Use meaningful names.
    No one character names (except index vars).
  3. Use whole English words.
  4. Classes variables and methods are to be given names, which explain their content/functionality. It should answer questions:
    • Why it exists?
    • What it does?
    • How it is used?
  5. It is no problem to have long names, as long as they reflect the purpose of the variable/method. If name requires a comment, then the name doesn't reveal it's intent. However, all well-named variables tend to be concise. But question exclusively long names as they may indicate need to refactor/redesign.
  6. Other naming practices:
    • Avoid names which does not give additional meaning or are unclear.
    • Do not abbreviate words (such as num). Unless the abbreviation is very common, unambiguous and is much more widely used than the long form, such as url, html, min/max.
    • Avoid using inherently ambiguous names.
    • Choose names for different identifiers that are "psychologically distant" in order to avoid confusion.
    • Distinguish multiple words in a name using lowerCamelCase notation, i.e. itemList. This applies to class as well as method, function and variable and parameter names in Java/JavaScript/HTTP.
    • Capitalize SQL special words. Database interaction is a big part of most web applications. If you are writing raw SQL queries, it is a good idea to keep them readable as well. Even though SQL special words and function names are case insensitive, it is common practice to capitalize them to distinguish them from your table and column names.
    • Use "-" as word separator for file names, in URL parameters, HTML tag names IDs, attribute names and in CSS selectors, instead of "_". "-" is more usual for XML elements as separator than lowerCamelCase style also you will have nicer URLs with all chars lower-cased.
    • Class/object/page name should be noun followed by verb if needed: e.g. ItemRepository, ItemService, ItemListController, ItemViewController, ItemEditController, item-edit.jsp or better item/edit.jsp, item/list.jsp etc.
    • Use short names for standard JSTL tags, e.g. c:if instead of core:if.

Package Naming

  1. Use single lowercased word as a root name for each package.
  2. Use reserved internet domain names as a page prefix.
  3. Package names should only contain alpha-numberic characters.
  4. Package names should be suffixed with the name of the module in which they are defined.

For example, if the module name is common, then the base package name should be com.company.product.common.

Class / Interface Naming

  1. Class names should be nouns unless you have a good reason for it not to be a noun. Try to keep your class names simple and descriptive.
  2. Use singular form of noun whenever possible.
  3. Interface names often end in "able," especially if they have one method: calculable, changeable, chargeable, commensurable, committable, communicable, compellable, computable, doable, igniteable, implementable, moveable, paintable, plugable, printable, realizeable, runnable, serializable, terminable, throwable, tolerable, traceable, transferable, transmittable, transposable, transportable, traversable, triable, usable, variable, venerable, etc.

Method Naming

  1. Name methods using verb-object pair, such as showDialog() or findFirstBoundaryPoint(). Method names should be verbs or verb phrases to show the action the method is providing or performing name them after what method does (or better yet, why you want whatever it does done), don't name methods after how it works. See Intention Revealing Names.
  2. Verbosity is encouraged: method names should be as illustrative as is practical to enhance understanding, as they should describe the use and functionaltiy itself. It should tell the story of the system, but remember that functions should be small (do one thing).
  3. The name of the object is implicit, and should be avoided in a method name.
  4. The terms get/set must be used where an attribute is accessed directly.
  5. Method with return values should have a name describing the value returned, such as getObjectState().
  6. Methods or functions returning a boolean type should generally start with verb is, or alternatives that fits better in some situations like has/have, can or should, etc. [Rationale: Using the is prefix solves a common problem of choosing bad boolean names like status or flag. isStatus or isFlag simply doesn't fit, and the programmer is forced to chose more meaningful names.]
    For example:
    • isValid, isSet, isVisible, isFinished, isFound, isOpen
    • boolean hasAllAttributes();
    • bool canUpdate();
    • boolean haveAllDate();
    • boolean shouldAbort = false;
  7. The term compute can be used in methods where something is computed. [Rationale: Give the reader the immediate clue that this is a potential time consuming operation, and if used repeatedly, he might consider caching the result. Consistent use of the term enhances readability.]
  8. The term initialize can be used where an object or a concept is established. The American initialize should be preferred over the English initialise. Abbreviation init must be avoided.
  9. The term find can be used in methods where something is looked up.
  10. Finally sort all methods in the class from most simple / public / abstract (descriptive and easy to understand what class does in general) to most complext / private.

Variables Naming

  1. In general variables should be named so that they make it clear what it contains.
  2. Variable names should always be easy-to-read, be short yet meaningful, mixed case with a lower-case first letter English words.
  3. Use plural names for arrays/collections of objects.
  4. Generic variables should have the same name as their type.
  5. Unacceptable are the names, that don't contain any description of the variable, or such description is misleading.
  6. Types provide good roots for variable names, e.g. resetButton. But prefer not to use type information in names where more generic form could be enough e.g. instead userList. could be users (imagine that you change type list to collection or set). Spelling similar concepts similarly is information. Using inconsistent spelling is disinformation.
  7. Always self-describing names., i.e., slashIndex instead of idx, or nodeCount instead of cnt, or columnNumber instead of colnum.
  8. Use standard "throwaway" variable names, e.g.:
    • index: i, j, k
    • exception: e, or if there are multiple use full name e.g.: sqlException
    • generic type variable: T (type), S (struct?), E (enum), K (key), V (value)
  9. All identifiers should have meaningful names - meanginful to people who do not know about the program. Occasionally, single letter loop indices like i for an int or o for an Object are acceptable. But do not overlook other possibilities like index, row or column.
  10. Constant (static final) variable names should me in all capital letters and separate words in the name with the underscore, i.e., PRIORITY_NORMAL, PRIORITY_HIGH, DEFAULT_PRICE_PER_POUND or LOG. Note related constants start with the same prefix, or better consider to use Java 5 Enum type.

Abbreviations and Acronyms

  1. Capitalize only first letter in acronym, e.g. getXmlNode, not getXMLNode.
  2. When the abbreviation/acronym is longer then 1 char's, use a capital only for the first character of each acronym, e.g. htmlToUiHttpSoapRestSwtAwtIdConverter, instead of unreadable htmlToUIHTTPSOAPRESTSWTAWTIDConverter. [Rationale: Using all uppercase for the base name will give conflicts with the naming conventions given above. A variable of this type whould have to be named dVD, hTML etc. which obviously is not very readable. Another problem is illustrated in the examples above; When the name is connected to another, the readability is seriously reduced; The word following the acronym does not stand out as it should.]
  3. Acronyms MUST be treated as words for camel-casing purposes: informationUri, not informationURI. [Rationale: An abbreviation that is well known to one community is often incomprehensible to others who need to use the same document format (and who do understand the full name); treating an acronym as a word makes it easier to see where the word boundaries are.]
public final class J2eeLoader {
    public static EjbRef[] loadEjbRefs(Element parent) {
        //...
    }
}

Note: This is more of a guideline than a rule, as some modules simply can not follow this convention, but where applicable they should.

Programming Techniques, Recommendations and Coding Practices

Clean Code

Having code that works is not enough. It's not enough that your car works; when you open the bonnet you want to see good engineering, not a tangle of pipes, wires and belts that somehow hangs together.

Software is vulnerable to poor craftsmanship because code is often well hidden from customers and end-users. Still, the programmer knows whether they are putting together something that just about works, or crafting something excellent that will be understandable and maintainable long into the future.

  1. Keep code where it belongs.
  2. Keep methods short. The principle is to use extract method refactoring until there is nothing more to extract. Consider anything over 20 lines a suspect.
  3. Have methods with only a few arguments - preferably no more than two - and don't use boolean arguments because they cause confusion. Boolean (flag) arguments loudly declare that the function does more than one thing. They are confusing and should be eliminated.
  4. Similarly, a class should be a small batch of code, with only a few variables, a couple of dozen methods.
  5. Eliminate duplication in your code; use abstraction.
  6. Give public methods short names, but use long descriptive names for private methods. The code is the documentation.
  7. Improve code slightly every time you touch it. Sometimes the opposite happens; code decays as fixes get added. If you improve it instead, your project improves over time.
  8. You need comprehensive tests, otherwise you do not dare to make changes in case something breaks. Test code should be of the same quality as production code; if your tests are slow and buggy, you will not use them or trust them.
  9. Don't initialize variables to 0 or null where it's not required (redundant), e.g. instance variables or call super() constructor where it is called automatically. Don't clutter up your code.
  10. Keep the public API simple. If the method doesn't need to be public, don't make it so.

Code Design

  • Always construct objects in valid state.
  • Use nested constructors to eliminate redundant code.
  • Avoid multiple exits from loops.
  • Avoid introducing boolean "flag" variables.
  • Try to have exactly one return at the end of functions.
  • Do not use System.exit().
  • One class per file (inner classes excluded).
  • Try to keep classes limited to 50-90 lines.
  • Try to keep methods limited to 20-30 lines. More then this is usually a symptom of poorly abstracted code.
  • Use packages to modularlize complex programs.
  • Report errors and handle I/O in the main program.
  • Avoid OS depedent behavior, e.g., Unix-centric constants "\n", "/", etc.
  • Favor immutability.
  • Avoid constructor madness.
  • Avoid string concatenation (except when concatenation two or three strings), use StringBuilder (StringBuffer is syncronized and so is less efficient).
  • Favor interfaces to reflection.
  • Never declare implementation types.

Visibility

  • Restrict the visibility of variables and other identifiers as much as possible. Move the declaration of local variables to the point of their use.
  • Make all fields private.
    Non static instance variables should be private for proper encapsulation, never protected. Subclasses should access them the same way other classes do - through accessors. This allows the base class to keep its state consistent.
  • Declare a local variable as close as possible to its first use.
  • Keep the initialization near the declration if possible.
  • Declare the index variables of loops in the for construct.
  • Avoid methods that depend on instance variables and non-local variables.
  • Don't publish the this reference during construction. Don't implicitly expose the this reference.

Designing for Inheritance

  1. Always decide whether a class's methods and instance variables (collectively: "attributes") should be public or non-public. If in doubt, choose non-public; it's easier to make it public later than to make a public attribute non-public.
  2. Public attributes are those that you expect unrelated clients of your class to use, with your commitment to avoid backward incompatible changes. Non-public attributes are those that are not intended to be used by third parties; you make no guarantees that non-public attributes won't change or even be removed.
  3. Another category of attributes are those that are part of the "subclass API" (often called "protected" in other languages). Some classes are designed to be inherited from, either to extend or modify aspects of the class's behavior. When designing such a class, take care to make explicit decisions about which attributes are public, which are part of the subclass API, and which are truly only to be used by your base class.

With this in mind, here are the guidelines:

  1. If your variable name collides with a reserved keyword, and you can't think of some appropriate prefix for this name, append a single trailing underscore to your variable name. This is preferable to an abbreviation or corrupted spelling. (However, notwithstanding this rule, 'clazz' is the preferred spelling for any variable or argument which is known to be a class)
  2. Do not expose public data attributes, but use accessor/mutator methods for them. Note 1: Try to keep the functional behavior side-effect free, although side-effects such as caching are generally fine. Note 2: Avoid using properties for computationally expensive operations; the attribute notation makes the caller believe that access is (relatively) cheap.

Exceptions

  1. Use unchecked, runtime exceptions to report serious unexpected errors that may indicate an error in program's logic.
  2. Use checked exceptions to report errors that may occur, however rarely, under normal program operation.
  3. Always know why you are catching an exception.
  4. Do not silently absorb a runtime or error exception.
  5. Use return statement to report expected state changes (not exceptions).
  6. Error handler should be present whenever you anticipate possibility of error.
  7. A situation is only exceptional, if the program can not handle it with reasonably effort. Wrong input data should be an expected situation of the regular code, that could be handled gracefully.
  8. Catch only exceptions for which you have explicit handling. Don't handle exceptions unless the procedure can fix the problem or unless the procedure is responsible for reporting errors.
  9. Use exception handling to handle uncommon cases.
  10. The intention of exception-handling is to separate real error-handling from the regular part of the code, so don't force the caller to mix it with unnecessary exceptions.
  11. Only if your code really has a problem to continue e.g., when a parameter is invalid, feel free to throw an exception!
  12. Do not throw an exception, if you only suppose the caller of your code could have a problem with a special result. Try to return a special result value instead e.g., null, and let the caller decide with a regular if-else-statement. if the caller really has a problem, he will throw an exception on his own.
  13. But if your code throws an exception, even though it has no real problem and it could continue without an exception and return a special result value, you forestall the decision of the caller, whether the special result is really an error or not.
  14. If you throw an exception, where the caller would decide that it is no error in the context of the caller, you force the caller to write an exception handler in his regular part or to abort i.e., you force the caller to mix regular code with exception handling. That is the opposite of the intention of exception handling.
  15. Checked exception are overused in Java. You should not be forced to catch exceptions you are unlikely to recover from.
  16. Bad example:
    java.lang.Class.forName(string) throws ClassNotFoundException
    In most programs/situations it is an error if this method does not find the class, therefore it throws an exception and forestalls the decision of the caller.
    but maybe there is a program that should check a list of class names, whether the classes are present or not. Such a program is forced to mix its regular code with error handling of an exception, that is no error at all in that context.
    The method should return a special result value instead: null. Many callers of that method have expected that situation and therefore are not in an unexpected situation/exceptional state. They could decide the situation on their own.
  17. Only throw checked exceptions (not derived from RuntimeException), if the caller has a chance to handle it.
  18. Exceptions that signal programming errors or system failures usually cannot be handled/repaired at runtime -> unchecked exception.
  19. If your code really has a problem to continue e.g., when a parameter is invalid, throw an unchecked exception (derived from RuntimeException) and do not throw a checked exception, because if not even your code can handle the problem, in the very most cases the caller has no chance to handle the problem, too. Instead there maybe somebody somewhere in the highest layers who catches all RuntimeException's, logs them and continues the regular service.
  20. Only if it is not possible to return special result values cleanly, use checked exceptions to force the caller to decide the situation. The caller should deescalate the situation by catching and handling one or more checked exceptions, e.g. with special result values(?) or by escalating with an unchecked exception, because the situation is an error, that can not be handled.
  21. Checked exceptions are an official part of the interface, therefore do not propagate checked exceptions from one abstraction layer to another, because usually this would break the lower abstraction. e.g. do not propagate sqlexception to another layer, because sqlexceptions are an implementation detail, that may change in the future and such changes should not affect the interfaces and their callers.
  22. Never throw NullPointerException or RuntimeException. use either IllegalArgumentException, or NullArgumentException (which is a subclass of IllegalArgumentException anyway). If there isn't a suitable subclass available for representing an exception, create your own. NullPointerException is always evidence of a bug in the program so it should be fixed.
  23. In a catch statement that throws an exception, always throw the original exception (or another exception constructed from original exception) to maintain the stack location of the original error.
  24. Avoid error code as method return values.
  25. Avoid defining custom exception classes. Use standard whenever suitable.
  26. Report errors and handle I/O in the main program.
  27. Errors should be raised in the methods present in the components and captured in the application’s GUI.
  28. Do not use try-catch for flow control.
  29. Never declare an empty catch block. Comment why it is empty.
  30. Error message should be user friendly, simple and understandable.

Logging

  1. Log as much as necessary for someone to figure out what broke. :)
  2. Use SLF4J org.slf4j.Logger rather than raw Log4j or JCL.
  3. Do not log throwables that you throw - leave them to the caller.
  4. Use flags to avoid string concatenation for debug and trace.
  5. Use SLF4J varargs {} expansion.
  6. Cache flags (especially for trace) to avoid excessive isTraceEnabled() calls.
  7. Surround LOG with blank lines to separate visually essential program code from suplemental (logging) one.
  8. Tips on Proper Application Logging

Levels

  1. Use trace level for detailed/diagnostic logging.
  2. Use debug level for things an application developer would need to know.
  3. Use info level for things an administrator would need to know. All important started and finished processes.
  4. Use warn level for things indicating an application or transient problem. All actions that run in trouble but were able to be finished. For example if configuration is missing and we use a default config for a dedicated action.
  5. Use error level for things indicating a problem with the server itself. All actions and problems which are not able to be recovered / fixed by system. All problems that cause manual actions in configs or code.
private static final Logger LOG = LoggerFactory.getLogger(SomeClass.class);

public void doSomeStuff(Stuff stuff) throws StuffException {
    try {
        LOG.trace("About to do stuff: {}.", stuff);

        stuff.doSomething();

        LOG.trace("Did some stuff.");
    } catch (BadException e) {
        // Don't log - leave it to caller.
        throw new StuffException("Something bad happened.", e);
    } catch (IgnorableException e) {
        // Didn't cache this as we don't expect to come here a lot.
        if (LOG.isDebugEnabled()) {
            LOG.debug("Ignoring problem doing stuff " + stuff, e);
        }
    }
}

API Design

Other Programming Recommendations and Coding Practices

  1. Use class-based exceptions. Modules or packages should define their own domain-specific base exception class, which should be subclassed from the built-in RuntimeException/Exception class.
  2. When catching exceptions, mention specific exceptions whenever possible instead of catching general Exception.
  3. Additionally, for all try/except clauses, limit the 'try' clause to the absolute minimum amount of code necessary. Again, this avoids masking bugs.
  4. Avoid explicit initialization of class field to the default value.
  5. Don't compare boolean values to true or false using ==.
  6. Avoid function calls in Boolean conditional statements. Assign into local variables and check on them.
  7. Functions:
    1. Should ideally have zero arguments. More then three should not be used anyway.
    2. Flag (boolean) arguments are ugly.
    3. Avoid output arguments.
  8. Always use zero based arrays.
  9. Do not provide public or protected member variables.
  10. Avoid providing explicit values for enums.
  11. With the exception of zero or one, never hard-code a numeric value; always declare a constant instead.
  12. Prefer using explicit interface implementation.
  13. Never hardcode strings or other constants that might change based on deployment such as connection strings.
  14. Use null String instead of empty string "".
  15. Don't use the this reference unless invoking another constructor from within a constructor.
  16. Do not use the super word to access parent class members unless you wish to resolve a conflict with a subclasses member of the same name or when invoking a parent class constructor.
  17. Eliminate superfluous syntactic sugar (like needless casts, and heavy parenthesizing). Such stuff may help educate a novice programmer, but is unneeded by anyone doing serious debugging and a hindrance to someone trying to get the big (or medium) picture.
  18. Make sure your code is maintainable.
  19. The only valid measurement of code quality: WTF/minute.

Unit Test Cases

  1. Follow the same standards for all tests.
  2. Test individual functional elements.
  3. Be clear about what each test state is.
  4. Be specific about the expected behavior.
  5. Java unit test best practices:
    1. Method naming, e.g.:
      • canCountAllItems()
      • canRetrieveProperCountWhenAddingMultipleItems()
      • cannotAddSameObjectAgain()
      • shouldPreventApplicationFromExitingAndHandleExitRequest()
      • shouldShowHomePageWithRecentRants()
    2. Use Given-When-Then test method naming concept.
    3. Use test case / file naming scheme *Test.java.
    4. Do not define public static Test suite() or constructor methods, the build system will automatically do the right thing without them.
    5. Use JUnit @Test annotations and so don't precede method with 'test'.

File and Folder Naming and Organization

Split and conquer!
  • Place types that are commonly used, changed, and released together into the sampe package.
  • Use lowercase names for urls (google likes it), folders and files with words separated by dashes ('-'). Exceptions apply only to Java classes or other files that represent class structure.
  • Do not repeat words in file if name is already part of folder name.

Content Editing Rules

  1. Write in English.
  2. Before you start creating or editing your content please check W3C Guidelines and learn some general rules of Titles and Headings Capitalization (if you are writing in English, if not see Rule #1).
    See Wikipedia for examples.
    Capitalization of all words, except for internal articles, prepositions, conjunctions and forms of to be.

SQL Code

  1. SQL Formatting
  2. Database Coding Standards and Guidelines

JavaScript/XML/XHTML/CSS


  • Double ident continuation of attributes and internal element values.
  • Tag and attribute names should be lower case.
  • Self closing tags should have whitespace before slash.

Repository Integration and URI Design

You should not commit any IDE or Maven-generated files to Subversion. In practical terms this means whenever you create a new directory that contains pom.xml, set the svn:ignore property as follows:

svn propset svn:ignore ".*
target" .

Maven Integration for Eclipse can help you to have one-step development environment setup.

General principles for good URI design:

  • Don't use query parameters to alter state
  • Don't use mixed-case paths if you can help it; lowercase is best
  • Don't use implementation-specific extensions in your URIs
  • Don't fall into RPC with your URIs
  • Do limit your URI space as much as possible
  • Do keep path segments short
  • Do prefer /resource instead of /resource/; and create 301 redirects from the last one if not used
  • Do use query parameters for sub-selection of a resource; i.e. pagination, search queries
  • Do move stuff out of the URI that should be in an HTTP header or a body

(Note: I did not say "RESTful URI design"; URIs are essentially opaque in REST.)

General principles for HTTP method choice

  • Don't ever use GET to alter state; this is a great way to have the Googlebot ruin your day
  • Don't use PUT unless you are updating an entire resource
  • Don't use PUT unless you can also legitimately do a GET on the same URI
  • Don't use POST to retrieve information that is long-lived or that might be reasonable to cache
  • Don't perform an operation that is not idempotent with PUT
  • Do use GET for as much as possible
  • Do use POST in preference to PUT when in doubt
  • Do use POST whenever you have to do something that feels RPC-like
  • Do use PUT for classes of resources that are larger or hierarchical
  • Do use DELETE in preference to POST to remove resources
  • Do use GET for things like calculations, unless your input is large, in which case use POST

General principles of web service design with HTTP:

  • Don't put metadata in the body of a response that should be in a header
  • Don't put metadata in a separate resource unless there is no other option
  • Do use the appropriate status code
    • 201 Created after creating a resource; resource must exist at the time the response is sent
    • 202 Accepted after performing an operation successfully or creating a resource asynchronously
    • 400 Bad Request when someone does an operation on data that's clearly bogus; for your application this could be a validation error; generally reserve 500 for uncaught exceptions
    • 403 Forbidden when someone accesses your API in a way that might be malicious or if they aren't authorized
    • 405 Method Not Allowed when someone uses POST when they should have used PUT, etc
    • 413 Request Entity Too Large when someone does something like ask for your entire database
    • 418 I'm a teapot when attempting to brew coffee with a teapot
  • Do use caching headers whenever you can
    • ETag headers are good when you can easily reduce a resource to a hash value
    • Last-Modified should indicate to you that keeping around a timestamp of when resources are updated is a good idea
    • Cache-Control and Expires should be given sensible values
  • Do use redirects when they make sense, but these should be rare for a web service

Parameters don't apply to a resource. A resource is a single entity with a unique identifier. A parameterized URL indicates a collection of resources you select among using the parameters. The content of the URL should not be responsible for changing the underlying state of the system. It should only be used as an identifier for a particular resource.

If a resource always falls within another resource, nest it. Nothing wrong with that. Going deeper than one can sometimes be a bit of a pain because your route paths will be very long and can get a bit confusing. But don't confuse nesting with namespacing. Adding permalink style URLs that use words rather than just IDs are more visually appealing and they can help with SEO, whether or not they're nested. Keep URLs simple, clean, human readable and searchable.

The point of ReSTful approach is to allow you to change the URL's that are used to access resources at-will without affecting clients that work against your existing services. A REST API must not define fixed resource names or hierarchies (an obvious coupling of client and server). Servers must have the freedom to control their own namespace.

Patterns

Model/View/Controller

Separate the model from the view. Separate the controller from the view and the model.

  • Separate model from view: don't build assumptions about the presentation into the model or data source. Keep the interface between the data source and the presentation abstract. Don't give the model knowledge of its view. (A good rule of thumb is to ask yourself if it's possible to have multiple presentations, with different states, on a single instance of your data source.)
  • Separate controller from view and model: don't put all of the "business logic" into view-related classes; this makes the code very unusable. Make controller classes to host this code, but ensure that the controller classes don't make too many assumptions about the presentation.

JS Patterns

Essential JavaScript Design Patterns For Beginners

References and Links

  1. [1] Code Conventions for the Java Programming Language
  2. [2] Java Style (Geosoft)
  3. [3] Style Guide for Python Code
  4. [4] http://www.wikipedia.com/wiki/CamelCase
  5. [5] Apache Geronimo Coding Standards (Exceptions and Logging)
  6. A List of Coding Standard Websites
  7. Variable Naming Conventions
  8. The smartest, ideal, efficient programming can still look awful.
  9. PHP: PSR 1 Basic Coding Standard and PSR 2 Coding Style Guide
  10. Jalopy Source Code Formatter (commercial)
  11. JavaDoc Formatting Guide
  12. Checkstyle
  13. PMD Rules
  14. FindBugs
  15. Bad Variable Naming and Syntax Conventions for Java but Good References
  16. Coding Standards and Conventions for Java and Rails Projects

Copyright

This document has been placed in the public domain.