Search code examples
javapojo

What do you do when you start a new POJO class?


Let's say that you are setting up a POJO.

What do you define when you setup the class?

Here's my list

  • Constructor to create an object with supplied fields (so that I can make fields final and hence immutable)
  • toString
  • equals
  • hashcode
  • implements comparable
  • get methods (where applicable)
  • [Optional] copy constructors for mutable fields - to guarantee immutability of the class
  • [Optional] Define interfaces to access fields and methods.
  • [Optional] implements Serializable and implement a versioning scheme.

Is this overkill or sound engineering? Anything missing that you would add?


Solution

  • I'm assuming that because you mentioned a versioning scheme, that we're talking about persistable classes.

    I'd say you have a nice list there, but (depending on your ORM engine), I also tend to determine what values (other than the autoincrement ID), define the 'uniqueness' of any record.

    I only mention this because hibernate has weird behaviour with Sets, if you use the ID in hashCode, because it is liable to change halfway through the process.

    Also worth noting that it's worth your time to look at which collections are going to be Lazy or Eager, especially for the toString method (which may cause Lazy-Inits if you do a toString when you are detached from the persistence context).