What are the pros/cons of choosing between static and instance data access classes in a web app?

Kevin Babcock picture Kevin Babcock · Jan 20, 2010 · Viewed 8.4k times · Source

I've read several other questions on this topic (here, here, and here), but have yet to see a great answer. I've developed my fair share of data access layers before and personally prefer to use instance classes instead of static classes. However, it is more of a personal preference (I like to test my business objects, and this approach makes mocking out the DAL easier). I have used static classes to access the database before, but I've always felt a little insecure in the appropriateness of such a design (especially in an ASP.NET environment).

Can anyone provide some good pros/cons with regards to these two approaches to developing data access classes with ADO.NET providers (no ORM), in an ASP.NET application in particular. Feel free to chime in if you have some more general static vs. instance class tips as well.

In particular, the issues I'm concerned about are:

  1. Threading & concurrency
  2. Scalability
  3. Performance
  4. Any other unknowns

Thanks!

Answer

Reed Copsey picture Reed Copsey · Jan 20, 2010

Static based approaches really typically have one, and only one, main advantage: they're easy to implement.

Instance based approaches win for:

  1. Threading and Concurrency - You don't need any/as much synchronization, so you get better throughput
  2. Scalability - Same issues as above
  3. Perf. - Same issues as above
  4. Testability - This is much easier to test, since mocking out an instance is easy, and testing static classes is troublesome

Static approaches can win on:

  1. Memory - You only have one instance, so lower footprint
  2. Consistency/Sharing - It's easy to keep a single instance consistent with itself.

In general, I feel that instance-based approaches are superior. This becomes more important if you're going to scale up beyond a single server, too, since the static approach will "break" as soon as you start instancing it on multiple machines...