Should Java POJO have field validation and throw exceptions in setter methods? -


let's have tens of java pojos represent domain, is, data in system flows objects between different layers of system. system may web application, or simple desktop application. domain consists of doesn't matter.

when designing system, confused should put validation logic. pojos ( domain objects ) represent data, , of fields inside of objects must adhere criteria, if put lot of validation logic inside setter-methods, way tell calling client throw exception. , if don't want system crash, exception must checked exception must caught , handled. consequence of each , every time create new object using setter-methods (or constructors), have either re-throw exception or use try-catch block. doesn't feel right forced use try-catch on many setter-methods.

so question should put validation logic, don't clutter code lot of boilerplate try-catch blocks , rethrows. finest java byte eaters welcome join discussion.

i have researched , googled, not found specific discussion on topic, waiting great enthusiasm deeper insight how things should done.

you might have answered own question when said

some of fields inside of objects must adhere criteria

it helps think invariants in system, i.e. things want maintain @ cost or rules must followed.
pojos "last line of defence" such invariants on data objects , appropriate - or necessary - place put validation logic. without such validation, object might no longer represent makes sense in domain.

these system invariants form contract between objects (or methods) , "clients". if trying use them contrary (hopefully well-documented) contract, throwing exception right thing do, since client's responsibility use individual parts of system correctly.

over time, i've started favoring unchecked exceptions on checked ones instances of contract violations, partly because of reason mention, namely avoid try-catch blocks everywhere.
java's standard unchecked exceptions include:

  • nullpointerexception
  • illegalargumentexception
  • illegalstateexception
  • unsupportedoperationexception

a best practice guideline use checked exceptions when error considered recoverable , unchecked exceptions otherwise.

chapter 9 of joshua bloch's "effective java, 2nd ed." provides more wisdom on topic:

  • item 57: use exceptions exceptional conditions
  • item 58: use checked exceptions recoverable conditions , runtime exceptions programming errors
  • item 59: avoid unnecessary use of checked exceptions
  • item 60: favor use of standard exceptions

none of above should deter using appropriate validation logic @ higher levels, enforce context-specific business rules or constraints.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

node.js - How to abort query on demand using Neo4j drivers -