rspec/rules/S3673/java/rule.adoc
Fred Tingaud 16f6c0aecf
Inline adoc when include has no additional value (#1940)
Inline adoc files when they are included exactly once.

Also fix language tags because this inlining gives us better information
on what language the code is written in.
2023-05-25 14:18:12 +02:00

58 lines
2.0 KiB
Plaintext

== Why is this an issue?
Calling ``++Class.newInstance++`` invokes the class' default constructor. Unfortunately, since it's not a direct call to the constructor, compile-time checking will be unable to detect the possibility. This means that your code will compile even if you haven't put the invocation in a ``++try++`` block.
On the other hand, ``++Construtor.newInstance++`` handles exceptions by wrapping them in an ``++InvocationTargetException++`` and explicitly throwing them.
This rule raises an issue when ``++Class.newInstance++`` is used to invoke a constructor that throws checked exceptions.
=== Noncompliant code example
[source,java]
----
Foo f = Foo.class.newInstance(); // Noncompliant
----
=== Compliant solution
[source,java]
----
Foo f = Foo.class.getConstructor().newInstance();
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
* Use "xxx.getConstructor().newInstance()" instead.
=== Highlighting
``++xxx.newInstance()++``
'''
== Comments And Links
(visible only on this page)
=== on 14 Jul 2016, 18:01:06 Ann Campbell wrote:
https://github.com/google/error-prone/blob/master/docs/bugpattern/ClassNewInstance.md
=== on 15 Jul 2016, 09:38:16 Freddy Mallet wrote:
Hi [~ann.campbell.2], I would convert this "Code Smells Detection Rule" into a "Bugs Detection Rule" by making it raising an issue : IF AND ONLY IF the "class.newInstance()" leads to call a constructor having some checked exceptions. This is another example of the following pattern : instead of enforcing a coding practice allowing to avoid facing some bugs from time to time, let's provide a rule able to precisely detect those bugs.
=== on 15 Jul 2016, 14:40:14 Freddy Mallet wrote:
And in that case [~ann.campbell.2], the title and description of the rule should also evolve. For the title, that might become: "'Class.newIntance(...)' should be not be called when the relating nullary constructor throws checked exceptions".
endif::env-github,rspecator-view[]