I need help to refactor my code. I usually had a hard time figuring out how to make my code reusable.
I have an XML file that hold the data for each Tag element. Tag element should have child nodes LastClocked, and TotalClocked. I first thought of creating Tag object and do serialization. But, I found Linq to XML is much easier. I would really appreciate if you guys can tell me what to improve for my code. Thank you.
namespace StopWatch.Models
{
public class TagCollection
{
private XElement doc;
private IEnumerable<XElement> tagElements;
public TagCollection()
{
if(File.Exists("TagsData.xml"))
{
doc = XElement.Load("TagsData.xml");
}
else
{
//TODO: Create XML
}
}
public void Save(TimeSpan clocked, string tags)
{
tagElements = from t in doc.Elements("Tag")
where (string)t.Attribute("Name") == tags
select t;
TimeSpan lastClocked = TimeSpan.Parse((string)
(from lc in tagElements.Descendants("LastClocked")
select lc).First());
lastClocked = lastClocked.Add(clocked);
if (!tagElements.Any())
{
Insert(clocked, tags);
}
else
{
Update(clocked, lastClocked);
}
doc.Save("TagsData.xml");
}
private void Update(TimeSpan clocked, TimeSpan lastClocked)
{
foreach(XElement tagElement in tagElements)
{
tagElement.SetElementValue("LastClocked", clocked.ToString());
tagElement.SetElementValue("TotalClocked", lastClocked.ToString());
}
}
private void Insert(TimeSpan clocked, string tags)
{
XElement newTag = new XElement("Tag",
new XAttribute("Name", tags),
new XElement("LastClocked", clocked.ToString()),
new XElement("TotalClocked", clocked.ToString()));
doc.Add(newTag);
}
}
}