Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

TIOBE Java Coding Standard

Uploaded by

s810531111
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

TIOBE Java Coding Standard

Uploaded by

s810531111
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

2024/11/27 下午6:58 TIOBE Java Coding Standard

TIOBE Java Coding Standard


Version: 3.10
Issuer: CCB Coding Standards TIOBE

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quuG… 1/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Purpose
This document defines the TIOBE Java Coding Standard. The coding standard consists of rules
and recommendations for code written and/or maintained in the Java programming language.

Scope
This coding standard applies to all Java code that is written and/or maintained. The procedure to
be followed when a rule must be broken is outside the scope of this document.

This coding standard does specify rules and recommendations

to prevent coding errors


to prevent coding using obsolete or deprecated language features
to prevent coding using undefined or implementation defined language features
to achieve a certain consistency in coding style

The TIOBE Java coding standard does not attempt to teach how to design effective Java code. It
also does not categorically rule out any programming idioms that Java is designed to support.

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quuG… 2/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Change History
3.10 2021-06-29
Maikel Steneker (TIOBE)
- Ticket 26834: Set rule Controversial5 to level 4 (from level 1)
- Ticket 26919: Removed rule ImportStatement101
- Ticket 27464: Removed rule Optimization5
- Ticket 28322: Removed rule Style101
- Ticket 28366: Removed rule Design34
3.9 2020-08-27
Maikel Steneker (TIOBE)
- Ticket 26251: Set rule Design21 to level 2 (from level 1)
- Ticket 24082: Added rule Multithreading1
- Ticket 26226: Added rule Optimization12
- Ticket 26255: Added rule UnusedCode5
3.8 2019-12-30
Maikel Steneker (TIOBE)
- Ticket 24576: Set rule StrictException2 to level 3 (from level 1)
- Ticket 24404: Removed rule Import101
3.7 2019-07-10
Maikel Steneker (TIOBE)
- Ticket 23413: Added rule Optimization11
3.6 2019-05-27
Maikel Steneker (TIOBE)
- Ticket 23129: Added rule TypeResolution4
3.5 2019-04-26
Maikel Steneker (TIOBE)
- Ticket 22727: Added rules Basic34, StrictException8 and TypeResolution3
3.4 2019-04-01
Maikel Steneker (TIOBE)
- Ticket 22586: Removed rule Design33
3.3 2019-03-06
Maikel Steneker (TIOBE)
Changes for ticket 22585:
- Renamed rule CodeSize11 to CodeSize100
- Added rule UnusedCode100
3.2 2019-02-27
Maikel Steneker (TIOBE)
Changes for ticket 21024:

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quuG… 3/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

- Removed rules CodeSize9 and CodeSize10


- Adjusted the description of rule Design40
3.1 2019-02-19
Maikel Steneker (TIOBE)
Changes for ticket 21120:
- Added rules Basic103, CodeSize11, Design101, StrictException102,
StringandStringBuffer14
- Adjusted the description of rule Design33 to differentiate it from rule
StringandStringBuffer14
3.0 2018-07-26
Paul Jansen (TIOBE):
Changes for ticket 20136:
- Added rules Basic31, Basic32, Basic33, CloneImplementation4, Design45,
Optimization10, Security1 and Security2.
- Adjusted rules Basic19 and Design15.
- Removed rules Controversial4, Naming4, Naming5, Naming6, Naming 7,
Naming9, Naming11, Naming 17 and Naming101.
2.7 2018-03-16
Paul Jansen (TIOBE):
- Ticket 20396: Improved the description of rules Basic10, Basic 11, Basic
12, Basic23, Basic24, Basic25, Basic29 and Basic100.
2.6 2018-01-07
Paul Jansen (TIOBE):
- Ticket 20029: Adjusted scope of this document.
2.5 2017-01-18
Bram Stappers (TIOBE)
- Ticket 10002: Improved description of rule Basic14
2.4 2017-01-13
Bram Stappers (TIOBE)
- Ticket 15954: Added rule ImportStatement101
2.3 2016-02-23
Bram Stappers (TIOBE):
- Ticket 16337: Updated TIOBE logo/images.
2.2 2016-01-15
Paul Jansen (TIOBE):
- TICS ticket 16256: Removed rule Style102.
2.1 2015-02-16
- Added rule "Basic102".
2.0 2014-07-12

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quuG… 4/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

- Added rule "Optimization100".


- Updated the document to support the Google Android standard.
1.15 2012-12-07
Improved synopsis of rule "Basic18".
1.14 2011-06-09
Improved rule "Naming4".
1.13 2010-04-04
Logo front page changed.
1.12 2010-03-21
Changed front page.
1.11 2010-01-10
Added new rule "Design 44".
1.10 2009-11-22
Rule "Controversial4" set from 3 to 7.
1.9 2009-10-21
New rule added: Design43.
1.8 2009-10-01
Removed the following rules: CodeSize8, Controversial11, and
Optimization2.
Set the following rules temporarily to unchecked: Design4 and
Design33.
Extended rule Naming18 for variables starting with 'mX'

1.7 2009-04-01
Title page improved.
1.6 2009-03-21
Minor corrections.
1.5 2009-03-21
Rule "Design31" removed.
1.4 2009-02-08
Rule "Controversial12" removed and the level of rule "Optimization1" set
from 2 to 4.
1.3 2009-01-23
Introduction improved.
1.2 2009-01-23
Rule Optimization3 removed.
1.1 2008-12-27
Revision after feedback from Manuel Bilderbeek and Jacques Bergmans
(Océ Technologies).

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quuG… 5/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

1.0 2007-03-05
Initial Version.

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quuG… 6/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Basic
Basic2
Synopsis Avoid empty 'if' statements
Level 2
Category Basic
Status Checked
Empty If Statement finds instances where a condition is checked but nothing is done about it.
public class Foo {
void bar(int x) {
if (x == 0) {
// empty!
}
}
}

Basic3
Synopsis Avoid empty 'while' statements
Level 2
Category Basic
Status Checked
Empty While Statement finds all instances where a while statement does nothing. If it is a timing
loop, then you should use Thread.sleep() for it; if it's a while loop that does a lot in the exit
expression, rewrite it to make it clearer.
public class Foo {
void bar(int a, int b) {
while (a == b) {
// empty!
}
}
}

Basic4
Synopsis Avoid empty try blocks
Level 1
Category Basic
Status Checked
Avoid empty try blocks - what's the point?

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quuG… 7/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

public class Foo {


public void bar() {
try {
} catch (Exception e) {
e.printStackTrace();
}
}
}

Basic5
Synopsis Avoid empty finally blocks
Level 5
Category Basic
Status Checked
Avoid empty finally blocks - these can be deleted.
public class Foo {
public void bar() {
try {
int x=2;
} finally {
// empty!
}
}
}

Basic6
Synopsis Avoid empty switch statements
Level 1
Category Basic
Status Checked
Avoid empty switch statements.
public class Foo {
public void bar() {
int x = 2;
switch (x) {
// once there was code here
// but it's been commented out or something
}
}
}

Basic7
https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quuG… 8/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Avoid modifying an outer loop incrementer in an inner loop for update


Synopsis
expression
Level 1
Category Basic
Status Checked
Avoid jumbled loop incrementers - it's usually a mistake, and it's confusing even if it's what's
intended.
public class JumbledIncrementerRule1 {
public void foo() {
for (int i = 0; i < 10; i++) {
for (int k = 0; k < 20; i++) {
System.out.println("Hello");
}
}
}
}

Basic8
Synopsis This for loop could be simplified to a while loop
Level 4
Category Basic
Status Checked
Some for loops can be simplified to while loops - this makes them more concise.
public class Foo {
void bar() {
for (;true;) {
// No Init or Update part, may as well be: while (true)
}
}
}

Basic9
Synopsis Avoid unnecessary temporaries when converting primitives to Strings
Level 3
Category Basic
Status Checked
Avoid unnecessary temporaries when converting primitives to Strings
public String convert(int x) {
// this wastes an object
String foo = new Integer(x).toString();
// this is better

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quuG… 9/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

return Integer.toString(x);
}

Basic10
Synopsis Ensure you override both equals() and hashCode()
Level 2
Category Basic
Status Checked
Override both public boolean Object.equals(Object other), and public int Object.hashCode(), or
override neither. Even if you are inheriting a hashCode() from a parent class, consider
implementing hashCode and explicitly delegating to your superclass.
// this is bad
public class Bar {
public boolean equals(Object o) {
// do some comparison
}
}

// and so is this
public class Baz {
public int hashCode() {
// return some hash value
}
}

// this is OK
public class Foo {
public boolean equals(Object other) {
// do some comparison
}
public int hashCode() {
// return some hash value
}
}

Justification:

“You must override hashCode() in every class that overrides equals(). Failure to do so will result
in a violation of the general contract for Object.hashCode(), which will prevent your class from
functioning properly in conjunction with all hash-based collections, including HashMap,
HashSet, and Hashtable.” from Effective Java, by Joshua Bloch.

If two objects are equal according to the {@code equals(Object)} method, then calling the
{@code hashCode} method on each of the two objects must produce the same integer result.​

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 10/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

So, implementing an equals() method comparing 2 members, and then implementing a


hashCode() which only calls super.hashCode() is just as bad.

Basic11
Synopsis Double checked locking is not thread safe in Java
Level 1
Category Basic
Status Checked
Partially created objects can be returned by the Double Checked Locking pattern when used in
Java. An optimizing JRE may assign a reference to the baz variable before it creates the object
the reference is intended to point to.
public class Foo {
Object baz;

Object bar() {
if(baz == null) { //baz may be non-null yet not fully created
synchronized(this){
if(baz == null){
baz = new Object();
}
}
}
return baz;
}
}

Justification:

First of all, because the null-check is outside of the synchronized block when 2 threads are
"simultaneously" doing the null-check then both will enter the if-statement. One of them will
enter the synchronized block, and the other one is stopped. The first one will create a new
Object and leave the synchronized block. That allows the 2nd thread to enter the synchronized
block and create another Object. The 2nd thread will still create another Object because
compiler generation of the instructions for writes that initialize the "baz" Object may be
executed after.

One of the suggested fixes is to declare the baz object as volatile:

