Using Static methods or none static methods in Dao Class?

前端 未结 5 1476
庸人自扰
庸人自扰 2020-12-30 06:22

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 belo

相关标签:
5条回答
  • 2020-12-30 06:50

    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();
          // ...
      }
    }
    
    0 讨论(0)
  • 2020-12-30 06:50

    Bruno is correct. However, you could also add a singleton and use "lock" to single-thread that part of your app. Keep in mind, though, that requests are going to queue up and if your query takes time your app's performance will degrade. This is especially noticeable in a web app. For a mobile or desktop app "lock" is definitely appropriate.

    0 讨论(0)
  • 2020-12-30 06:54

    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

    0 讨论(0)
  • 2020-12-30 06:55

    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.

    0 讨论(0)
  • 2020-12-30 07:03

    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.

    0 讨论(0)
提交回复
热议问题