Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Static methods or none static methods in Dao Class?

Tags:

class

static

dao

Hi I generate Dao classes for some DB operations

in this manner making methods of Dao class as static or none static is better?

Using sample dao class below ,İf more than one client got to use the AddSampleItem method in same time?how this may result?

public class SampleDao
{
  static DataAcessor dataAcessor 

  public static void AddSampleItem(object[] params)
  {
      dataAcessor =new DataAcessor();
       //generate query here
       string query="..."
      dataAcessor.ExecuteQery(query);
      dataAcessor.Close(); 
   }

  public static void UpdateSampleItem(object[] params)
  {
      dataAcessor =new DataAcessor();
       //generate query here
       string query="..."
      dataAcessor.ExecuteQery(query);
      dataAcessor.Close(); 
   }
}
like image 343
dankyy1 Avatar asked Mar 26 '10 14:03

dankyy1


2 Answers

Assigning new DataAccessor object to static DataAccessor reference in every method will result in concurrency issues. You can still have the static methods in SampleDao class but make sure you remove the static reference to DataAccessor. To use DataAccessor, create a local instance. This way you can avoid concurrency issues. The disadvantage here is every time you call the static method, an instance to DataAccessor is created.

Daos in most cases are stateless.In those cases I see no point in having non static methods in Daos, because we need to create an instance of that dao to access its method.

like image 153
MVJ Avatar answered Nov 12 '22 21:11

MVJ


It would result in a big mess. If you are adding 2 items simultaneously from different threads, you would certainly end up with very strange results, or even errors if one thread closes the DataAcessor before the other completes.

I would use a local DataAcessor or create a new and use that in all the methods depending on how you want to manage the lifetime of DataAcessor.

public class SampleDao
{
  public void AddSampleItem(object[] params)
  {
      DataAcessor dataAcessor =new DataAcessor();
      // ...
  }

  public void UpdateSampleItem(object[] params)
  {
      DataAcessor dataAcessor =new DataAcessor();
      // ...
  }
}
like image 34
bruno conde Avatar answered Nov 12 '22 21:11

bruno conde