What you are doing is basically an implementation of the Active Record pattern. Many people use it, and it's a perfectly valid approach. If your application is very complex however, or if you have a fetish about separation of concerns, you might find the following helpful:
I recommend a DDD (domain-driven design) approach. DDD uses the so-called repository pattern. DDD segregates your application and its concerns into different layers, "Model/Domain", "Infrastructure" and "Service".
The repository is a pattern that belongs inside the infrastructure layer. Business objects like Customer
or Employer
(or Monster
and Weapon
) are inside the model layer and represent the core of your 'domain' (which you try to model), they are also responsible for the business logic. The Service layer can be used to simplify, orchestrate activities that span multiple models.
For each domain model (for instance, your classes Foo and Bar) you have a repository which handles the database access. With this, you have your database calls and your models separated.
public interface IFooRepository
{
Foo Get(Guid guid);
}
public class FooRepository : IFooRepository
{
public Foo Get(Guid guid)
{
//... DB voodoo magic happening
return foo;
}
}
You could also create a generic IRepository<T>
if you're sick of writing boiler code for your repositories all the time.
You should also look into dependency injection / inversion of control because this approach works really well with it.
The benefit of this approach is, that you can easily implement new classes that derive from IFooRepository. This allows you to quickly adopt to changes in your database infrastructure. For instance, you could create a FooRepository which reads data from an XML file, or one that reads from a Postgres db with NHibernate.
You can also read this, this and this article about DDD.