rspec/rules/S2112/java/rule.adoc

74 lines
2.1 KiB
Plaintext

== Why is this an issue?
The `equals` and `hashCode` methods of `java.net.URL` may trigger a name service lookup (typically DNS) to resolve the hostname or IP
address. Depending on the configuration, and network status, this lookup can be time-consuming.
On the other hand, the `URI` class does not perform such lookups and is a better choice unless you specifically require the functionality
provided by `URL`.
In general, it is better to use the `URI` class until access to the resource is actually needed, at which point you can convert the `URI` to
a `URL` using `URI.toURL()`.
This rule checks for uses of `URL` 's in `Map` and `Set` , and for explicit calls to the `equals` and `hashCode` methods.
It suggests reconsidering the use of `URL` in such scenarios to avoid potential performance issues related to name service lookups.
== How to fix it
Use the `URI` class until access to the resource is actually needed.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
public void checkUrl(URL url) {
Set<URL> sites = new HashSet<URL>(); // Noncompliant
URL homepage = new URL("http://sonarsource.com"); // Compliant
if (homepage.equals(url)) { // Noncompliant
// ...
}
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
public void checkUrl(URL url) {
Set<URI> sites = new HashSet<URI>(); // Compliant
URI homepage = new URI("http://sonarsource.com"); // Compliant
URI uri = url.toURI();
if (homepage.equals(uri)) { // Compliant
// ...
}
}
----
== Resources
* https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/net/URL.html[Oracle Java SE - java.net.URL]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Use the URI class instead.
'''
== Comments And Links
(visible only on this page)
=== on 8 Oct 2014, 07:17:12 Nicolas Peru wrote:
\[~freddy.mallet] This one will probably require to have Generics in the symbol table.
endif::env-github,rspecator-view[]