0

HibernateDocs
In this link to hibernate docs, in the example, in Cat.class the setId() is declared private.
Is it a good practice to mark setters private for the fields whose values I do not want to change?

Also can this be used as an alternative to marking fields final? Providing default constructor and constructor with desired fields and making setters private for those fields.

I want this answer in Hibernate's context, not java's abstraction. Is this a good practice and should it be used?

Community
  • 1
  • 1
Ankit Deshpande
  • 3,476
  • 1
  • 29
  • 42

1 Answers1

2

I think no. Fields Encapsulation methods are used to access/set private fields from the outside of a class. If you don't want to modify your field you should declare it final or you should not declare a setter method. The hibernate example shown is an exception. If you persist an Entity the id property (if autogenerated) is setted automatically by reflection. Making this setter private is a good way to preserve this value without the risk to manually modify it in your code

Homo Filmens
  • 116
  • 7
  • I agree.. But because of Hibernate I'm forced to declare the setter `methods` – Ankit Deshpande Apr 25 '16 at 11:28
  • 1
    yes you have to declare it but you could make it private for the reasons above.Expecially for the id property. You are forced to make encapsulation for an hibernate entity but you can avoid modifying properties that you don't want to modify by using private accessor. – Homo Filmens Apr 25 '16 at 11:30
  • So is it acceptable if i mark it as private? I mean by the Industry standards and all – Ankit Deshpande Apr 25 '16 at 11:30
  • Yes, It is acceptable. I always use private setter for the ID property – Homo Filmens Apr 25 '16 at 11:32