Simplify database operations

Since fetch and edit operations are such common tasks in many applications, it's beneficial if these tasks can be made as simple and compact as possible. Even when using tools on top of JDBC, there are very often ways of simplifying code and removing repetition.

If you find that your data access code is becoming repetitive, look for ways to remove the repetition - utility classes, template methods, and so on.


The MemberDAO class is taken from one of the WEB4J example applications. This example is already quite compact. The methods are short, and read at a high level. If you look closely, however, you can see that one item is still repeated. Can you spot it? It's rather subtle. (See answer below.)

/** Data Access Object (DAO) for {@link Member} objects. */
public final class MemberDAO {

  List<Member> list() throws DAOException {
    return Db.list(Member.class, MEMBER_LIST);
  public Member fetch(Id aMemberId) throws DAOException {
    return Db.fetch(Member.class, MEMBER_FETCH, aMemberId);
  Id add(Member aMember) throws DAOException, DuplicateException {
    return Db.add(MEMBER_ADD, baseParamsFrom(aMember));
  boolean change(Member aMember) throws DAOException, DuplicateException {
    Object[] params = Db.addIdTo(baseParamsFrom(aMember), aMember.getId());
    return Util.isSuccess(Db.edit(MEMBER_CHANGE, params));
  int delete(Id aMemberId) throws DAOException {
     return Db.delete(MEMBER_DELETE, aMemberId);
  private Object[] baseParamsFrom(Member aMember){
    return new Object[]{
      aMember.getName(), aMember.getIsActive(), aMember.getDisposition().getId()
The answer is that the list and fetch methods repeat the same piece of data - the class literal Member.class. Like any repeated literal, it should likely be placed in a private static final field. Since that would be a common occurence, it would likely be beneficial to make a habit of doing so, and of giving a conventional name to the field as well, such as MODEL_CLASS.

See Also :
Reduce database code duplication
Keep SQL out of code
Consider data layer tools
Encapsulate connections
A Web App Framework WEB4J
Use template for transactions