Public Mutable Field (ARCH4186)
هذا المحتوى غير متوفر بلغتك بعد.
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.
Incorrect
Section titled “Incorrect”public class Account { public double balance;}Correct
Section titled “Correct”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.