88 lines
2.0 KiB
Plaintext
88 lines
2.0 KiB
Plaintext
![]() |
*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 doesn’t 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,text]
|
|||
|
----
|
|||
|
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,text]
|
|||
|
----
|
|||
|
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,text]
|
|||
|
----
|
|||
|
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);
|
|||
|
}
|
|||
|
|
|||
|
// ...
|
|||
|
----
|
|||
|
|