Coding standard
- 3. I think there may be a bug in Joe’s Code
-- Please Fix
func GreenEggsNHam(Not SamIAm, Green EggsNHam)
foreach Green TryThem in SamIAm
do EatThem(TryThem) = false
NotInACarNotOnABus(EggsNHam)
func NotInACarNotOnABus(Green EggsNHam)
EatThem(EggsNHam) = true
NotOnAPlane(EggsNHam)
foreach NotLikeThem SamIAm of EggsNHam do
if not EatThem(SamIAm) then
NotInACarNotOnABus(SamIAm)
IDoNotLikeThem(EggsNHam)
- 4. Joe’s Code Following a Sane Coding Standard
func DepthFirstSearch(graph G, vertex v)
foreach vertex w in G
do Encountered(w) = false
RecursiveDFS(v)
func RecursiveDFS(vertex v)
Encountered(v) = true
PreVisit(v)
foreach neighbor w of v do
if not Encountered(w) then
RecursiveDFS(w)
PostVisit(v)
- 5. What are Coding Standards
• Coding standards are guidelines for code style and documentation.
• The dream is that any developer familiar with the guidelines can
work on any code that followed them.
• Standards range from a simple series of statements to involved
documents.
- 6. Areas Typically Covered
• Program Design
• Naming Conventions
• Formatting Conventions
• Documentation
• Possibly Even Licensing
- 7. Why Coding Standards are Important?
• Coding Standards lead to greater consistency within your code and
the code of your teammates.
• Easier to understand
• Easier to develop
• Easier to maintain
• Reduces overall cost of application
- 8. Prime Directive
• Document every time you violate a standard.
• No standard is perfect for every application, but failure to comply with your
standards requires a comment
- 9. Ambler’s Law of Standards
• Industry Standards > organizational standards > project standards > no standards
- 10. Ambler’s Law of Standards (Contd…)
• The more commonly accepted a standard the easier it is for team
members to communicate
• Invent standards when necessary, but don’t waste time creating
something that you won’t be able to use later.
• All languages have recommended coding standards available. It is
well worth your effort to find and use industry standards
• Push for organizational standards whenever possible
- 11. Good Coding Style
• Names
Use full English descriptors
Use CamelCase to make names readable
Use abbreviations sparingly and consistently
Avoid long names
Avoid leading/trailing underscores
• Documentation
Document the purpose of every classes and methods
Document why something is done not just what
- 12. Member Functions Documentation
• What and why member function, what it does
• Parameters / return value
• How function modifies object
• Preconditions /Postconditions
• Concurrency issues
• Restrictions
- 14. Three Rules
1. Coding standards needn’t be onerous - find a standard that works
for your team.
2. Standardize early - the effort to bring your old work into the
standard will be too great otherwise.
3. Encourage a culture where standards are followed.
- 18. Naming Conventions
• What Makes Up a Good Name?
Use full English descriptors
For example, use names like firstName, grandTotal, or CorporateCustomer
• Use terminology applicable to the domain
Banking domain - Customer, Software services domain - Client
• Use mixed case to make names readable
• Avoid long names (< 15 characters is a good idea)
• User abbreviations sparingly
• Capitalize the first letter of standard acronym
- 19. Naming Conventions (Contd…)
• Classes / Interfaces –
Class names should be nouns, in mixed case with the first letter of each internal word
capitalized.
• Methods –
Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of
each internal word capitalized.
• Variables –
Variables should be nouns, in mixed case with the first letter lowercase, with the first letter of
each internal word capitalized.
• Class Constants –
Class Constants should be all uppercase with words separated by underscores (“_”).
- 20. Blank Spaces
Before / After Parenthesis –
A keyword followed by a parenthesis should be separated by a space.
while_(true)_{
...
}
A blank space should appear after commas in argument lists.
All binary operators except . should be separated from their operands by spaces.
a = (a + b) / (c * d);
The expressions in a for statement should be separated by blank spaces.
for (expr1; expr2; expr3)
Casts should be followed by a blank.
User x = (User) anObject;
blank spaces
- 21. Returning Values
• Try to make the structure of your program match the intent.
• Example:
if (booleanExpression) {
return TRUE;
} else {
return FALSE;
}
• should instead be written as return booleanExpression;
- 22. Ternary Operator (?:)
• Use Ternary Operator for conditional assignment
• Example:
Int x;
If (expression) {
x = 9;
} else {
x = 0;
}
• can be written as x = (expression) ? 9 : 0;
- 23. so, what is the lesson to learn?
Whenever possible, reuse standards and guidelines,
don’t reinvent them
- 24. Java Code Quality Tools
CodePro Analytix QJ-Pro Dependometer
PMD Byecycle Hammurapi
FindBugs Coqua JavaNCSS
Cobertura Dependency Finder DCD
Emma Jalopy Classycle
Checkstyle JarAnalyzer ckjm
JBoss Tattletale Condenser Jameleon
UCDetector Relief DoctorJ
Sonar JCSC Macker
XRadar Spoon Squale
QALab Lint4j SourceMonitor
Clirr Crap4j Panopticon
JDiff PathFinder Eclipse Metrics plugin
JLint Soot cloc
JDepend ESC/Java2 AppPerfect
- 25. FindBugs PMD Checkstyle
License
Lesser GNU Public License BSD-style license Lesser General Public License
Purpose
Potential Bugs Bad Practices Conventions
finds - as the name suggests - bugs in
Java byte code
- looks for potential problems, possible
bugs,
scans source code and looks for coding
standards,
unused and sub-optimal code and over-
complicated expressions in the Java source
code
e.g. Sun Code Conventions, JavaDoc
Strengths
- finds often real defects
- finds occasionally real defects
- finds violations of coding conventions
- low false detected rates
- finds bad practices
- fast because byte code
- less than 50% false positive
Weaknesses
- is not aware of the sources - slow duplicate code detector - can't find real bugs
- needs compiled code
Number of rules
408 347 132
- 26. Correctnes s JSP Annota ti ons
Ba d pra cti ce - Ba s i c JSF Bl ock Checks
Dodgy code - Ba s i c JSP Cl a s s Des i gn
Mul ti threa ded
Correctnes s
XSL Codi ng
Performa nce Ma l i ci ous - XPa th i n XSL Dupl i ca te Code
Code Vul nera bi l i ty Ja va Hea ders
Securi ty Experi menta l - Des i gn I mports
I nterna ti ona l i za ti on - Coupl i ng Ja va doc Comments
- Ja ka rta Commons
Loggi ng
Metri cs
- Ba s i c Mi s cel l a neous
- Stri ct Excepti ons Modi fi ers
- Securi ty Code
Gui del i nes
Na mi ng Conventi ons
- Ja va Loggi ng Regexp
- Androi d -
Controvers i a l
Si ze Vi ol a ti ons
- Comments Whi tes pa ce
- Type Res ol uti on
- Empty Code
- Stri ng a nd
Stri ngBuffer
- Code Si ze
- Bra ces
- Unus ed Code
- Unneces s a ry
- J2EE
- Ja va Bea ns
- Mi gra ti on
- I mport Sta tements
- JUni t
- Na mi ng
- Fi na l i zer
- Opti mi za ti on
- Cl one
I mpl ementa ti on
Ecma s cri pt
- Ba s i c Ecma s cri pt
- Unneces s a ry
- Bra ces
XML
- Ba s i c XML
Rul e Ca tegori es
- 28. PMD
http://pmd.sourceforge.net/
Possible bugs empty try/catch/finally/switch statements
Dead code unused local variables, parameters and private
methods
Suboptimal code wasteful String/StringBuffer usage
Overcomplicated expressions unnecessary if statements, for loops that could
be while loops
Duplicate code copied/pasted code means copied/pasted bugs
PMD scans Java source code and looks for potential problems like:
- 29. Plugin installation
1. In Eclipse, click on Help -> Install New Software...
2. Click on Add..
Enter the following:
• Name: PMD for Eclipse Update Site
• URL: https://sourceforge.net/projects/pmd/files/pmd-eclipse/update-site/
and click OK.
3. You should see PMD for Eclipse 4. Select the checkbox next to it and click Next >.
4. Accept the License and Restart eclipse.
- 30. Configure Ant with PMD under Eclipse
• Download pmd-bin-5.3.4.zip from official website
• Unpack and Add jars above to Window - Preferences - Ant - Runtime
- Ant Home Entries - Add External JARs
• Unpack rulesets folder
• Reference location of ruleset from
<pmd rulesetfiles=...>
- 32. PMD with ANT Example
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse.ant.import?>
<project>
<path id="pmd.classpath">
<pathelement location="../../eclipse/plugins/net.sourceforge.pmd.eclipse.plugin_3.2.6.v200903300643"/>
<fileset dir="../../eclipse/plugins/net.sourceforge.pmd.eclipse.plugin_3.2.6.v200903300643">
<include name="**/*.jar" />
</fileset>
</path>
- 33. <target name="pmd-java">
<echo message="Run ant build with PMD (JAVA)" />
<taskdef name="pmd" classname="net.sourceforge.pmd.ant.PMDTask"
classpathref="pmd.classpath"/>
<pmd shortFilenames="true" encoding="UTF-8" targetjdk="1.6">
<ruleset>basic</ruleset> <ruleset>imports</ruleset>
<formatter type="html" toFile="doc/pmd/report-java.html"
linkPrefix="http://pmd.sourceforge.net/xref/"/>
<fileset dir="." >
<include name="src/**/*.java" /> <include name="test/**/*.java" />
</fileset>
</pmd>
<echo message="PMD complate: Report in doc/pmd_report-java.html" />
</target>
</project>
- 34. Goals
1.pmd:pmd creates a PMD site report based on the rulesets and configuration set in the plugin. It can also
generate a pmd output file aside from the site report in any of the following formats: xml, csv or txt.
2.pmd:cpd generates a report for PMD's Copy/Paste Detector (CPD) tool. It can also generate a cpd results
file in any of these formats: xml, csv or txt.
3.pmd:check verifies that the PMD report is empty and fails the build if it is not. This goal is executed by
default when pmd:pmd is executed.
4.pmd:cpd-check verifies that the CPD report is empty and fails the build if it is not. This goal is executed by
default when pmd:cpd is executed.
- 42. FindBugs
• FindBugs looks for bugs in Java programs.
• It is based on the concept of bug patterns.
• A bug pattern is a code idiom that is often an error and arise for a variety of reasons:
1.Difficult language features
2.Misunderstood API methods
3.Misunderstood invariants when code is modified during maintenance
4.Garden variety mistakes: typos, use of the wrong boolean operator
- 43. • Supports bug detectors written using the ASM bytecode framework.
• Uses dom4j for XML manipulation.
• It uses static analysis to identify hundreds of different potential types of
errors in Java programs. Potential errors are classified in four ranks:
1. scariest,
2. scary,
3. troubling
4. of concern.
- 45. • Findbugs provides the possibility to uncomment wrong and/or unwanted
warnings.
• There are two ways to remove warnings
1. The entire warning is switched off for all classes in the project settings
2. Single warnings can be disabled for certain piece of code
- 46. Plug-In Installation
1. In Eclipse, click on Help -> Install New Software...
2. Click on Add..
Enter the following:
Name: FindBugs for Eclipse
URL: http://findbugs.cs.umd.edu/eclipse and click OK.
3. You should see FindBugs. Select the checkbox next to it and click Next >.
4. Accept the license and confirm you want to install a plugin that is not digitally signed. Go
ahead and install it anyway.
5. Restart eclipse.
- 47. Configure Ant with Findbugs under Eclipse
• Download findbugs-3.0.1.zip from official website
• Unpack and Add jars in a separate folder under your project.
- 57. Checkstyle
• Checkstyle is a static code analysis tool used in software development for
checking if Java source code complies with coding rules.
• Checkstyle, originally developed by Oliver Burn back in 2001, is maintained
by a team of several developers around the world.
• The current stable release is version 5.7 which is targeted towards the Java
7 language.
- 58. • Defines a set of available modules,
• Each of which provides rules checking with a configurable level of strictness
(mandatory, optional...).
• Each rule can raise Notifications, Warnings, and Errors.
- 59. Checkstyle can examine
• Javadoc comments for classes, attributes and methods;
• Naming conventions of attributes and methods;
• Limit of the number of function parameters, line lengths;
• Presence of mandatory headers;
• The use of packets imports, of classes, of scope modifiers and of instructions blocks;
• The spaces between some characters;
• The good practices of class construction;
• Duplicated code sections;
• Multiple complexity measurements, among which expressions.
- 60. A Checkstyle plug-in can provide new functionalities, like:
• Overload syntax coloring or decorations in code editor;
• Decorate the project explorer to highlight problem-posing resources;
• Add warnings and errors outputs to the outputs.
- 61. Plug-In Installation
• In Eclipse, click on Help -> Install New Software...
• Click on Add..
• Enter the following:
• Name: Checkstyle for Eclipse
• URL: http://eclipse-cs.sf.net/update and click OK.
• You should see FindBugs. Select the checkbox next to it and click Next >.
• You'll need to accept the license and confirm you want to install a plugin that is
not digitally signed. Go ahead and install it anyway.
• Restart eclipse.
- 62. Configure Ant with Check style under Eclipse
• Download net.sf.eclipsecs-updatesite_6.9.0.201508291549-bin.zip
from official website
• Unpack and Add jars in a separate folder under your project.
- 64. Configuration
• You can turn of certain checks. If you change settings from the
standard profile you should always make a copy of the existing
profile.
• To customize your check, first make a copy of the checks
Editor's Notes
- Scott W. Ambler (1966) is a Canadian software engineer, consultant and author, currently Senior Consulting Partner at Scott Ambler + Associates. He is an author of a number of books focused on the Disciplined Agile Delivery process decision framework, the Unified process, Agile software development, the Unified Modeling Language, and CMM-based development. He regularly runs surveys which explore software development issues and works with organizations in different countries on their approach to software development.
Whenever possible, reuse standards and guidelines, don’t reinvent them. The greater the scope of the standards and guidelines the more desirable they are, industry standards are more desirable than organizational standards which in turn are more desirable than project standards. Projects aren’t developed in a vacuum and organizations do not operate in a vacuum either, therefore the greater the scope of the standard the greater the chance that somebody else is also following it, making it that much easier for you to work together with them.