Static Methods X Nonstatic Methods for Data Access Layer

Asked

Viewed 67 times

-4

I’m creating a layer in ADO.NET for data access and painted a question. It is good practice to have my methods of accessing data as Static instead of always having to instantiate the object and call the method?

  • It’s good practice yes.

  • No, it’s not no.

  • no, it’s not... if you use multiple threads to make a update, for example.... can give "bullshit" rs

  • I don’t understand.... how can it be "bullshit"? If the value received by the static method will be that of the thread, how will it manage to get lost?

1 answer

4


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

In general I would say that nay, is not a good practice.

Using static methods in DAO, you cannot modify its behavior (in cases of overload, for example)...

If you use 2 or more threads simultaneously, if one of the threads closes the DAO before the others, which has great chances of happening, you will not get the result you expect, do you agree? Not to mention other cases like unit testing... it’s a lot more complicated... so some disadvantages:

  • Is not safe in an application multi-threaded.
  • You cannot inject dependencies into static classes.
  • "Hinders" the implementation of unit tests....

I advise using the standard Singleton for his 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 method openInst() in unit tests to create Mocks for your DAO, what will simplify and MUCH your unit tests.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.