public class Foo {


volatile Object baz;

Object bar() {
if(baz == null) { //baz may be non-null yet not fully created
synchronized(this) {

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 11/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

if(baz == null){
baz = new Object();
}
}
}
return baz;
}
}

However, even if JVM prevents writes to volatile variables to be reordered and ensures that they
are flushed to main memory immediately, it still permits reordering of reads and writes
instructions for volatile variable with respect to reads and writes for nonvolatile variables. Which
means, considering two threads A and B, unless all fields of "baz" type class are volatile as well,
thread B can still perceive the constructor's effect as happening after "baz" object is set to
reference by the thread A.

For more details see http://www.javaworld.com/javaworld/jw-02-2001/jw-0209-double.html.

Basic12
Synopsis Avoid returning from a finally block
Level 1
Category Basic
Status Checked
Avoid returning from a finally block - this can discard exceptions.
public class Bar {
public String foo() {
try {
throw new Exception( "My Exception" );
} catch (Exception e) {
throw e;
} finally {
return "A. O. K."; // Very bad.
}
}
}

Justification:

According to Java Language Specification: "If execution of the try block completes abruptly for
any other reason R, then the finally block is executed, and then there is a choice:

If the finally block completes normally, then the try statement completes abruptly for
reason R.

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 12/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

If the finally block completes abruptly for reason S, then the try statement completes
abruptly for reason S (and reason R is discarded).​"

Basic13
Synopsis Avoid empty synchronized blocks
Level 4
Category Basic
Status Checked
Avoid empty synchronized blocks - they're useless.
public class Foo {
public void bar() {
synchronized (this) {
// empty!
}
}
}

Basic14
Synopsis Avoid unnecessary return statements
Level 3
Category Basic
Status Checked
Avoid unnecessary return statements in methods with return type void.
public class Foo {
public void bar() {
int x = 42;
return;
}
}

Basic15
Synopsis Empty static initializer was found
Level 3
Category Basic
Status Checked
An empty static initializer was found.
public class Foo {
static {
// empty

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 13/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

}
}

Basic16
Synopsis Do not use 'if' statements that are always true or always false
Level 3
Category Basic
Status Checked
Do not use "if" statements that are always true or always false.
public class Foo {
public void close() {
if (true) {
// ...
}
}
}

Basic17
Synopsis An empty statement (semicolon) not part of a loop
Level 3
Category Basic
Status Checked
An empty statement (aka a semicolon by itself) that is not used as the sole body of a for loop or
while loop is probably a bug. It could also be a double semicolon, which is useless and should
be removed.
public class MyClass {
public void doit() {
// this is probably not what you meant to do
;
// the extra semicolon here this is not necessary
System.out.println("look at the extra semicolon");;
}
}

Basic18
Synopsis Avoid instantiating Boolean objects; reference Boolean.TRUE or Boolean.FALSE
Level 2
Category Basic
Status Checked
Avoid instantiating Boolean objects; you can reference Boolean.TRUE or Boolean.FALSE.

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 14/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

public class Foo {


Boolean bar = new Boolean("true"); // just do a Boolean bar = Boolean.TRUE;
Boolean buz = Boolean.valueOf(false); // just do a Boolean buz = Boolean.FALSE;
}

Basic19
Synopsis Unnecessary modifier used
Level 5
Category Basic
Status Checked
Fields in interfaces and annotations are automatically public static final, and methods are
public abstract. Classes, interfaces or annotations nested in an interface or annotation are
automatically public static (all nested interfaces and annotations are automatically static).
Nested enums are automatically static. For historical reasons, modifiers which are implied by
the context are accepted by the compiler, but are superfluous.

public @interface Annotation {


public abstract void bar(); // both abstract and public are ignored by the
compiler
public static final int X = 0; // public, static, and final all ignored
public static class Bar {} // public, static ignored
public static interface Baz {} // ditto
}
public interface Foo {
public abstract void bar(); // both abstract and public are ignored by the
compiler
public static final int X = 0; // public, static, and final all ignored
public static class Bar {} // public, static ignored
public static interface Baz {} // ditto
}
public class Bar {
public static interface Baz {} // static ignored
public static enum FoorBar { // static ignored
FOO;
}
}

Basic21
Synopsis Overriding method merely calls super
Level 2
Category Basic
Status Checked

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 15/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

The overriding method merely calls the same method defined in a superclass
public String foo() {
return super.foo(); //Why bother overriding?
}

Basic22
Synopsis This usage of the Collection.toArray() method will throw a ClassCastException
Level 1
Category Basic
Status Checked
if you need to get an array of a class from your Collection, you should pass an array of the
desidered class as the parameter of the toArray method. Otherwise you will get a
ClassCastException.
import java.util.ArrayList;
import java.util.Collection;

public class Test {

public static void main(String[] args) {


Collection c=new ArrayList();
Integer obj=new Integer(1);
c.add(obj);

// this would trigger the rule (and throw a ClassCastException


if executed)
Integer[] a=(Integer [])c.toArray();

// this wouldn't trigger the rule


Integer[] b=(Integer [])c.toArray(new Integer[c.size()]);
}
}

Basic23
Synopsis Avoid creating BigDecimal with a decimal (float/double) literal. Use a String literal
Level 1
Category Basic
Status Checked
It is generally recommended that the valueOf() should be used in preference to BigDecimal
constructor with float/double parameter. The value returned is equal to that resulting from using
the BigDecimal constructor with String parameter.

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 16/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Note: valueOf() will use the canonical String representation of thedoublevalue passed in to
instantiate theBigDecimal object. In other words: The value of theBigDecimalobject will be what
you see when you doSystem.out.println(d).​

import java.math.BigDecimal;
public class Test {

public static void main(String[] args) {


// this would trigger the rule
BigDecimal bd=new BigDecimal(1.123);
// this wouldn't trigger the rule
BigDecimal bd=new BigDecimal("1.123");
// this wouldn't trigger the rule
BigDecimal bd=new BigDecimal(12);
}
}

Justification:

One might assume that "new BigDecimal(.1)" is exactly equal to .1, but it is actually equal to
.1000000000000000055511151231257827021181583404541015625. This is so because .1 cannot
be represented exactly as a double (or, for that matter, as a binary fraction of any finite length).
Thus, the long value that is being passed in to the constructor is not exactly equal to .1,
appearances notwithstanding.

The (String) constructor, on the other hand, is perfectly predictable: 'new BigDecimal(".1")' is
exactly equal to .1, as one would expect. Therefore, it is generally recommended that the (String)
constructor be used in preference to this one.

Basic24
An operation on an Immutable object (BigDecimal or BigInteger) won't change
Synopsis
the object itself
Level 1
Category Basic
Status Checked
An operation on an Immutable object (BigDecimal or BigInteger) won't change the object itself.
The result of the operation is a new object. Therefore, ignoring the operation result is an error.
import java.math.*;
class Test {
void method1() {
BigDecimal bd=new BigDecimal(10);
bd.add(new BigDecimal(5)); // this will trigger the rule
}
void method2() {

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 17/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

BigDecimal bd=new BigDecimal(10);


bd = bd.add(new BigDecimal(5)); // this won't trigger the rule
}
}

Justification:

The value of the immutable object instance cannot be change after it's created. When we
attempt to alter the internal fields of an immutable object, the reference of the respective object
it is changed to refer to a new instance of that type.

Basic25
The null check here is misplaced; if the variable is null there'll be a
Synopsis
NullPointerException
Level 1
Category Basic
Status Checked
The null check here is misplaced. if the variable is null you'll get a NullPointerException. Either
the check is useless (the variable will never be "null") or it's incorrect.
public class Foo {
void bar() {
if (a.equals(baz) || a == null) {}
}
}

Justification:

If the variable is null, a NullPointerException is triggered when equals method is called.

Basic28
Synopsis Method call on object which may be null
Level 1
Category Basic
Status Checked
The null check is broken since it will throw a Nullpointer itself. The reason is that a method is
called on the object when it is null. It is likely that you used || instead of && or vice versa.
class Foo {
String munge(String string) {
// should be &&
if (string!=null || !string.equals(""))
return string;
// should be ||

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 18/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

if (string==null && string.equals(""))


return string;
}
}

Basic29
Don't create instances of already existing BigInteger and BigDecimal (ZERO, ONE,
Synopsis
TEN)
Level 5
Category Basic
Status Checked
Don't create instances of already existing BigInteger (BigInteger.ZERO, BigInteger.ONE) and for
1.5 on, BigInteger.TEN and BigDecimal (BigDecimal.ZERO, BigDecimal.ONE, BigDecimal.TEN)
public class Test {

public static void main(String[] args) {


BigInteger bi=new BigInteger(1);
BigInteger bi2=new BigInteger("0");
BigInteger bi3=new BigInteger(0.0);
BigInteger bi4;
bi4=new BigInteger(0);
}
}

Justification:

Avoid creating unnecessary new instance when there is already one(e.g. BigDecimal.ZERO).
BigDecimal.ZERO will never change because BigDecimal is an immutable class.

