guidelines

"Guideline" is the NATO reporting name for the Soviet SA-2 surface-to-air missile. read more at WikiPedia

    • Durability of Usability GuidelinesAbout 90% of usability guidelines from 1986 are still valid, though several guidelines are less important because they relate to design elements that are rarely used today.The 944 guidelines related to military command and control systems built in the 1970s and early 1980s; most used mainframe technology. You might think that these old findings would be completely irrelevant to today's user interface designers.60 guidelines reviewed here
    • Jakob Nielsen pageDr. Nielsen founded the "discount usability engineering" movement for fast and cheap improvements of user interfaces and has invented several usability methods, including heuristic evaluation. He holds 76 United States patents, mainly on ways of making the Internet easier to use.

  • Checkstyle is a development tool to help programmers write Java code that adheres to a coding standard.
    It automates the process of checking Java code to spare humans of this boring (but important) task. This
    makes it ideal for projects that want to enforce a coding standard. Checkstyle is highly configurable and can
    be made to support almost any coding standard. An example configuration file is supplied supporting the
    Sun Code Conventions. As well, other sample configuration files are supplied for other well known conventions.

    From http://checkstyle.sourceforge.net/

    Some facts about checkstyle:

    Languages

     
    Java 71%
     
    XML 26%
     
    Other  
      XSL Transformation 2%
      CSS 1%
      HTML <1%
      Emacs Lisp <1%
      MetaFont <1%

    Project Cost

    This calculator estimates how much it would cost to hire a team to write this project from scratch.
    Include
    Codebase 68,028 LOC
    Effort (est.) 16 Person Years
    Avg. Salary $/year
    $897,876
  • Everything on this pageshould NOT be applied

    "In the interests of creating employment opportunities in the Java programming field, I am passing on these tips from the masters on how to write code that is so difficult to maintain, that the people who come after you will take years to make even the simplest changes. Further, if you follow all these rules religiously, you will even guarantee yourself a lifetime of employment, since no one but you has a hope in hell of maintaining the code. Then again, if you followed all these rules religiously, even you wouldn't be able to maintain the code!
    You don't want to overdo this. Your code should not look hopelessly unmaintainable, just be that way. Otherwise t stands the risk of being rewritten orrefactored."

  • Â

    Java Coding guidelines

    I won&39;t give you here all explanations on how to improve your code, only some references to external ressources, a lot of people have done a good job (hard work, respect!). Feel the need to improve your code, and you will follow more or less the same road

    Kent Beck often makes a statement about himself, "I&39;m not a great programmer; I&39;m just a good programmer with great habits."

    "keep it small to keep it beautiful" me speaking about refactoring ;-)

    "Tests don&39;t prove the absence of bugs"

    "Good judgment comes from experience. Unfortunately, the experience usually comes from bad judgment"

    Occam&39;s razor (14th century philosopher monk): No complexity beyond what is necessary.


    Things you may do to improve your code

    • Respect the Java guidelines, a lot of white papers can be found on internet.
    • Never return a collection (Vector or Hashtable or) in java, prefer to return a class which hide the real collection, better return an interface, this will allow to refactor the code if performances issues are found. Difficulty is of course to define a good contract between your code and client which will use it (good interface). Never use a Vector and let the client cast or extract Object type, let the compiler protect yourself against runtime error!!!!
    • If you need to have diffferent implementation of a class, but do not want to have one of them in memory (for example because of costly licences), you need a dynamical factory (Abstract polymorphical factory) Here is a templates of this ZIP file
    • Use idea of design from open source project! a lot of great and skilled people are working for the fundation Apache for example.
    • Use Object development (of course) but do not rely on interface shipped with 3rd party objects you are buying/integrating, always create a wrapper around them or better define your own interface, use a strategy pattern....
    • A good code is a small code! responsabilities must be properly localized (do not be lazy, create more objects!)and not spread around or worse localized in one object (spaghetti code). Naming convention is very important! you can distinguish an orange from an apple? right so do not forget that the easiest refactoring methods are: rename methods, rename variables, rename objects, rename packages, move code to...
    • Use a logging framework or better use nothing else than log4j or any implementation based on it. It is a great advantage to know how many bugs or errors has occured in production and when. Moreover changing debug level without rebooting server, or changing output destination are neat features FAQ.
    • Feel the need to avoid comments! they are not really synchronized (some people prefer to say NEVER synchronized) with the source code. If you still need comments, ask yourself if you can not use these comments to rename or reorganize the code they belongs. You may only explain: designs patterns used, bugs corrected (prefer to write a Junit testcase), algorithms or hacks (hacks are temporary solutions that do not create any major problems).
    • Do a daily integration, this is quite simple with eclipse and if you use ANT, read more at http://www.martinfowler.com/articles/continuousIntegration.html
    • Use XML! yes it is memory consuming, slow to read (not always) but it has a so much advantages that they can not be listed here (or not now),
    • Prefer lossely coupled system or process, for example try to create a meta descriptions data storage if you have a lot of layers in your system or use webservices

    Optimizations:

    Of course some habits of coding are really bad, but nearly all compilers are catching them, and can do some agressive optimizations... you will never thinks of, moreover some JVM can optimized the bytecode on the fly (HOTSPOT) or do second pass during compile time. Do you really think that you will speed up your program when you take care of writing rules or try to use a non readable algorithm which contains a lot of tricks? if you do so, you will not see the evil loop where your system will hang for seconds....Keep always in minds:

    • Do not try to start any optimizations too early, code must be readable and high level.
    • Use a profiler, if you are not satisfied with performances! and locate precisely the place where you loose time or eat memory. Memory leaks can be found with profilers too (yes memroy leaks are existing in java :-) ). This can be done by a core taskforce team, generally in one/two week(s).
    • Remember that when you will ship your code to customers, new cpu or machines will be available, chance is that a better cpu will cost less than hours of optimizations.
    • Techniques to improves performances are well documented, and quite easy. I use generally: pooling, load balancing, caching, precomputing values (you remember people using sinus table accurate at 10-3 for demo on amiga or HP48?), some patterns are helpful too, lazy evaluations, lazy initialization, delayed constructions! and so on...It is like a new world!
    • If you use a storage system, like a database, you can use an external ressource to improve IO, turn on the SQL query analyzer in SQL or Oracle to see what is going on. Any DBA (Database Administrator) can determine really fast where problems are: no index, bad design, foreign keys not well choosen, too much or bad join of tables, tables are too big, temporary table not empty after use, not enough virtual memory tuning, no cache tuning, bad JDBC-ODBC driver....
    • JVM parameters tuning: after using the profiler, you can determine the optimal size of heap and stack, turn hotspot on or cut it off because sometimes it has some bad effects.
    • User determine if a system is slow, or after loading the applications you can decide to improve your code if needed (memory used, cpu used, io used...). Remember end users are humans (not always ;-) for me), you can disturb them or make the wait look shorter if you use a hourglass or vertical slider, system must be responsive to user interactions! display something but do not hangs during seconds. A small javascript code can give you 40% more "hanging" time with great users acceptance

    Things you may read to improve your code

    • Read news about java technologies: www.javaworld.com, project hosted at www.soundforge.net and so on. You must keep yourself inform about the latest state of the art.
    • Register at http://developer.java.sun.com/developer/ a lot of great forums, and a knowledge database can be freely browsed.
    • Refactoring:a change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior. (from Martin Fawler&39;s book: Refactoring)
      www.refactoring.com and techniques associated.
      My own definition would be: never be satisfied with your code! when it works and has been tested, write JUnit testcases and take 10 min to refactore your code each day. The book above has a good introduction about why it is important and how you can explain it to your manager. read one refactoring technique per day, it will also help you to improve your code.
    • AntiPattern: "An AntiPattern is a literary form that describes a commonly occurring solution to a problem that generates decidedly negative consequences.
    • AntiPatterns are a method for efficiently mapping a general situation to a specific class of solutions.
    • AntiPatterns provide real-world experience in recognizing recurring problems in the software industry and provide a detailed remedy for the most common predicaments.
    • AntiPatterns provide a common vocabulary for identifying problems and discussing solutions.
    • AntiPatterns support the holistic resolution of conflicts, utilizing organizational resources at several levels, where possible.
    • AntiPatterns provide stress release in the form of shared misery for the most common pitfalls in the software industry" from
    • Reference book isAntiPatternsRefactoring Software, Architectures, and Projects in Crisis
      William J. Brown - Raphael C. Malveau - Hays W. McCormick III - Thomas J. Mowbray - John Wiley & Sons, Inc.

    • www.extremeprogramming.com follow this rules to respect deadlines and work in an ambitious project.
    • www.objectsbydesign.com use patterns in your projects! and use comments saying which one you are using and why.It help a lot to understand the code.
    • www.bruceeckel.com and his famous free book "Thinking in Java" is a must for all developer (entry level but sometimes it is good not to forget basics of languages or OO)
    • Checked exceptions are not supported in Java but can be implemented, read here: http://www.mindview.net/Etc/Discussions/CheckedExceptions
    • Read cocomo in order to know what can make sense, statistics released by an university in USA that show influence of parameters during a project: what does a guru bring to a project?...what are the cost of a reatime application? how do I determine how long it will take?
  • coding.guidelines

    Code checker scans Java source code in your favorite IDE (I assume Eclipse :-))

    There are basically of 2 types:

    • On the fly code checker, as soon as you type a word or save a new document, it run and give a real time feedback
    • Offline checker or so called static code analyzer that can be run during the build of your java components

    Why using a code guidelines checker?

    These tools are highly recommended across a team of different developers for the following reasons:

    • These tools are highly configurable and can be made to support almost any coding standard.
    • Ideal for projects that want to enforce a coding standard (ideally where not all developer code the same way)
    • Ease your debugging and maintenance costs by making the code more readable: developers do not have to worry about
      deciphering individual coding styles when working on a piece of code they did not write.
    • They can detect possible bugs or dangerous coding behavior - empty try/catch/finally/switch statements
    • Detect dead code - unused local variables, parameters and private methods
    • Sub optimal code - wasteful String/String Buffer usage
    • Overcomplicated expressions - unnecessary if statements, for loops that could be while loops
    • Duplicate code - copied/pasted code means copied/pasted bugs
    • Find class design problems, bug patterns like double checked locking.

    They give an immediate "objective" feedback and help developers recognize where they have been excellent or lazy;

    It gives team leader, an opportunity to study the code, design and team from a different perspective; and by slicing off
    whole classes of faults, You can concentrate more on design shortcomings.

    Features

    All code checker share more or less the same features

    • Violations severity can be defined at rules level (error, warning, ignore, other).
    • Rules can be triggered by threshold/values.
    • Rules are stored in XML files.
    • Java editor highlight offending lines/rules in violation
    • Rules can be extended (require some strong tree parsing and language knowledge)
    • Integration in major IDE (eclipse, IDEA,...)
    • Integration in ANT, Maven,...

    Attention

    The major issues wont be to install these tools...

    Most developers are convinced that their code is the best, and bad habits are difficult to get rid of. The
    biggest pain will be to force all developers to agree on a set of common rules that you want to enforce.
    A good starting point is to use some well known rules or good practices from the industry. Sun is for example
    publishing some code writing rules.

    I will look at the major open source and free code checker on the market in this series of articles:

    • PMD
    • Findbugs
    • Checkstyle
    • Code coverage

    &160;


    pmd_logo_small PMD

    PMD is a static ruleset based Java source code analyzer that identifies potential problems like:

    • Possible bugs - Empty try/catch/finally/switch blocks.
    • Dead code - Unused local variables, parameters and private methods
    • Empty if/while statements
    • Overcomplicated expressions - Unnecessary if statements, for loops that could be while loops
    • Sub optimal code - wasteful String/String Buffer usage
    • Classes with high Cyclomatic Complexity measurements.
    • Duplicate code - Copied/pasted code can mean copied/pasted bugs, and decreases maintainability.

    While PMD doesn't officially stand for anything, it has several unofficial names, the most appropriate probably
    being Programming Mistake Detector. Typically, PMD errors are not true errors, but rather inefficient code,
    i.e. the application could still function properly even if they were not corrected
    . from WikiPedia

    • PMD Can be integrated with Eclipse (see below), Maven (maven-pmd-plugins), Ant (Ant task).
    • PMD is an engine, rulesets parse code and issue a message and level if rules are violated.
    • PMD is notable because you can write your own rules using XPath expressions over an XML version of the parse tree
    • PMD has a duplicate code detector CPD which is quite fast and accurate to locate dangerous CUT and Paste code sections.

    List of rule sets

    Basic JSF rules:

    Basic JSP rules

    Basic Rules

    Braces Rules

    Clone Implementation Rules

    Code Size Rules

    Controversial Rules

    Coupling Rules

    Design Rules

    Finalizer Rules

    Import Statement Rules

    J2EE Rules

    JavaBean Rules

    JUnit Rules

    Jakarta Commons Logging Rules

    Java Logging Rules

    Migration Rules

    Migration15

    MigratingToJava4

    Naming Rules

    Optimization Rules

    Strict Exception Rules

    String and StringBuffer Rules

    Security Code Guidelines

    Type Resolution Rules

    Unused Code Rules

    &160;


    Example of integrations: Ant, Maven and Eclipse

    Ant
    <target name="pmd">
    <taskdef name="pmd" classname="net.sourceforge.pmd.ant.PMDTask"/>
    <pmd shortFilenames="true">
    <ruleset>rulesets/favorites.xml</ruleset>
    <ruleset>basic</ruleset>
    <formatter type="html" toFile="pmd_report.html&8220;  linkPrefix="http://pmd.sourceforge.net/xref/"/>
    <fileset dir="/tmp/productcatalog/">
      <include name=&8220;com/**/*.java"/>
    </fileset>
    </pmd>
    </target>
    Maven
    <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-pmd-plugin</artifactId>
            <configuration>
              <linkXref>true</linkXref>
              <sourceEncoding>utf-8</sourceEncoding>
              <!-- 100 tokens corresponds to approximately 5-10 lines of code. -->
              <minimumTokens>100</minimumTokens>
              <targetJdk>1.5</targetJdk>
                <excludes>
                <exclude>**/generated/*.java</exclude>
                </excludes>
            </configuration>
    </plugin>
    Eclipse

    see below

    &160;


    Installing PMD in Eclipse

    1. Start Eclipse.
    2. Start the installation procedure : select the Help>Software Updates>Find and Install... menu item.
    3. Select "Search for new features to install" option and click Next.
    4. Click New Remote Site...
    5. Give a name (ie PMD Eclipse Site), enter the URL&160; http://pmd.sf.net/eclipse
    6. Select this new site in the Sites to include in search list and click Next.
    7. Select PMD for Eclipse 3 and Apache Xerces in the "Select the features to install" list and click Next.
    8. Accept the terms of the license agreements and click Next.
    9. Verify that the install location is your Eclipse installation directory, otherwise select the correct one, click Finish.
    10. A warning appear telling the feature is not signed. Ignore and click Install to continue.
    11. Accept to restart the workbench to load PMD into the workbench.

    Eclipse is restarted and a PMD welcome page is displayed : the plugin is correctly installed.

    Using PMD in Eclipse

    Trying to start PMD on a full workspace on too many modules/projects is very dangerous as the number of
    violations can be very high (many thousands) and can make eclipse run out of memory

    In order to test PMD. I did choose an open source project, the connector of MySQL 5 in the version 5.1.6.
    I do not want to judge the quality of MySQL connector, this is simply a project code that was available on my desktop.

    First Review all rules, you will find some of them disturbing (remember nobody like to be told that his coding habit
    are bad), You can switch off some rules or import a set of predefined rules in the preferences windows

    PMD.code.checker0

    If you are in a distributed team, or wan to share your settings using either CVS or Subversion (SVN) don't
    forget to export the rule sets to a share project.

    The code duplicator detector will report any code that seems to be identical according to a certain value of
    number of line (25 lines of duplicated code)

    &160;PMD.code.checker1

    The project is set in eclipse, and compiling

    PMD.code.checker3&160;

    Lets run PMD on MySQL connector,
    PMD.code.checker.activate&160;
    The project is after no more compiling....

    PMD.code.checker2 PMD.code.checker4png

    PMD create additional Eclipse views, this help you better judge how many violations there is and their
    level. As You see there is some violations

    PMD.code.checker8


    The duplicate detector ask for the number of lines that it should consider duplicated.

    PMD.code.checker7

    PMD.code.checker5 &160;
    PMD.code.checker6 By Clicking in the view, you can jump to the code

    &160;

    PMD final words...

    • Is customizable via XSL rules, java
    • Will disturb You at the beginning, but will improve your code in no time.
    • Has a broad scope of rule sets, basic JSF rules are now existing.
    • Some reported violations are not bugs, so take everything with a bit of salt, try to reach a
      realistic goal: (1 failure per 100 lines of code per example is my goal)