I have three database operations like so:
public void Add<T>(T entity)
{
using (var transaction = Session.BeginTransaction())
{
if (entity is IEnumerable)
{
foreach (var item in (IEnumerable) entity)
{
Session.Save(item);
}
}
else
{
Session.Save(entity);
}
transaction.Commit();
}
}
public void Update<T>(T entity)
{
using (var transaction = Session.BeginTransaction())
{
if (entity is IEnumerable)
{
foreach (var item in (IEnumerable) entity)
{
Session.Update(item);
}
}
else
{
Session.Update(entity);
}
transaction.Commit();
}
}
public void Delete<T>(T entity)
{
using (var transaction = Session.BeginTransaction())
{
if (entity is IEnumerable)
{
foreach (var item in (IEnumerable)entity)
{
Session.Delete(item);
}
}
else
{
Session.Delete(entity);
}
transaction.Commit();
}
}
As you can see, the only thing that differs is the Session.[something] part. How would I refactor this into only one method?
Delegates look like a good solution here, as explained by other answerers. One other possible refactoring that could arguably simplify the inside logic would be a function that returns an IEnumerable. If the passed-in object is an IEnumerable, just return it; otherwise build a single-element enumeration with the passed-in object and return the enumeration. This would turn this:
into this: