rspec/rules/S4719/java/rule.adoc

54 lines
1.2 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
JDK7 introduced the class ``++java.nio.charset.StandardCharsets++``. It provides constants for all charsets that are guaranteed to be available on every implementation of the Java platform.
* ISO_8859_1
* US_ASCII
* UTF_16
* UTF_16BE
* UTF_16LE
* UTF_8
These constants should be preferred to:
* the use of a String such as "UTF-8" which has the drawback of requiring the ``++catch++``/``++throw++`` of an ``++UnsupportedEncodingException++`` that will never actually happen
* the use of Guavas ``++Charsets++`` class, which has been obsolete since JDK7
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
try {
byte[] bytes = string.getBytes("UTF-8"); // Noncompliant; use a String instead of StandardCharsets.UTF_8
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
// ...
byte[] bytes = string.getBytes(Charsets.UTF_8); // Noncompliant; Guava way obsolete since JDK7
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
byte[] bytes = string.getBytes(StandardCharsets.UTF_8)
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]