Video in progress

Is it right to automatically write a getter and setter for every private field?

No. Adding setters blindly is the same as making the field public. Expose only what the outside really needs, and offer changes through meaningful methods (activate(), changeEmail()).

📖 Answer

It is easy to click "Generate getters and setters" in the IDE, but the result often looks like this:

order.setStatus(Status.PAID);
order.setPaidAt(null);       // paid but no time: an impossible state

It is better to move the behavior into the class:

public void markPaid(Instant at) {
    if (status != Status.NEW) throw new IllegalStateException("Faqat yangi buyurtma to'lanadi");
    this.status = Status.PAID;
    this.paidAt = at;
}

Now Order can never end up "half paid".

This is what I usually do:

  • if you need a getter, add it, but don't return a mutable collection directly;
  • a method with a business-meaningful name is better than a setter;
  • make fields that never change final and set them in the constructor.

Setters are fine in JPA entities and DTOs, since the framework asks for them. Be careful in classes with domain logic.