rspec/rules/S3306/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

67 lines
1.8 KiB
Plaintext

== Why is this an issue?
Field injection seems like a tidy way to get your classes what they need to do their jobs, but it's really a ``++NullPointerException++`` waiting to happen unless all your class constructors are ``++private++``. That's because any class instances that are constructed by callers, rather than instantiated by a Dependency Injection framework compliant with the JSR-330 (Spring, Guice, ...), won't have the ability to perform the field injection.
Instead ``++@Inject++`` should be moved to the constructor and the fields required as constructor parameters.
This rule raises an issue when classes with non-``++private++`` constructors (including the default constructor) use field injection.
=== Noncompliant code example
[source,java]
----
class MyComponent { // Anyone can call the default constructor
@Inject MyCollaborator collaborator; // Noncompliant
public void myBusinessMethod() {
collaborator.doSomething(); // this will fail in classes new-ed by a caller
}
}
----
=== Compliant solution
[source,java]
----
class MyComponent {
private final MyCollaborator collaborator;
@Inject
public MyComponent(MyCollaborator collaborator) {
Assert.notNull(collaborator, "MyCollaborator must not be null!");
this.collaborator = collaborator;
}
public void myBusinessMethod() {
collaborator.doSomething();
}
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Use constructor injection for this field.
'''
== Comments And Links
(visible only on this page)
=== on 14 Oct 2016, 13:31:17 Freddy Mallet wrote:
As decided with the Java team, let's remove this rule from the default "Sonar way" quality profile. See SONARJAVA-1880.
endif::env-github,rspecator-view[]