Some people think that they should always encapsulate all fields using seters / getters. Others believe that this practice should not be used at all.
If your class does not have any logic for fields and is simply used as the owner, you can skip using methods and just declare your fields public. This concept is also called a data transfer object (or Messenger.) But, as a rule, you should use the final attribute for such fields to make your class immutable:
public class TwoTuple<A,B> { public final A first; public final B second; public TwoTuple(A a, B b) { first = a; second = b; } }
However, you should / or strongly recommended using setters / getters:
- Web applications sometimes have requirements for using setters / getters. See POJO / JavaBean Objects.
- if your class will be used in a parallel environment. See Java Concurrency in Practice, Section 3.2: “Whether another thread really does something with the published link doesn't really matter, because the risk of abuse is still present. [7] Once the object runs away, you must assume that another class or thread may, maliciously or carelessly, abuse It is a compelling reason to use encapsulation: it makes it practical to analyze programs for correctness and it’s harder to break constructive constraints by accident "
- if you want to add additional logic when setting / getting values, you should use seters / getters. Just read about encapsulation and its benefits.
My own opinion always declares the fields a “private finale”, and only after that, if necessary, change these properties.
Alexandr
source share