What would be a better approach for an xml-based repository:
1) Save changes to the underlying xml document on each call to the repository...
public class XmlRepository1
{
private XDocument xDocument;
public void CrudOp()
{
// Perform CRUD operation...
// Call Save()
xDocument.Save(path);
}
}
or
2) Provide the end-user with a SaveChanges() method...
public class XmlRepository2
{
private XDocument xDocument;
public void CrudOp()
{
// Perform CRUD operation...
// DON'T call save
}
// Provide a SaveChanges() method to the end-user...
public void SaveChanges()
{
xDocument.Save(path);
}
}
My inclination leans towards option 1, because providing a SaveChanges() method doesn't really seem like a repositories responsibility. However, I'm second-guessing this decision for a couple of reasons:
a) In a multi-threaded environment, this gives the end-user an easy way to roll-back changes should a call to the repository fail, leaving objects in a partially-mutated state.
b) Option 2 provides a "batch-like" paradigm, which I can see as being more flexible for a variety of reasons.
Consider adding some sort of transaction support (close to your second apporach).
public class XmlRepository2
{
public void CrudOp()
{
// DON'T call save
}
public MakeTransacedChanges(Action<XmlRepository2> makeChanges)
{
try{
makeChanges(this);
saveChanges();
}
catch (RepositoryException e)
{
//revert changes
}
}
private void saveChanges()
{
xDocument.Save(path);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With