Repository Save vs Update
One thing that has bugged me to no end (yes, I'm easily irked) is the concept of Save vs. Update. People seem to always follow the CRUD (Create, Read, Update, Delete) mentality even when dealing with objects. Take a class following the Repository pattern:
public class Repository
{
public static void Update(DomainObject obj)
{
// Find the information to update
// Update the values
}
public static void Save(DomainObject obj)
{
// Add a new item to the repository
// Update the values
}
}
public class Repository
{
public static void Update(DomainObject obj)
{
// Determine if this is new or not
// If new, add a new item otherwise
// find the existing item and update the values
}
private static void Add(DomainObject obj)
{
// Add a new item to the repository
}
}
So now I'm only exposing the Update method to any callers to the Repository and let the Repository make the decision whether or not this is a new item or not. The Add is hidden and maybe I have a private method to do a find based on an identity in the DomainObject. In some cases (like if my Repository is a facade to a DBMS) then I really just need a new id back from the add then I could do a Save using that information which would transmogrify my Repository into something like this:
public class Repository
{
public static void Update(DomainObject obj)
{
// Determine if this is new or not
if(!FindById(DomainObject.Id))
{
DomainObject.Id = Add();
}
// Now update the item using a Mapper
Mapper.Save(DomainObject);
}
private static long Add()
{
// Add a new item to the repository
// could be in-memory or a write to a DBMS
return SomeMethodToAddRecordInDBMS();
}
private static bool FindById(long id)
{
// Do some kind of find of an item with the same identity
return SomeMethodToFindRecordInDBMS(id);
}
}