tags:

views:

139

answers:

3

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(); 
   }
}
A: 

this code is not thread-safe the way you have it written.

if you have the dataAccessor field and the methods static like this, you will have concurrency problems with multiple clients hitting this code at the same time. it's likely you'll have very strange exceptions occuring, and even possible that one client could see another client's data.

get rid of static on these methods and this field and instantiate a new instance of SampleDao for each client.

Derick Bailey
+1  A: 

It would result in a big mess. If your adding 2 items simultaneously from different threads, you would certainly end up with very strange results, or even errors if 1 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();
      // ...
  }
}
bruno conde
+2  A: 

I always prefer non static classes. Dependencies cannot be injected to an static class and unit tests are harder. Also, its clients cannot replace it with a test double when they are unit tested.

http://googletesting.blogspot.com/2008/12/static-methods-are-death-to-testability.html

bloparod