java - Are there use-cases for mutable public fields? -


i want know if there might use cases public fields justified (for mutable values) or should avoided @ costs , getters/setters should used.

supposed there dto(data transfer object)/java bean no have logic, holding data (to add more might part of protocol not change, enhance). there no implementation details exist encapsulated because there no implementation, data. suppose bean validation framework used validating object via annotations there no purpose of having setters validating logic.

why setters , getters bother me?

it's more easy read without setters/getters; fields, inner classes (you don't have scroll through setters , getters reach other fields). it's more clear have user.password rather user.getpassword() in groovy.

i know project lombok; have lots of annotations bean validation.

so make question clear: might above scenario justified public fields or still better have setters/getters? and why?

the current opinion should not have mutable public fields.

it derives principle of least astonishment 2 different directions.

first, common practice have fields private access via getters , setters. there code out there surprising when come across code doesn't.

second, gives predictability. can guarantee no-one change fields anywhere else other in setter. can therefore put break-point on setter , know every change field hit break-point.

there - - pure data situations describe tempting make fields public, , rarer, not final.

i have in toolbox class pair has public fields:

public class pair<p, q> {      // exposing p & q directly simplicity. final safe.      public final p p;     public final q q;      public pair(p p, q q) {         this.p = p;         this.q = q;     } 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -