rspec/rules/S2107/java/rule.adoc
Fred Tingaud 6f24cc0632
Clean rule at root
In some cases, the `rule.adoc` at root of a rule is never included
anywhere and thus is dead code.
It's a maintenance cost by itself, but also it misses opportunities to
inline code that seems used by two documents when in fact only one
document is actually rendered. And this missed opportunity, in turn,
stops us from applying the correct language tag on the code samples.
2023-10-16 16:34:38 +02:00

88 lines
2.0 KiB
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

*This rule was deprecated for Java before it was implemented.*
> in Java the members are initialized to default values (i.e. zero and null), so the rule doesnt bring much value.
https://discuss.sonarsource.com/t/is-the-rule-s2107-implemented-planned-duplicate-for-java/15217/2[discuss post]
== Why is this an issue?
Class members that are not assigned a default value and are not initialized in a constructor will be set to null by the compiler. Even if code exists to properly set those members, there is a risk that they will be dereferenced before it is called, resulting in a ``++NullPointerException++``.
Because you cannot guarantee that such classes will always be used properly, class members should always be initialized.
This rule flags members which have no default value and which are left uninitialized by at least one class constructor, but which are unconditionally dereferenced somewhere in the code.
=== Noncompliant code example
[source,java]
----
public class Team {
int limit = 30;
List<Player> roster; // Noncompliant; no default & not initialized by constructor
Person coach;
public Team (Person coach) { // roster is left uninitialized
this.coach = coach;
}
public void add(Player p) {
if (roster == null) {
roster = new ArrayList<Player>();
}
roster.add(p);
}
public boolean isFull() { // NPE if called before add()
return roster.size() < limit;
}
}
----
=== Compliant solution
[source,java]
----
public class Team {
int limit = 30;
List<Player> roster = new ArrayList<Player>();
Person coach;
public Team (Person coach) {
this.coach = coach;
}
public void add(Player p) {
roster.add(p);
}
// ...
----
or
[source,java]
----
public class Team {
int limit = 30;
List<Player> roster;
Person coach;
public Team (Person coach) {
this.coach = coach;
this.roster = new ArrayList<Player>();
}
public void add(Player p) {
roster.add(p);
}
// ...
----