Basic30
Synopsis Do not start a literal by 0 unless it's an octal value
Level 2
Category Basic
Status Checked
Integer literals should not start with zero. Zero means that the rest of literal will be interpreted
as an octal value.
public class Foo {
int i = 012; // set i with 10 not 12
int j = 010; // set j with 8 not 10
k = i * j; // set k with 80 not 120
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 19/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Basic31
Synopsis Replace for loop by for each loop
Level 5
Category Basic
Status Checked
Reports loops that can be safely replaced with the foreach syntax. The rule considers loops over
lists, arrays and iterators. A loop is safe to replace if it only uses the index variable to access an
element of the list or array, only has one update statement, and loops through every element of
the list or array left to right.

public class MyClass {


void loop(List

Basic32
Synopsis Use @Override annotation if applicable
Level 4
Category Basic
Status Checked
Annotating overridden methods with @Override ensures at compile time that the method really
overrides one, which helps refactoring and clarifies intent.

public class Foo implements Runnable {


// This method is overridden, and should have an @Override annotation
public void run() {

}
}

Basic33
Synopsis Merge identical catch branches
Level 6
Category Basic
Status Checked
Identical catch branches use up vertical space and increase the complexity of code without
adding functionality. It’s better style to collapse identical branches into a single multi-catch
branch.

try {
// do something
} catch (IllegalArgumentException e) {

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 20/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

throw e;
} catch (IllegalStateException e) { // Can be collapsed into the previous block
throw e;
}

try {
// do something
} catch (IllegalArgumentException | IllegalStateException e) { // This is better
throw e;
}

Basic34
Synopsis Don't use unclear do/while loops
Level 7
Category Basic
Status Checked
Some do while loops are hard to understand and can be simplified or omitted.
public class Example {
{
while (true) { } // allowed
while (false) { } // should be removed; the block will never be executed
do { } while (true); // should be simplified to while (true) { }
do { } while (false); // should be simplified; the block will be executed once
}
}

Basic100
Synopsis Each variable should have an initializer.
Level 3
Category Basic
Status Checked
Local variables should be declared at the point they are first used. Nearly every local variable
declaration should contain an initializer. If you don't yet have enough information to initialize a
variable sensibly, you should postpone the declaration until you do.

Justification:

Failure to initialize a local variable has been identified as a very common source of error. Also,
declaring local variables without using them immediately may increase their scope.

Basic101
Synopsis Use standard brace style.

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 21/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Level 4
Category Basic
Status Checked
Braces do not go on their own line; they go on the same line as the code before them. So:

class MyClass {
int func() {
if (something) {
// ...
} else if (somethingElse) {
// ...
} else {
// ...
}
}
}

We require braces around the statements for a conditional. Except, if the entire conditional (the
condition and the body) fit on one line, you may (but are not obligated to) put it all on one line.
That is, this is legal:

if (condition) {
body();
}

and this is legal:

if (condition) body();

but this is still illegal:

if (condition)
body(); // bad!

Basic102
Synopsis Avoid implicit allocation of objects
Level 4
Category Basic
Status Checked
When writing code such as

byte[] myLocalStackVariable = { 0x00, 0x00 };

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 22/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Java implicitly allocates an object. For some applications this is a bad thing. It is better to make
the allocation explicit:

byte[] myLocalStackVariable = new byte[] {0x00, 0x00};

This way everybody will realize that a new object is allocated.

Basic103
Synopsis Don't modify control variables within a for block
Level 2
Category Basic
Status Checked
Reassigning loop variables can lead to hard-to-find bugs. Prevent or limit how these variables
can be changed.
for (int i = 0; i < 1; i++) {
i++; //violation
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 23/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

CloneImplementation
CloneImplementation4
Synopsis Clone method should be public
Level 5
Category CloneImplementation
Status Checked
The java Manual says “By convention, classes that implement this interface should override
Object.clone (which is protected) with a public method.”

public class Foo implements Cloneable {


@Override
protected Object clone() throws CloneNotSupportedException { // Violation, must be
public
}
}

public class Foo implements Cloneable {


@Override
protected Foo clone() { // Violation, must be public
}
}

public class Foo implements Cloneable {


@Override
public Object clone() // Ok
}

CloneImplementation5
Synopsis Clone method return type should match class name
Level 4
Category CloneImplementation
Status Checked
If a class implements cloneable the return type of the method clone() must be the class name.
That way, the caller of the clone method doesn’t need to cast the returned clone to the correct
type.

public class Foo implements Cloneable {


@Override
protected Object clone() { // Violation, Object must be Foo
}
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 24/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

public class Foo implements Cloneable {


@Override
public Foo clone() { //Ok
}
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 25/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

CodeSize
CodeSize1
Synopsis Avoid complex methods
Level 2
Category CodeSize
Status Checked
The NPath complexity of a method is the number of acyclic execution paths through that
method. A threshold of 200 is generally considered the point where measures should be taken
to reduce complexity.

CodeSize2
Synopsis Avoid really long methods
Level 2
Category CodeSize
Status Checked
Violations of this rule usually indicate that the method is doing too much (containing more than
100 statements). Try to reduce the method size by creating helper methods and removing any
copy/pasted code.
public class Foo {
public void doSomething() {
System.out.println("Hello world!");
System.out.println("Hello world!");
// 98 copies omitted for brevity.
}
}

CodeSize3
Synopsis Avoid really long parameter lists
Level 2
Category CodeSize
Status Checked
Long parameter lists can indicate that a new object should be created to wrap the numerous
parameters. Basically, try to group the parameters together. This rule triggers if a method has 10
or more parameters.
public class Foo {
public void addData(
int p0, int p1, int p2, int p3, int p4, int p5,
int p5, int p6, int p7, int p8, int p9, int p10) {

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 26/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

}
}
}

CodeSize4
Synopsis Avoid really long classes
Level 2
Category CodeSize
Status Checked
Long class files are indications that the class may be trying to do too much. Try to break it down,
and reduce the size to something manageable. This rule triggers in case a class has 1000 or
more lines of code.

CodeSize5
Synopsis Avoid complex code
Level 2
Category CodeSize
Status Checked
Complexity is determined by the number of decision points in a method plus one for the
method entry. The decision points are 'if', 'while', 'for', and 'case labels'. Generally, 1-4 is low
complexity, 5-7 indicates moderate complexity, 8-10 is high complexity, and 11+ is very high
complexity. This rule triggers if a method has a complexity of 10 or more.

The higher the cyclomatic complexity, the harder it is to write a set of unit tests that cover all
branches. Cyclomatic complexity is an indication how hard it is to test your code.

// Cyclomatic Complexity = 12
public class Foo {
1 public void example() {
2 if (a == b) {
3 if (a1 == b1) {
fiddle();
4 } else if a2 == b2) {
fiddle();
} else {
fiddle();
}
5 } else if (c == d) {
6 while (c == d) {
fiddle();
}
7 } else if (e == f) {
8 for (int n = 0; n < h; n++) {

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 27/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

fiddle();
}
} else{
switch (z) {
9 case 1:
fiddle();
break;
10 case 2:
fiddle();
break;
11 case 3:
fiddle();
break;
12 default:
fiddle();
break;
}
}
}
}

CodeSize6
Synopsis This class has too many public methods and attributes
Level 2
Category CodeSize
Status Checked
A large number of public methods and attributes declared in a class can indicate the class may
need to be broken up as increased effort will be required to thoroughly test it. This rule is
triggered in case a class has 45 or more public methods and/or attributes.
public class Foo {
public String value;
public Bar something;
public Variable var;
// [... more more public attributes ...]
public void doWork() {}
public void doMoreWork() {}
public void doWorkAgain() {}
// [... more more public methods ...]
}

CodeSize7
Synopsis Too many fields
Level 3

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 28/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Category CodeSize
Status Checked
Classes that have too many fields could be redesigned to have fewer fields, possibly through
some nested object grouping of some of the information. For example, a class with city/state/zip
fields could instead have one Address field. This rule is triggered in case a class has 15 or more
fields.
public class Person {
String one;
int two;
int three;
[... many more public fields ...]
}

CodeSize100
Synopsis Avoid long files
Level 4
Category CodeSize
Status Checked
If a source file becomes very long it is hard to understand. Therefore long classes should usually
be refactored into several individual classes that focus on a specific task.

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 29/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Comments
Comments100
Synopsis Every file should have a copyright statement at the top.
Level 7
Category Comments
Status Checked
For example

/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

Comments101
Synopsis Use standard Java annotations.
Level 5
Category Comments
Status Checked
Annotations should precede other modifiers for the same language element. Simple marker
annotations (e.g. @Override) can be listed on the same line with the language element. If there
are multiple annotations, or parameterized annotations, they should each be listed one-per-line
in alphabetical order.

Android standard practices for the three predefined annotations in Java are:

@Deprecated: The @Deprecated annotation must be used whenever the use of the
annotated element is discouraged. If you use the @Deprecated annotation, you must also
have a @deprecated Javadoc tag and it should name an alternate implementation. In
addition, remember that a @Deprecated method is still supposed to work.

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 30/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

If you see old code that has a @deprecated Javadoc tag, please add the @Deprecated
annotation.
@Override: The @Override annotation must be used whenever a method overrides the
declaration or implementation from a super-class.

For example, if you use the @inheritdocs Javadoc tag, and derive from a class (not an
interface), you must also annotate that the method @Overrides the parent class's method.

@SuppressWarnings: The @SuppressWarnings annotation should only be used under


circumstances where it is impossible to eliminate a warning. If a warning passes this
"impossible to eliminate" test, the @SuppressWarnings annotation must be used, so as to
ensure that all warnings reflect actual problems in the code.

When a @SuppressWarnings annotation is necessary, it must be prefixed with a TODO


comment that explains the "impossible to eliminate" condition. This will normally identify an
offending class that has an awkward interface. For example:

// TODO: The third-party class com.third.useful.Utility.rotate() needs generics


@SuppressWarnings("generic-cast")
List

When a @SuppressWarnings annotation is required, the code should be refactored to


isolate the software elements where the annotation applies.

Comments103
Synopsis Use TODO comments.
Level 7
Category Comments
Status Checked
Use TODO comments for code that is temporary, a short-term solution, or good-enough but not
perfect.

TODOs should include the string TODO in all caps, followed by a colon:

// TODO: Remove this code after the UrlTable2 has been checked in.

and

// TODO: Change this to use a flag instead of a constant.

If your TODO is of the form "At a future date do something" make sure that you either include a
very specific date ("Fix by November 2005") or a very specific event ("Remove this code after all
production mixers understand protocol V7.").

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 31/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Comments104
Synopsis Each class should be preceded by JavaDoc comments.
Level 6
Category Comments
Status Checked
For example:

import java.sql.ResultSet;
import java.sql.SQLException;

/**
* Does X and Y and provides an abstraction for Z.
*/

public class Foo {


...
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 32/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Controversial
Controversial5
Synopsis Avoid assignments in operands
Level 4
Category Controversial
Status Checked
Avoid assignments in operands; this can make code more complicated and harder to read.
public class Foo {
public void bar() {
int x = 2;
if ((x = getX()) == 3) {
System.out.println("3!");
}
}
private int getX() {
return 3;
}
}

Controversial7
Synopsis Avoid importing anything from the 'sun.*' packages
Level 1
Category Controversial
Status Checked
Avoid importing anything from the 'sun.*' packages. These packages are not portable and are
likely to change.
import sun.misc.foo;
public class Foo {}

Controversial8
Synopsis Suspicious decimal characters following octal escape in string literal
Level 1
Category Controversial
Status Checked
A suspicious octal escape sequence was found inside a String literal. The Java language
specification (section 3.10.6) says an octal escape sequence inside a literal String shall consist of
a backslash followed by: OctalDigit | OctalDigit OctalDigit | ZeroToThree OctalDigit OctalDigit

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 33/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Any octal escape sequence followed by non-octal digits can be confusing, e.g. "\038" is
interpreted as the octal escape sequence "\03" followed by the literal character "8".
public class Foo {
public void foo() {
// interpreted as octal 12, followed by character '8'
System.out.println("suspicious: \128");
}
}

Controversial10
Synopsis This statement may have some unnecessary parentheses
Level 6
Category Controversial
Status Checked
Sometimes expressions are wrapped in unnecessary parentheses, making them look like a
function call.
public class Foo {
boolean bar() {
return (true);
}
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 34/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Coupling
Coupling1
Synopsis High amount of different objects as members denotes a high coupling
Level 4
Category Coupling
Status Checked
This rule counts unique attributes, local variables and return types within an object. A number
higher than specified threshold can indicate a high degree of coupling. This treshold has been
set to 20.
import com.Blah;
import org.Bar;
import org.Bardo;
public class Foo {
private Blah var1;
private Bar var2;
//followed by many imports of unique objects
void ObjectC doWork() {
Bardo var55;
ObjectA var44;
ObjectZ var93;
return something;
}
}

Coupling2
Synopsis A high number of imports can indicate a high degree of coupling within an object
Level 3
Category Coupling
Status Checked
A high number of imports can indicate a high degree of coupling within an object. Rule counts
the number of unique imports and reports a violation if the count is above the user defined
threshold. This treshold has been set to 30.
import blah.blah.Baz;
import blah.blah.Bif;
// 18 others from the same package elided
public class Foo {
public void doWork() {}
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 35/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Design
Design1
Synopsis Classes with only static methods should have a private constructor
Level 3
Category Design
Status Checked
If you have a class that has nothing but static methods, it allows either one instance or none at
all. In either case a private constructor should be used. This also holds in case exactly one
instance is allowed, because the Singleton pattern uses a private constructor.

Note that this doesn't apply to abstract classes, since their subclasses may well include non-
static methods.

public class MaybeASingleton {


public static void foo() {}
public static void bar() {}
}

Design2
Synopsis Avoid unnecessary if..then..else statements when returning a boolean
Level 4
Category Design
Status Checked
Avoid unnecessary if..then..else statements when returning a boolean.
public class Foo {
private int bar =2;
public boolean isBarEqualsTo(int x) {
// this bit of code
if (bar == x) {
return true;
} else {
return false;
}
// can be replaced with a simple
// return bar == x;
}
}

Design3
Synopsis Avoid unnecessary comparisons in boolean expressions

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 36/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Level 4
Category Design
Status Checked
Avoid unnecessary comparisons in boolean expressions - this complicates simple code.
public class Bar {
// can be simplified to
// bar = isFoo();
private boolean bar = (isFoo() == true);

public isFoo() { return false;}


}

Design4
Synopsis Switch statements should have a default label
Level 2
Category Design
Status Unchecked
Switch statements should have a default label.
public class Foo {
public void bar() {
int x = 2;
switch (x) {
case 2: int j = 8;
}
}
}

Design5
Synopsis Deeply nested if..then statements are hard to read
Level 2
Category Design
Status Checked
Deeply nested if..then statements are hard to read.
public class Foo {
public void bar(int x, int y, int z) {
if (x>y) {
if (y>z) {
if (z==x) {
// whew, too deep
}
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 37/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

}
}
}

Design6
Synopsis Avoid reassigning parameters
Level 2
Category Design
Status Checked
Reassigning values to parameters is a questionable practice. Use a temporary local variable
instead.
public class Foo {
private void foo(String bar) {
bar = "something else";
}
}

Design7
Synopsis A high ratio of statements to labels in a switch statement. Consider refactoring
Level 3
Category Design
Status Checked
A high ratio of statements to labels in a switch statement implies that the switch statement is
doing too much work. Consider moving the statements into new methods, or creating
subclasses based on the switch variable.
public class Foo {
public void bar(int x) {
switch (x) {
case 1: {
// lots of statements
break;
} case 2: {
// lots of statements
break;
}
}
}
}

Design8
Synopsis Don't call overridable methods during object construction

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 38/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Level 1
Category Design
Status Checked
Calling overridable methods during construction poses a risk of invoking methods on an
incompletely constructed object and can be difficult to discern. It may leave the sub-class unable
to construct its superclass or forced to replicate the construction process completely within
itself, losing the ability to call super(). If the default constructor contains a call to an overridable
method, the subclass may be completely uninstantiable. Note that this includes method calls
throughout the control flow graph - i.e., if a constructor Foo() calls a private method bar() that
calls a public method buz(), this denotes a problem.
public class SeniorClass {
public SeniorClass(){
toString(); //may throw NullPointerException if overridden
}
public String toString(){
return "IAmSeniorClass";
}
}
public class JuniorClass extends SeniorClass {
private String name;
public JuniorClass(){
super(); //Automatic call leads to NullPointerException
name = "JuniorClass";
}
public String toString(){
return name.toUpperCase();
}
}

Design9
Avoid instantiation through private constructors from outside of the constructor's
Synopsis
class
Level 3
Category Design
Status Checked
Instantiation by way of private constructors from outside of the constructor's class often causes
the generation of an accessor. A factory method, or non-privitization of the constructor can
eliminate this situation. The generated class file is actually an interface. It gives the accessing
class the ability to invoke a new hidden package scope constructor that takes the interface as a
supplementary parameter. This turns a private constructor effectively into one with package
scope, and is challenging to discern.

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 39/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

public class Outer {


void method(){
Inner ic = new Inner();//Causes generation of accessor class
}
public class Inner {
private Inner(){}
}
}

Design10
Synopsis This final field could be made static
Level 4
Category Design
Status Checked
If a final field is assigned to a compile-time constant, it could be made static, thus saving
overhead in each object at runtime.
public class Foo {
public final int BAR = 42; // this could be static and save some space
}

Design11
Synopsis Ensure that resources are closed after use
Level 1
Category Design
Status Checked
Ensure that resources (like Connection, Statement, and ResultSet objects) are always closed after
use.
public class Bar {
public void foo() {
Connection c = pool.getConnection();
try {
// do stuff
} catch (SQLException ex) {
// handle exception
} finally {
// oops, should close the connection using 'close'!
// c.close();
}
}
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 40/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Design12
Synopsis Non-static initializers are confusing
Level 2
Category Design
Status Checked
A nonstatic initializer block will be called any time a constructor is invoked (just prior to invoking
the constructor). While this is a valid language construct, it is rarely used and is confusing.
public class MyClass {
// this block gets run before any call to a constructor
{
System.out.println("I am about to construct myself");
}
}

Design13
Synopsis The default label should be the last label in a switch statement
Level 3
Category Design
Status Checked
By convention, the default label should be the last label in a switch statement.
public class Foo {
void bar(int a) {
switch (a) {
case 1: // do something
break;
default: // the default case should be last, by convention
break;
case 2:
break;
}
}
}

Design14
Synopsis A non-case label was present in a switch statement
Level 2
Category Design
Status Checked
A non-case label (e.g. a named break/continue label) was present in a switch statement. This
legal, but confusing. It is easy to mix up the case labels and the non-case labels.

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 41/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

public class Foo {


void bar(int a) {
switch (a) {
case 1:
// do something
break;
mylabel: // this is legal, but confusing!
break;
default:
break;
}
}
}

Design15
Synopsis This call to Collection.toArray() may be optimizable
Level 5
Category Design
Status Checked
Calls to a collection’s toArray(E[]) method should specify a target array of zero size. This allows
the JVM to optimize the memory allocation and copying as much as possible.

Note: If you don’t need an array of the correct type, then the simple toArray() method without
an array is faster, but returns only an array of type Object[].

class Foo {
List

Design16
Synopsis Avoid equality comparisons with Double.NaN
Level 1
Category Design
Status Checked
Avoid equality comparisons with Double.NaN - these are likely to be logic errors.
public class Bar {
boolean x = (y == Double.NaN);
}

Design17
Synopsis Avoid using equals() to compare against null
Level 1

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 42/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Category Design
Status Checked
Inexperienced programmers sometimes confuse comparison concepts and use equals() to
compare to null.
class Bar {
void foo() {
String x = "foo";
if (x.equals(null)) { // bad!
doSomething();
}
}
}

Design18
Synopsis Avoid if (x != y) ..; else ..;
Level 4
Category Design
Status Checked
In an "if" expression with an "else" clause, avoid negation in the test. For example, rephrase: if (x
!= y) diff(); else same(); as: if (x == y) same(); else diff(); Most "if (x != y)" cases without an "else"
are often return cases, so consistent use of this rule makes the code easier to read. Also, this
resolves trivial ordering problems, such as "does the error case go first?" or "does the common
case go first?".
public class Foo {
boolean bar(int x, int y) {
return (x != y) ? diff : same;
}
}

Design19
Avoid instantiating an object just to call getClass() on it; use the .class public
Synopsis
member instead
Level 4
Category Design
Status Checked
Avoid instantiating an object just to call getClass() on it; use the .class public member instead.
public class Foo {
// Replace this
Class c = new String().getClass();
// with this:

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 43/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Class c = String.class;
}

Design20
Synopsis Avoid idempotent operations (like assigning a variable to itself)
Level 2
Category Design
Status Checked
Avoid idempotent operations - they are have no effect.
public class Foo {
public void bar() {
int x = 2;
x = x;
}
}

Design21
Synopsis When instantiating a SimpleDateFormat object, specify a Locale
Level 2
Category Design
Status Checked
Be sure to specify a Locale when creating a new instance of SimpleDateFormat.
public class Foo {
// Should specify Locale.US (or whatever)
private SimpleDateFormat sdf = new SimpleDateFormat("pattern");
}

Design22
Synopsis Declare private fields final, if possible
Level 3
Category Design
Status Checked
Identifies private fields whose values never change once they are initialized either in the
declaration of the field or by a constructor. This aids in converting existing classes to immutable
classes.
public class Foo {
private int x; // could be final
public Foo() {
x = 7;
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 44/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

public void foo() {


int a = x + 2;
}
}

Design23
Synopsis When doing a String.toLowerCase()/toUpperCase() call, use a Locale
Level 4
Category Design
Status Checked
When doing a String.toLowerCase()/toUpperCase() call, use a Locale. This avoids problems with
certain locales, i.e. Turkish.
class Foo {
// BAD
if (x.toLowerCase().equals("list"))...
/*
This will not match "LIST" when in Turkish locale
The above could be
if (x.toLowerCase(Locale.US).equals("list")) ...
or simply
if (x.equalsIgnoreCase("list")) ...
*/
// GOOD
String z = a.toLowerCase(Locale.EN);
}

Design24
Synopsis Avoid protected fields in a final class. Change to private or package access
Level 2
Category Design
Status Checked
Do not use protected fields in final classes since they cannot be subclassed. Clarify your intent
by using private or package access modifiers instead.
public final class Bar {
private int x;
protected int y; // <-- Bar cannot be subclassed, so is y really private or package
visible???
Bar() {}
}

Design25

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 45/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Synopsis Possible unsafe assignment to a non-final static field in a constructor


Level 1
Category Design
Status Checked
Identifies a possible unsafe usage of a static field.
public class StaticField {
static int x;
public StaticField(int y) {
x = y; // unsafe
}
}

Design26
Synopsis Class cannot be instantiated and does not provide any static methods or fields
Level 1
Category Design
Status Checked
A class that has private constructors and does not have any static methods or fields cannot be
used.
/* This class is unusable, since it cannot be
instantiated (private constructor),
and no static method can be called.
*/
public class Foo {
private Foo() {}
void foo() {}
}

Design27
Synopsis Use block level rather than method level synchronization
Level 3
Category Design
Status Checked
Method level synchronization can backfire when new code is added to the method. Block-level
synchronization helps to ensure that only the code that needs synchronization gets it.
public class Foo {
// Try to avoid this
synchronized void foo() {
}
// Prefer this:
void bar() {

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 46/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

synchronized(this) {
}
}
}

Design28
Synopsis A switch statement does not contain a break
Level 1
Category Design
Status Checked
A switch statement without an enclosed break statement may be a bug.
public class Foo {
public void bar(int status) {
switch(status) {
case CANCELLED:
doCancelled();
// break; hm, should this be commented out?
case NEW:
doNew();
case REMOVED:
doRemoved();
}
}
}

Design29
Synopsis Call Thread.notifyAll() rather than Thread.notify()
Level 1
Category Design
Status Checked
Thread.notify() awakens a thread monitoring the object. If more than one thread is monitoring,
then only one is chosen. The thread chosen is arbitrary; thus it's usually safer to call notifyAll()
instead.
public class Foo {
void bar() {
x.notify();
// If many threads are monitoring x, only one (and you won't know which) will be
notified.
// use instead:
x.notifyAll();
}
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 47/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Design30
An instanceof check is being performed on the caught exception. Create a
Synopsis
separate catch clause for this exception type
Level 3
Category Design
Status Checked
Each caught exception type should be handled in its own catch clause.
try { // Avoid this
// do something
} catch (Exception ee) {
if (ee instanceof IOException) {
cleanup();
}
}
try { // Prefer this:
// do something
} catch (IOException ee) {
cleanup();
}

Design32
Synopsis No need to check for null before an instanceof
Level 4
Category Design
Status Checked
No need to check for null before an instanceof; the instanceof keyword returns false when given
a null argument.
class Foo {
void bar(Object x) {
if (x != null && x instanceof Bar) {
// just drop the "x != null" check
}
}
}

Design35
Synopsis Consider simply returning values instead of storing it in a local variable
Level 3
Category Design
Status Checked

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 48/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Avoid unnecessarily creating local variables


public class Foo {
public int foo() {
int x = doSomething();
return x; // instead, just 'return doSomething();'
}
}

Design36
Synopsis Singleton is not thread safe
Level 1
Category Design
Status Checked
Non-thread safe singletons can result in bad state changes. Eliminate static singletons if possible
by instantiating the object directly. Static singletons are usually not needed as only a single
instance exists anyway. Other possible fixes are to synchronize the entire method or to use an
initialize-on-demand holder class (do not use the double-check idiom). See Effective Java, item
48.
private static Foo foo = null;

//multiple simultaneous callers may see partially initialized objects


public static Foo getFoo() {
if (foo==null)
foo = new Foo();
return foo;
}

Design39
An Interface should be used only to model a behaviour; consider converting this
Synopsis
to a class
Level 3
Category Design
Status Checked
An interface should be used only to model a behaviour of a class: using an interface as a
container of constants is a poor usage pattern. The static import feature should always be
considered as a replacement for this practice.
public interface ConstantsInterface {
public static final int CONSTANT1=0;
public static final String CONSTANT2="1";
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 49/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Design40
Synopsis Static java.text.Format objects should be accessed in a synchronized manner
Level 2
Category Design
Status Checked
Instances of java.text.Format are generally not synchronized. Sun recommends using separate
format instances for each thread. If multiple threads must access a static formatter, the formatter
must be synchronized either on method or block level.
public class Foo {
private static final SimpleDateFormat sdf = new SimpleDateFormat();
void bar() {
sdf.format(); // poor, no thread-safety
}
synchronized void foo() {
sdf.format(); // preferred
}
}

Design41
Synopsis Caught exception is rethrown, original stack trace may be lost
Level 2
Category Design
Status Checked
Throwing a new exception from a catch block without passing the original exception into the
new Exception will cause the true stack trace to be lost, and can make it difficult to debug
effectively.
public class Foo {
void good() {
try{
Integer.parseInt("a");
} catch(Exception e){
throw new Exception(e);
}
}
void bad() {
try{
Integer.parseInt("a");
} catch(Exception e){
throw new Exception(e.getMessage());
}
}
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 50/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Design42
Synopsis Substitute calls to size() == 0 (or size() != 0) with calls to isEmpty()
Level 4
Category Design
Status Checked
The isEmpty() method on java.util.Collection is provided to see if a collection has any elements.
Comparing the value of size() to 0 merely duplicates existing behavior.
public class Foo {
void good() {
List foo = getList();
if (foo.isEmpty()) {
// blah
}
}

void bad() {
List foo = getList();
if (foo.size() == 0) {
// blah
}
}
}
}

Design43
Synopsis Declare members privately
Level 3
Category Design
Status Checked
Class members should be declared privately to make sure data is not directly accessible from
outside the class.

class Design43 {
public string bar; // bad
protected string bar2; // bad too
private string bar3; // allowed
public final static int BAR = 0; // allowed
}

Design44
Synopsis Never initialize a final field to null

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 51/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Level 1
Category Design
Status Checked
Final fields can only be written to once. If a final field is initialized explicitly to null, it cannot be
used anymore for a proper reason. This is probably a mistake.
class Foo {
final Bar b = null;
}

Design45
Synopsis Avoid overloading the getInstance method
Level 3
Category Design
Status Checked
Some classes contain overloaded getInstance. The problem with overloaded getInstance
methods is that the instance created using the overloaded method is not cached and so, for
each call and new objects will be created for every invocation.

public class Singleton {

private static Singleton singleton = new Singleton( );

private Singleton(){ }

public static Singleton getInstance( ) {


return singleton;
}

public static Singleton getInstance(Object obj){


Singleton singleton = (Singleton) obj;
return singleton; //violation
}
}

Design100
Synopsis The scope of local variables should be kept to a minimum.
Level 6
Category Design
Status Checked
The scope of local variables should be kept to a minimum (Effective Java Item 29). By doing so,
you increase the readability and maintainability of your code and reduce the likelihood of error.

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 52/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Each variable should be declared in the innermost block that encloses all uses of the variable.

Design101
Synopsis Classes with only private constructors should be declared as final
Level 3
Category Design
Status Checked
Checks that a class which has only private constructors is declared as final. Doesn't check for
classes nested in interfaces or annotations, as they are always final there.
public class ClassWithPrivateConstructor { // violation
private ClassWithPrivateConstructor() {
}
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 53/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Finalizer
Finalizer1
Synopsis Avoid empty finalize methods
Level 3
Category Finalizer
Status Checked
If the finalize() method is empty, then it does not need to exist.
public class Foo {
protected void finalize() {}
}

Finalizer2
Synopsis Finalize should do something besides just calling super.finalize()
Level 3
Category Finalizer
Status Checked
If the finalize() is implemented, it should do something besides just calling super.finalize().
public class Foo {
protected void finalize() {
super.finalize();
}
}

Finalizer3
Synopsis Finalize methods should not be overloaded
Level 1
Category Finalizer
Status Checked
Methods named finalize() should not have parameters. It is confusing and probably a bug to
overload finalize(). It will not be called by the VM.
public class Foo {
// this is confusing and probably a bug
protected void finalize(int a) {
}
}

Finalizer4

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 54/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Synopsis Last statement in finalize method should be a call to super.finalize()


Level 1
Category Finalizer
Status Checked
If the finalize() is implemented, its last action should be to call super.finalize.
public class Foo {
protected void finalize() {
something();
// neglected to call super.finalize()
}
}

Finalizer5
Synopsis If you override finalize(), make it protected
Level 2
Category Finalizer
Status Checked
If you override finalize(), make it protected. If you make it public, other classes may call it.
public class Foo {
public void finalize() {
// do something
}
}

Finalizer6
Synopsis Avoid calling finalize() explicitly
Level 2
Category Finalizer
Status Checked
Object.finalize() is called by the garbage collector on an object when garbage collection
determines that there are no more references to the object.
public class Foo {
void foo() {
Bar b = new Bar();
b.finalize();
}
}

Finalizer100
Synopsis Don't use finalizers.

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 55/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Level 5
Category Finalizer
Status Checked
Finalizers are a way to have a chunk of code executed when an object is garbage collected.

Pros: can be handy for doing cleanup, particularly of external resources.

Cons: there are no guarantees as to when a finalizer will be called, or even that it will be called at
all.

Decision: we don't use finalizers. In most cases, you can do what you need from a finalizer with
good exception handling. If you absolutely need it, define a close() method (or the like) and
document exactly when that method needs to be called. See InputStream for an example. In this
case it is appropriate but not required to print a short log message from the finalizer, as long as
it is not expected to flood the logs.

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 56/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

ImportStatement
ImportStatement1
Synopsis Avoid duplicate imports
Level 3
Category ImportStatement
Status Checked
Avoid duplicate import statements.
import java.lang.String;
import java.lang.*;
public class Foo {}

ImportStatement2
Synopsis Avoid importing anything from the package 'java.lang'
Level 4
Category ImportStatement
Status Checked
Avoid importing anything from the package 'java.lang'. These classes are automatically imported
(JLS 7.5.3).
// this is bad
import java.lang.String;
public class Foo {}

// --- in another source code file...

// this is bad
import java.lang.*;

public class Foo {}

ImportStatement3
Synopsis Avoid unused imports
Level 4
Category ImportStatement
Status Checked
Avoid unused import statements.
// this is bad
import java.io.File;
public class Foo {}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 57/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

ImportStatement4
Synopsis No need to import a type that lives in the same package
Level 3
Category ImportStatement
Status Checked
No need to import a type that lives in the same package.
package foo;
import foo.Buz; // no need for this
import foo.*; // or this
public class Bar{}

ImportStatement100
Synopsis Fully qualify imports.
Level 5
Category ImportStatement
Status Checked
When you want to use class Bar from package foo,there are two possible ways to import it:

import foo.*;

Pros: Potentially reduces the number of import statements.

import foo.Bar;

Pros: Makes it obvious what classes are actually used. Makes code more readable for
maintainers.

Decision: Use the latter for importing all Android code. An explicit exception is made for java
standard libraries (java.util.*, java.io.*, etc.) and unit test code (junit.framework.*)

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 58/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

JavaLogging
JavaLogging1
Synopsis Class contains more than one logger.
Level 2
Category JavaLogging
Status Checked
Normally only one logger is used in each class.
class Foo{
Logger log = Logger.getLogger(Foo.class.getName());
// It is very rare to see two loggers on a class, normally
// log information is multiplexed by levels
Logger log2= Logger.getLogger(Foo.class.getName());
}

JavaLogging2
Synopsis The Logger variable declaration does not contain the static and final modifiers
Level 4
Category JavaLogging
Status Checked
In most cases, the Logger can be declared static and final.
class Foo{
Logger log = Logger.getLogger(Foo.class.getName());
// It is much better to declare the logger as follows
// static final Logger log = Logger.getLogger(Foo.class.getName());
}

JavaLogging3
Synopsis System.out.print is used
Level 4
Category JavaLogging
Status Checked
System.(out|err).print is used, consider using a logger.
class Foo{
Logger log = Logger.getLogger(Foo.class.getName());
public void testA () {
System.out.println("Entering test");
// Better use this
log.fine("Entering test");

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 59/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

}
}

JavaLogging4
Synopsis Avoid printStackTrace(); use a logger call instead.
Level 2
Category JavaLogging
Status Checked
Avoid printStackTrace(); use a logger call instead.
class Foo {
void bar() {
try {
// do something
} catch (Exception e) {
e.printStackTrace();
}
}
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 60/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Multithreading
Multithreading1
Synopsis Avoid storing MessageDigest in a field that can be accessed by multiple threads
Level 3
Category Multithreading
Status Checked
Declaring a MessageDigest instance as a field make this instance directly available to multiple
threads. Such sharing of MessageDigest instances should be avoided if possible since it leads to
wrong results if the access is not synchronized correctly. Just create a new instance and use it
locally, where you need it. Creating a new instance is easier than synchronizing access to a
shared instance.
import java.security.MessageDigest;
public class AvoidMessageDigestFieldExample {
private final MessageDigest sharedMd;
public AvoidMessageDigestFieldExample() throws Exception {
sharedMd = MessageDigest.getInstance("SHA-256");
}
public byte[] calculateHashShared(byte[] data) {
// sharing a MessageDigest like this without synchronizing access
// might lead to wrong results
sharedMd.reset();
sharedMd.update(data);
return sharedMd.digest();
}

// better
public byte[] calculateHash(byte[] data) throws Exception {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(data);
return md.digest();
}
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 61/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Naming
Naming2
Synopsis Avoid excessively long variable names
Level 6
Category Naming
Status Checked
Detects when a field, formal or local variable is declared with a long name.
public class Something {
int reallyLongIntName = -3; // VIOLATION - Field
public static void main( String argumentsList[] ) { // VIOLATION - Formal
int otherReallyLongName = -5; // VIOLATION - Local
for (int interestingIntIndex = 0; // VIOLATION - For
interestingIntIndex < 10;
interestingIntIndex ++ ) {
}
}

Naming3
Synopsis Avoid using short method names
Level 6
Category Naming
Status Checked
Detects when very short method names are used.
public class ShortMethod {
public void a( int i ) { // Violation
}
}

Naming8
Synopsis Avoid using dollar signs in variable/method/class/interface names
Level 4
Category Naming
Status Checked
Avoid using dollar signs in variable/method/class/interface names.
public class Fo$o { // yikes!
}

Naming10
https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 62/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Synopsis The method name and return type are suspiciously close to hashCode()
Level 3
Category Naming
Status Checked
The method name and return type are suspiciously close to hashCode(), which may mean you
are intending to override the hashCode() method.
public class Foo {
public int hashcode() {
// oops, this probably was supposed to be hashCode
}
}

Naming12
Synopsis The method name and parameter number are suspiciously close to equals(Object)
Level 2
Category Naming
Status Checked
The method name and parameter number are suspiciously close to equals(Object), which may
mean you are intending to override the equals(Object) method.
public class Foo {
public int equals(Object o) {
// oops, this probably was supposed to be boolean equals
}
public boolean equals(String s) {
// oops, this probably was supposed to be equals(Object)
}
}

Naming13
Synopsis It is somewhat confusing to have a field name matching the declaring class name
Level 5
Category Naming
Status Checked
It is somewhat confusing to have a field name matching the declaring class name. This probably
means that type and or field names could be more precise.
public class Foo extends Bar {
// There's probably a better name for foo
int foo;
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 63/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Naming14
Synopsis It is somewhat confusing to have a field name with the same name as a method
Level 4
Category Naming
Status Checked
It is somewhat confusing to have a field name with the same name as a method. While this is
totally legal, having information (field) and actions (method) is not clear naming.
public class Foo {
Object bar;
// bar is data or an action or both?
void bar() {
}
}

Naming15
Synopsis Don't define methods with the same name as the class name
Level 3
Category Naming
Status Checked
It is very easy to confuse methods with class name with constructors. It is preferrable to name
these non-constructor methods in a different way.
public class Foo {
public void Foo() {
// not a constructor, just a poorly named method
}
}

Naming16
Synopsis All classes and interfaces must belong to a named package
Level 3
Category Naming
Status Checked
Detects when a class or interface does not have a package definition.
// no package declaration
public class ClassInDefaultPackage {
}

Naming18
Synopsis Avoid naming non-fields with a member-like prefix

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 64/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Level 7
Category Naming
Status Checked
Detects when a non-field has a name starting with 'm_' or 'mX', where 'X' is any uppercase
character. This usually indicates a field and thus is confusing.
public class Foo {
private int m_foo; // OK
public void bar(String m_baz) { // Bad
int mBar = 42; // Bad
}
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 65/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Optimization
Optimization1
Synopsis Local variables assigned only once can be declared final
Level 4
Category Optimization
Status Checked
A local variable assigned only once can be declared final.
public class Bar {
public void foo () {
String a = "a"; //if a will not be assigned again it is better to do this:
final String b = "b";
}
}

Optimization7
Synopsis Use asList instead of tight loops
Level 3
Category Optimization
Status Checked
The class java.util.Arrays has a "asList" method that should be use when you want to create a
new List from an array of objects. It is faster than executing a loop to cpy all the elements of the
array one by one
public class Test {
public void foo(Integer[] ints) {
// could just use Arrays.asList(ints)
List l= new ArrayList(10);
for (int i=0; i< 100; i++) {
l.add(ints[i]);
}
for (int i=0; i< 100; i++) {
l.add(a[i].toString()); // won't trigger the rule
}
}
}

Optimization8
Synopsis System.arrayCopy is more efficient
Level 3
Category Optimization

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 66/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Status Checked
Instead of copying data between two arrays, use System.arrayCopy method.
public class Test {
public void bar() {
int[] a = new int[10];
int[] b = new int[10];

// this will trigger the rule


for (int i=0;i<10;i++) {
b[i]=a[i];
}
}
}

Optimization9
Synopsis Unnecessary wrapper object creation
Level 4
Category Optimization
Status Checked
Parsing method should be called directy instead.
public int convert(String s) {
int i, i2;

i = Integer.valueOf(s).intValue(); // this wastes an object


i = Integer.parseInt(s); // this is better

i2 = Integer.valueOf(i).intValue(); // this wastes an object


i2 = i; // this is better

return i2;
}

Optimization10
Synopsis Avoid using FileStream
Level 5
Category Optimization
Status Checked
The FileInputStream and FileOutputStream classes contains a finalizer method which will cause
garbage collection pauses. The FileReader and FileWriter constructors instantiate
FileInputStream and FileOutputStream, again causing garbage collection issues while finalizer
methods are called.

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 67/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Use Files.newInputStream(Paths.get(fileName)) instead of new


FileInputStream(fileName).
Use Files.newOutputStream(Paths.get(fileName)) instead of new
FileOutputStream(fileName).
Use Files.newBufferedReader(Paths.get(fileName)) instead of new FileReader(fileName).
Use Files.newBufferedWriter(Paths.get(fileName)) instead of new FileWriter(fileName).

Optimization11
Synopsis Avoid double brace initialization
Level 5
Category Optimization
Status Checked
Double brace initialization is a pattern to initialize objects, such as collections, concisely.
However, it implicitly generates a new .class file, and the object holds a strong reference to the
enclosing object. For those reasons, it is preferable to initialize the object normally, even though
it’s verbose.
Set<String> countries = new HashSet<String>() { // violation
{
add("India");
add("USSR");
add("USA");
}
};

Optimization12
Synopsis Avoid creating Calendar objects
Level 6
Category Optimization
Status Checked
A Calendar is a heavyweight object and expensive to create. Use new Date(),
java.time.LocalDateTime.now() or ZonedDateTime.now() instead.
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;

public class DateStuff {


private Date bad1() {
return Calendar.getInstance().getTime(); // now
}
private Date good1a() {
return new Date(); // now

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 68/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

}
private LocalDateTime good1b() {
return LocalDateTime.now();
}
private long bad2() {
return Calendar.getInstance().getTimeInMillis();
}
private long good2() {
return System.currentTimeMillis();
}
}

Optimization100
Synopsis Declare JAXBcontext variables as static.
Level 3
Category Optimization
Status Checked
In order to minimize PermGen memory usage, it is best to declare variables of type JAXBcontext
as static. For example:

class MyServlet extends HttpServlet {


static final JAXBContext context = initContext();

private static JAXBContext initContext() {


return JAXBContext.newInstance(Foo.class,Bar.class);
}
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 69/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

SecurityCodeGuidelines
Security1
Synopsis Do not use hard coded values for cryptographic operations
Level 3
Category SecurityCodeGuidelines
Status Checked
Do not use hard coded values for cryptographic operations. Please store keys outside of source
code.

public class Foo {


void good() {
SecretKeySpec secretKeySpec = new SecretKeySpec(Properties.getKey(), "AES");
}

void bad() {
SecretKeySpec secretKeySpec = new SecretKeySpec("my secret here".getBytes(),
"AES");
}
}

Security2
Synopsis Do not use hard coded initialization vector in cryptographic operations
Level 3
Category SecurityCodeGuidelines
Status Checked
Do not use hard coded initialization vector in cryptographic operations. Please use a randomly
generated IV.

public class Foo {


void good() {
SecureRandom random = new SecureRandom();
byte iv[] = new byte[16];
random.nextBytes(bytes);
}

void bad() {
byte[] iv = new byte[] { 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00, 00,
00, 00, 00, };
}

void alsoBad() {

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 70/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

byte[] iv = "secret iv in here".getBytes();


}
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 71/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

StrictException
StrictException1
Synopsis A catch statement should never catch throwable since it includes errors
Level 1
Category StrictException
Status Checked
This is dangerous because it casts too wide a net; it can catch things like OutOfMemoryError.
public class Foo {
public void bar() {
try {
// do something
} catch (Throwable th) { //Should not catch throwable
th.printStackTrace();
}
}
}

StrictException2
Synopsis A method/constructor shouldn't explicitly throw java.lang.Exception
Level 3
Category StrictException
Status Checked
It is unclear which exceptions that can be thrown from the methods. It might be difficult to
document and understand the vague interfaces. Use either a class derived from
RuntimeException or a checked exception.
public void methodThrowingException() throws Exception {
}

StrictException3
Synopsis Avoid using exceptions as flow control
Level 2
Category StrictException
Status Checked
Using Exceptions as flow control leads to GOTOish code and obscures true exceptions when
debugging.
public class Foo {
void bar() {
try {

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 72/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

try {
} catch (Exception e) {
throw new WrapperException(e);
// this is essentially a GOTO to the WrapperException catch block
}
} catch (WrapperException e) {
// do some more stuff
}
}
}

StrictException4
Synopsis Avoid catching NullPointerException; consider removing the cause of the NPE
Level 1
Category StrictException
Status Checked
Code should never throw NPE under normal circumstances. A catch block may hide the original
error, causing other more subtle errors in its wake.
public class Foo {
void bar() {
try {
// do something
} catch (NullPointerException npe) {
}
}
}

StrictException5
Synopsis Avoid throwing raw exception types
Level 3
Category StrictException
Status Checked
Avoid throwing certain exception types. Rather than throw a raw RuntimeException, Throwable,
Exception, or Error, use a subclassed exception or error instead or use an assert.
public class Foo {
public void bar() throws Exception {
throw new Exception();
}
}

StrictException6

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 73/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Synopsis Avoid throwing null pointer exceptions


Level 2
Category StrictException
Status Checked
Avoid throwing a NullPointerException - it's confusing because most people will assume that the
virtual machine threw it. Consider using an IllegalArgumentException instead; this will be clearly
seen as a programmer-initiated exception.
public class Foo {
void bar() {
throw new NullPointerException();
}
}

StrictException7
Synopsis A catch statement that catches an exception only to rethrow it should be avoided
Level 3
Category StrictException
Status Checked
Catch blocks that merely rethrow a caught exception only add to code size and runtime
complexity.
public class Foo {
void bar() {
try {
// do something
} catch (SomeException se) {
throw se;
}
}
}

StrictException8
Synopsis Use the try-with-resources statement to ensure resources are closed
Level 4
Category StrictException
Status Unchecked
Java 7 introduced the try-with-resources statement. This statement ensures that each resource is
closed at the end of the statement. It avoids the need of explicitly closing the resources in a
finally block. Additionally exceptions are better handled: If an exception occurred both in the try
block and finally block, then the exception from the try block was suppressed. With the try-with-
resources statement, the exception thrown from the try-block is preserved.

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 74/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

public class TryWithResources {


public void run() {
InputStream in = null;
try {
in = openInputStream();
int i = in.read();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) in.close();
} catch (IOException ignored) {
// ignored
}
}

// better use try-with-resources


try (InputStream in2 = openInputStream()) {
int i = in2.read();
}
}
}

StrictException100
Synopsis Don't ignore exceptions.
Level 1
Category StrictException
Status Checked
Sometimes it is tempting to write code that completely ignores an exception like this:

void setServerPort(String value) {


try {
serverPort = Integer.parseInt(value);
} catch (NumberFormatException e) { }
}

You must never do this. While you may think that your code will never encounter this error
condition or that it is not important to handle it, ignoring exceptions like above creates mines in
your code for someone else to trip over some day. You must handle every Exception in your
code in some principled way. The specific handling varies depending on the case.

Anytime somebody has an empty catch clause they should have a creepy feeling. There are
definitely times when it is actually the correct thing to do, but at least you have to think about it. In
Java you can't escape the creepy feeling. -James Gosling

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 75/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Acceptable alternatives (in order of preference) are:

Throw the exception up to the caller of your method.

void setServerPort(String value) throws NumberFormatException {


serverPort = Integer.parseInt(value);
}

Throw a new exception that's appropriate to your level of abstraction.

void setServerPort(String value) throws ConfigurationException {


try {
serverPort = Integer.parseInt(value);
} catch (NumberFormatException e) {
throw new ConfigurationException("Port " + value + " is not valid.");
}
}

Handle the error gracefully and substitute an appropriate value in the catch {} block.

/** Set port. If value is not a valid number, 80 is substituted. */

void setServerPort(String value) {


try {
serverPort = Integer.parseInt(value);
} catch (NumberFormatException e) {
serverPort = 80; // default port for server
}
}

Catch the Exception and throw a new RuntimeException. This is dangerous: only do it if you
are positive that if this error occurs, the appropriate thing to do is crash.

/** Set port. If value is not a valid number, die. */

void setServerPort(String value) {


try {
serverPort = Integer.parseInt(value);
} catch (NumberFormatException e) {
throw new RuntimeException("port " + value " is invalid, ", e);
}
}

Note that the original exception is passed to the constructor for RuntimeException. If your
code must compile under Java 1.3, you will need to omit the exception that is the cause.

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 76/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Last resort: if you are confident that actually ignoring the exception is appropriate then you
may ignore it, but you must also comment why with a good reason:

/** If value is not a valid number, original port number is used. */


void setServerPort(String value) {
try {
serverPort = Integer.parseInt(value);
} catch (NumberFormatException e) {
// Method is documented to just ignore invalid user input.
// serverPort will just be unchanged.
}
}

StrictException101
Synopsis Don't catch generic exceptions.
Level 2
Category StrictException
Status Checked
Sometimes it is tempting to be lazy when catching exceptions and do something like this:

try {
someComplicatedIOFunction(); // may throw IOException
someComplicatedParsingFunction(); // may throw ParsingException
someComplicatedSecurityFunction(); // may throw SecurityException
// phew, made it all the way
} catch (Exception e) { // I'll just catch all exceptions
handleError(); // with one generic handler!
}

You should not do this. In almost all cases it is inappropriate to catch generic Exception or
Throwable, preferably not Throwable, because it includes Error exceptions as well. It is very
dangerous. It means that Exceptions you never expected (including RuntimeExceptions like
ClassCastException) end up getting caught in application-level error handling. It obscures the
failure handling properties of your code. It means if someone adds a new type of Exception in
the code you're calling, the compiler won't help you realize you need to handle that error
differently. And in most cases you shouldn't be handling different types of exception the same
way, anyway.

There are rare exceptions to this rule: certain test code and top-level code where you want to
catch all kinds of errors (to prevent them from showing up in a UI, or to keep a batch job
running). In that case you may catch generic Exception (or Throwable) and handle the error
appropriately. You should think very carefully before doing this, though, and put in comments
explaining why it is safe in this place.

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 77/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Alternatives to catching generic Exception:

Catch each exception separately as separate catch blocks after a single try. This can be
awkward but is still preferable to catching all Exceptions. Beware repeating too much code
in the catch blocks.
Refactor your code to have more fine-grained error handling, with multiple try blocks. Split
up the IO from the parsing, handle errors separately in each case.
Rethrow the exception. Many times you don't need to catch the exception at this level
anyway, just let the method throw it.

Remember: exceptions are your friend! When the compiler complains you're not catching an
exception, don't scowl. Smile: the compiler just made it easier for you to catch runtime problems
in your code.

StrictException102
Synopsis Exception classes should only contain final fields
Level 3
Category StrictException
Status Checked
Exception classes should be immutable, that is, they should only have final fields. This is because
Exception instances should represent an error condition. Having non final fields not only allows
the state to be modified by accident and therefore mask the original condition but also allows
developers to accidentally forget to set the initial state. In both cases, code catching the
exception could draw incorrect conclusions based on the state.
public class MyException {
int nonFinalMember; // violation
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 78/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

StringandStringBuffer
StringandStringBuffer1
Synopsis Don't use duplicate String literals; use constants instead
Level 3
Category StringandStringBuffer
Status Checked
Code containing duplicate String literals can usually be improved by declaring the String as a
constant field.
public class Foo {
private void bar() {
buz("Howdy");
buz("Howdy");
buz("Howdy");
buz("Howdy");
}
private void buz(String x) {}
}

StringandStringBuffer2
Synopsis Avoid instantiating String objects; this is usually unnecessary
Level 2
Category StringandStringBuffer
Status Checked
Avoid instantiating String objects; this is usually unnecessary.
public class Foo {
private String bar = new String("bar"); // just do a String bar = "bar";
}

StringandStringBuffer3
Synopsis Avoid calling toString() on String objects; this is unnecessary
Level 3
Category StringandStringBuffer
Status Checked
Avoid calling toString() on String objects; this is unnecessary.
public class Foo {
private String baz() {
String bar = "howdy";
return bar.toString();

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 79/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

}
}

StringandStringBuffer4
Synopsis Avoid concatenating nonliterals in a StringBuffer constructor or append()
Level 3
Category StringandStringBuffer
Status Checked
Avoid concatenating non literals in a StringBuffer constructor or append().
public class Foo {
void bar() {
// Avoid this
StringBuffer sb=new StringBuffer("tmp = "+System.getProperty("java.io.tmpdir"));
// use instead something like this
StringBuffer sb = new StringBuffer("tmp = ");
sb.append(System.getProperty("java.io.tmpdir"));
}
}

StringandStringBuffer5
Using equalsIgnoreCase() is cleaner than using
Synopsis
toUpperCase/toLowerCase().equals()
Level 4
Category StringandStringBuffer
Status Checked
Using equalsIgnoreCase() is faster than using toUpperCase/toLowerCase().equals()
public class Foo {
public boolean bar(String buz) {
// should be buz.equalsIgnoreCase("baz")
return buz.toUpperCase().equals("baz");
// another unnecessary toUpperCase()
// return buz.toUpperCase().equalsIgnoreCase("baz");
}
}

StringandStringBuffer6
Synopsis This is an inefficient use of StringBuffer.toString; call StringBuffer.length instead
Level 6
Category StringandStringBuffer
Status Checked

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 80/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Use StringBuffer.length() to determine StringBuffer length rather than using


StringBuffer.toString().equals("") or StringBuffer.toString().length() ==.
public class Foo {
void bar() {
StringBuffer sb = new StringBuffer();
// this is bad
if(sb.toString().equals("")) {}
// this is good
if(sb.length() == 0) {}
}
}

StringandStringBuffer7
Synopsis Avoid appending characters as strings in StringBuffer.append
Level 5
Category StringandStringBuffer
Status Checked
Avoid concatenating characters as strings in StringBuffer.append.
public class Foo {
void bar() {
StringBuffer sb=new StringBuffer();
// Avoid this
sb.append("a");

// use instead something like this


StringBuffer sb=new StringBuffer();
sb.append('a');
}
}

StringandStringBuffer8
Synopsis Combine StringBuffer.append calls, if possible
Level 4
Category StringandStringBuffer
Status Checked
Consecutively calling StringBuffer.append with String literals
public class Foo {
private void bar() {
StringBuffer buf = new StringBuffer();
buf.append("Hello").append(" ").append("World"); //bad
buf.append("Hello World");//good

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 81/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

}
}

StringandStringBuffer9
Synopsis String.indexOf(char) is faster than String.indexOf(String)
Level 4
Category StringandStringBuffer
Status Checked
Use String.indexOf(char) when checking for the index of a single character; it executes faster.
public class Foo {
void bar() {
String s = "hello world";
// avoid this
if (s.indexOf("d") {}
// instead do this
if (s.indexOf('d') {}
}
}

StringandStringBuffer10
Synopsis String.trim().length()==0 is an inefficient way to validate an empty String
Level 4
Category StringandStringBuffer
Status Checked
String.trim().length() is an inefficient way to check if a String is really empty, as it creates a new
String object just to check its size. Consider creating a static function that loops through a string,
checking Character.isWhitespace() on each character and returning false if a non-whitespace
character is found.
public class Foo {
void bar(String string) {
if (string != null && string.trim().size() > 0) {
doSomething();
}
}
}

StringandStringBuffer11
Synopsis Initialize objects of StringBuffer with a proper size
Level 8
Category StringandStringBuffer

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 82/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Status Checked
Failing to pre-size a StringBuffer properly could cause it to re-size many times during runtime.
This rule checks the characters that are actually passed into StringBuffer.append(), but represents
a best guess "worst case" scenario. An empty StringBuffer constructor initializes the object to 16
characters. This default is assumed if the length of the constructor can not be determined.
public class Foo {
void bar() {
StringBuffer bad = new StringBuffer();
bad.append("This is a long string, will exceed the default 16
characters");//bad
StringBuffer good = new StringBuffer(41);
good.append("This is a long string, which is pre-sized");//good
}
}

StringandStringBuffer12
Synopsis No need to call String.valueOf to append to a string
Level 3
Category StringandStringBuffer
Status Checked
No need to call String.valueOf to append to a string; just use the valueOf() argument directly.
public String convert(int i) {
String s;
s = "a" + String.valueOf(i); // Bad
s = "a" + i; // Better
return s;
}

StringandStringBuffer13
Synopsis Do not instantiate a StringBuffer with a char
Level 2
Category StringandStringBuffer
Status Checked
StringBuffer sb = new StringBuffer('c'); The char will be converted into int to intialize StringBuffer
size.
class Foo {
StringBuffer sb1 = new StringBuffer('c'); //Bad
StringBuffer sb2 = new StringBuffer("c"); //Better
}

StringandStringBuffer14
https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 83/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Synopsis Use equals() to compare String objects


Level 1
Category StringandStringBuffer
Status Checked
Use equals() to compare object references; avoid comparing them with ==. This is because
equals() compares object values and == only object references. So if the contents of 2 different
string objects is equal (say, both have value "hello"), == returns false.
class Foo {
boolean bar(String a, String b) {
return a == b; // might unexpectedly return false
}
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 84/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Style
Comments102
Synopsis Use one annotation per line.
Level 8
Category Style
Status Checked

Style100
Synopsis Don't use tabs.
Level 7
Category Style
Status Checked

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 85/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

TypeResolution
TypeResolution1
Synopsis Avoid using implementation types; use the interface instead
Level 3
Category TypeResolution
Status Checked
Avoid using implementation types (i.e., HashSet); use the interface (i.e, Set) instead
import java.util.ArrayList;
import java.util.HashSet;
public class Bar {
// Use List instead
private ArrayList list = new ArrayList();
// Use Set instead
public HashSet getFoo() {
return new HashSet();
}
}

TypeResolution3
Synopsis Use the diamond operator to let the type be inferred automatically
Level 6
Category TypeResolution
Status Checked
Use the diamond operator to let the type be inferred automatically. With the Diamond operator
it is possible to avoid duplication of the type parameters. Instead, the compiler is now able to
infer the parameter types for constructor calls, which makes the code also more readable.
List<String> strings = new ArrayList<String>(); // unnecessary duplication of type
parameters

TypeResolution4
Synopsis Use short array initializers without repeated type information
Level 6
Category TypeResolution
Status Unchecked
When declaring and initializing array fields or variables, it is not necessary to explicitly create a
new array using new. Instead one can simply define the initial content of the array as a
expression in curly braces.

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 86/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

int[] x = new int[] { 1, 2, 3 }; // overly verbose


int[] x = { 1, 2, 3 }; // equivalent to the previous line

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 87/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

UnusedCode
UnusedCode1
Synopsis Avoid unused private fields
Level 4
Category UnusedCode
Status Checked
Detects when a private field is declared and/or assigned a value, but not used.
public class Something {
private static int FOO = 2; // Unused
private int i = 5; // Unused
private int j = 6;
public int addOne() {
return j++;
}
}

UnusedCode2
Synopsis Avoid unused local variables
Level 4
Category UnusedCode
Status Checked
Detects when a local variable is declared and/or assigned, but not used.
public class Foo {
public void doSomething() {
int i = 5; // Unused
}
}

UnusedCode3
Synopsis Avoid unused private methods
Level 3
Category UnusedCode
Status Checked
Unused Private Method detects when a private method is declared but is unused.
public class Something {
private void foo() {} // unused
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 88/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

UnusedCode5
Synopsis Avoid unused assignments
Level 5
Category UnusedCode
Status Checked
Avoid assignments to variables that are never used before the variable is overwritten, or goes
out of scope. Unused assignments are those for which the variable is never read after the
assignment, or the assigned value is always overwritten by other assignments before the next
read of the variable.
class A {
// this field initializer is redundant,
// it is always overwritten in the constructor
int f = 1;

A(int f) {
this.f = f;
}
}

class B {
int method(int i, int j) {
// this initializer is redundant,
// it is overwritten in all branches of the `if`
int k = 0;

// Both the assignments to k are unused, because k is


// not read after the if/else
// This may hide a bug: the programmer probably wanted to return k
if (i < j)
k = i;
else
k = j;

return j;
}
}

class C {
int method() {
int i = 0;

checkSomething(++i); // variable i isn't use anymore after this


}
}

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 89/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

UnusedCode100
Synopsis Empty statements (standalone ';' semicolons) are not allowed
Level 3
Category UnusedCode
Status Checked
Empty statements do not serve any purpose, so they should be removed.
int i = 3;; // unused second semicolon
; // unused semicolon

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 90/91
2024/11/27 下午6:58 TIOBE Java Coding Standard

Literature

https://csviewer.tiobe.com/#/ruleset/rules?status=CHECKED,UNCHECKED&tagid=SGPpf5wUT7aQ5_77VZfL3A&setid=ft2gO5oDRluwlZr2quu… 91/91

You might also like