rspec/rules/S1220/java/rule.adoc

71 lines
2.5 KiB
Plaintext

== Why is this an issue?
Java packages serve two purposes:
1. Structure -- Packages give a structure to the set of classes of your project.
It is a bad practice to put all classes flat into the source directory of a project without a package structure.
A structure helps to mentally break down a project into smaller parts,
simplifying readers' understanding of how components are connected and how they interact.
2. Avoiding name clashes -- a class part of the _default package_ if no explicit package name is specified.
This can easily cause name collisions when other projects define a class of the same name.
When no package is explicitly specified for the classes in your project,
this makes the project harder to understand and may cause name collisions with other projects.
Also, classes located in the default package not be accessed from classes within named packages since Java 1.4.
== How to fix it
Move your class to a package directory and explicitly state the package's name at the top of the class.
If your project does not have a package structure, think of a structure that fits your needs.
The package names should be unique to your project.
You can find some best practices when choosing package names in the Ressources section below.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
public class MyClass { /* ... */ } // Noncompliant, no package spacified
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
package org.example; // Compliant
public class MyClass{ /* ... */ }
----
== Resources
=== Articles & blog posts
- https://www.baeldung.com/java-packages[Baeldung - Guide to Java Packages]
- https://www.tutorialspoint.com/what-are-the-best-practices-to-keep-in-mind-while-using-packages-in-java#:~:text=Naming%20conventions%20and%20best%20practices%20for%20packages[tutorialspoint - What are the best practices to keep in mind while using packages in Java?]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Move this file to a named package.
'''
== Comments And Links
(visible only on this page)
=== on 20 Aug 2013, 20:09:41 Freddy Mallet wrote:
Is implemented by \http://jira.codehaus.org/browse/SONARJAVA-310
=== on 16 Nov 2015, 11:40:10 Michael Gumowski wrote:
I removed reference to PMD rule "DefaultPackage", which is not describing the same case (forbid usage of package visibility for members, see RSPEC-1784 and RSPEC-2072)
endif::env-github,rspecator-view[]