Aller au contenu

Public Mutable Field (ARCH4186)

Ce contenu n’est pas encore disponible dans votre langue.

Key java.quality.public-mutable-field · Severity warning · Category quality

Public mutable fields break encapsulation; any caller can mutate the value with no checks. Make the field private and guard it with accessors.

public class Account {
public double balance;
}
public class Account {
private double balance;
public double getBalance() { return balance; }
public void deposit(double amount) {
if (amount <= 0) throw new IllegalArgumentException();
balance += amount;
}
}

Make the field private and govern changes through validating accessor/mutator methods.