Audit - Rules - Pattern UsageDescriptionThis group contains audit rules that check your code for constructs that violate specific coding patterns. |
Rules: |
Summary
Flag classes that appear to follow the Singleton pattern but have a non-private constructor.
Description
Ensure that a class defined as a singleton follows specific rules that disallow multiple instances to be created. Singleton classes should have a single, private constructor and static access to the instance.
Summary
A visit and endVisit methods should only be invoked by the object being visited.
Description
This audit rule looks for places where a visit
or endVisit
method is being invoked by an object other than the one being visited. Such invocations indicate that the visitor pattern is being used incorrectly. Clients should not invoke the visit
and endVisit
methods directly, but should ask the object to be visited to accept the visitor.
Example
The following invocation of the visit
method would be flagged as a violation because the argument to the invocation is not this
:
visitor.visit(someObject);
Summary
Singleton objects should be initialized as late as possible.
Description
This audit rule looks for singleton classes in which the singleton object is initialized earlier than necessary.
Example
The following static field declaration would be flagged because the field is initialized in the declaration rather than in the getInstance() method:
private static MySingleton UniqueInstance = new MySingleton();
public static MySingleton getInstance()
{
return UniqueInstance;
}
Summary
Static fields should be initialized in a thread safe way.
Description
Static fields are typically initialized either as part of their declaration, in a static initializer, or lazily in a static method. The first two ways are thread safe because of the way the JVM initializes classes. In order for the initialization of a lazily initialized field (such as the unique instance of a Singleton class) to be thread safe, either the method must be synchronized or the body of the method must be inside a synchronize statement. If not, and if the method is called by multiple threads, one of the threads might get a reference to the field before it is fully initialized or it might be initialized multiple times. This audit rule looks for places where a static field is initialized in a way that is not thread safe.
Example
The following singleton is not thread-safe, and would be marked as a violation.
public class MySingleton {
public MySingleton instance = null;
public MySingleton getInstance() {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}
private MySingleton() {}
}