Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Repository; to Save() or not to Save()

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.

like image 748
Didaxis Avatar asked Oct 09 '22 11:10

Didaxis


1 Answers

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); 
    }
  }
like image 132
Alexei Levenkov Avatar answered Oct 13 '22 12:10

Alexei Levenkov