Static methods X Non-static methods for data access layer

-4

I'm creating a layer in ADO.NET for data access and painted a doubt. Is it a good practice to have my data access methods as static instead of having to always instantiate the object and call the method?

    
asked by anonymous 31.03.2016 / 20:47

1 answer

4

The truth is that it depends on how "sophisticated" you are ...

In general I would say no , this is not good practice.

Using static methods in DAO , you can not modify its behavior (in cases of overloading, for example) ...

If you use 2 or more threads simultaneously, if one of the threads closes DAO before the others, which is very likely to happen, you will not get the result you expect, do you agree? Not to mention other cases like unit tests ... it's a lot more complicated ... then some disadvantages:

  • Is not secure in a multi-threaded application.
  • You can not inject dependencies into static classes.
  • "Difficult" to implement unit tests ....

I recommend using the Singleton pattern for your DAO :

public class ClienteDAO { 
  private static final ClienteDAO SINGLETON = openInst(); 

  private static ClienteDAO openInst() { 
    // Iniciar o DAO
  } 

  public ClienteDAO getInstance() { 
    return SINGLETON; 
  } 
} 
The advantage is that it is safe in multi-threaded applications, and you can modify the openInst() method in unit tests to create Mocks for your DAO , which will simplify your unit tests VERY much. / p>     
31.03.2016 / 22:01