Asif
Asif

Reputation: 5038

Right way of implementing DAO classes?

I have a number of plain entity classes corresponding to the tables in database, there structure is similar as:

package project.src.entities;
public class ClassName{
/** variables */
private type var1;
private type var2;
/** ...variable ends */
/** Default constructor */
public ClassName(){
}
/** Custom constructor */
public ClassName(type var1, type var2 /*, ... */){
this.var1 = var1;
..
}
/** follows getters and setters of all fields */
}


Now I created a new package:

package project.src.dao;

This package will contain all the methods that interacts with the database through JDBC. such as:

public class ClassNameDAO {
  /** @return an object of ClassName of given id */
  public static ClassName getClassName(String id){
  . . .
  return className;
  }
  /** @return an ArrayList<ClassName> of objects of ClassName */
  public static ArrayList<ClassName> getAllClassName(){
  . . .
  return classNameList;
  }
  /* Similarly, methods add(ClassName className), update(id, newClassName) and delete(id) follows */
}

Now My questions are:

  1. Is this the right way of implementation in a swing application?
  2. Suggest A nicer way to implement DAOs, examples are heartly welcomed?
  3. Can i have all static methods in DAO? Is there any problem? If Yes, then why so?
  4. Anything in extra you want to point out?
    Thanks.


EDIT : Found Exactly What I need Here .... Thanks @BalusC

Upvotes: 2

Views: 1446

Answers (1)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79838

This is basically right, except that I wouldn't use static methods in the DAO. I would also have an interface for the DAO, and a DAO class that implements the interface.

One important reason not to use static methods is for testability. At some point, you'll want to unit test the classes that call the DAO methods; and for this, you'll want to mock the DAO classes. You can't easily mock classes that have a lot of static methods.

In the future, you may want to supply different implementations for some of your DAO methods. For example, you may want to have some SQL that's specific to a particular database implementation (such as an Oracle Hint), or you may want to write data to the file system, or to a web service. If you use one DAO interface and many DAO classes that implement it, then it's easier to use the multiple implementations within the one application.

Upvotes: 1

Related Questions