rspec/rules/S4087/java/rule.adoc

47 lines
1.0 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
Java 7's try-with-resources structure automatically handles closing the resources that the ``++try++`` itself opens. Thus, adding an explicit ``++close()++`` call is redundant and potentially confusing.
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
try (PrintWriter writer = new PrintWriter(process.getOutputStream())) {
String contents = file.contents();
writer.write(new Gson().toJson(new MyObject(contents)));
writer.flush();
writer.close(); // Noncompliant
}
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
try (PrintWriter writer = new PrintWriter(process.getOutputStream())) {
String contents = file.contents();
writer.write(new Gson().toJson(new MyObject(contents)));
writer.flush();
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Remove this "close" call; closing the resource is handled automatically by the try-with-resources.
=== Highlighting
``++close()++``
endif::env-github,rspecator-view[]