Add a private constructor to hide the implicit public one. Open
public class FileUtils {
- Read upRead up
- Exclude checks
Utility classes, which are collections of static
members, are not meant to be instantiated. Even abstract utility classes, which can
be extended, should not have public constructors.
Java adds an implicit public constructor to every class which does not define at least one explicitly. Hence, at least one non-public constructor should be defined.
Noncompliant Code Example
class StringUtils { // Noncompliant public static String concatenate(String s1, String s2) { return s1 + s2; } }
Compliant Solution
class StringUtils { // Compliant private StringUtils() { throw new IllegalStateException("Utility class"); } public static String concatenate(String s1, String s2) { return s1 + s2; } }
Exceptions
When class contains public static void main(String[] args)
method it is not considered as utility class and will be ignored by this
rule.
Use "java.nio.file.Files#delete" here for better messages on error conditions. Open
file.delete();
- Read upRead up
- Exclude checks
When java.io.File#delete
fails, this boolean
method simply returns false
with no indication of the cause. On
the other hand, when java.nio.file.Files#delete
fails, this void
method returns one of a series of exception types to better
indicate the cause of the failure. And since more information is generally better in a debugging situation, java.nio.file.Files#delete
is
the preferred option.
Noncompliant Code Example
public void cleanUp(Path path) { File file = new File(path); if (!file.delete()) { // Noncompliant //... } }
Compliant Solution
public void cleanUp(Path path) throws NoSuchFileException, DirectoryNotEmptyException, IOException { Files.delete(path); }
Using the '.*' form of import should be avoided - java.io.*. Open
import java.io.*;
- Read upRead up
- Exclude checks
Checks that there are no import statements that use the *
notation.
Rationale: Importing all classes from a package or staticmembers from a class leads to tight coupling between packagesor classes and might lead to problems when a new version of alibrary introduces name clashes.
This documentation is written and maintained by the Checkstyle community and is covered under the same license as the Checkstyle project.