In public classes, use accessor methods, not public-fields

Occasionally, you may be tempted to write degenerate classes that server no purpose other than to group instance fields:

//Degenerate classes like this should not be public!
class Point {
  public long x;
  public long y;
}

Because the data fields of such classes are accessed directly, these classes do not offer the benefits of encapsulation. You can’t change the representation without change the API.

If a class is accessible outside its package, provide accessor methods.

If a class is package-private or is a private nested class, there is nothing inherently wrong with exposing its data fields.

While it’s never a good idea for a static public class to expose fields directly, it is less harmful if the fields are immutable.

// Public class with exposed immutable fields - questionable
public final class Time {
  private static final int HOURS_PER_DAY = 24;
  private static final int MINUTES_PER_HOUR = 60;

  public final int hour;
  public final int minutes;
}

In summary, public classes should never expose mutable fields. It is less harmful, though still questionable, for public classes to expose immutable fields.

It is, however, sometimes desirable for package-private or private nested classes to expose fields, whether mutable or immutable.

Faci un comentariu sau dai un răspuns?

Adresa ta de email nu va fi publicată. Câmpurile obligatorii sunt marcate cu *

Acest site folosește Akismet pentru a reduce spamul. Află cum sunt procesate datele comentariilor tale.