Skip to content

Instantly share code, notes, and snippets.

@ferclaverino
Created July 12, 2012 22:52
Show Gist options
  • Save ferclaverino/3101629 to your computer and use it in GitHub Desktop.
Save ferclaverino/3101629 to your computer and use it in GitHub Desktop.
Single responsability example, step 4
class ProductRepository : IProductRepository
{
private readonly IFileLoader loader;
private readonly IProductsMapper mapper;
public ProductRepository()
{
loader = new FileLoader();
mapper = new ProductsMapper();
}
public IEnumerable<Product> GetByFileName(string fileName)
{
IEnumerable<Product> products;
using (Stream file = loader.Load(fileName)) {
products = mapper.Map(file);
}
return products;
}
}
class ProductsMapper : IProductsMapper
{
private Product MapItem(XmlReader reader)
{
if (reader.Name != "product") throw new InvalidOperationException("XML reader is not on a product fragment.");
var product = new Product();
product.Id = int.Parse(reader.GetAttribute("id"));
product.Name = reader.GetAttribute("name");
product.UnitPrice = decimal.Parse(reader.GetAttribute("unitPrice"), CultureInfo.InvariantCulture);
product.Discontinued = bool.Parse(reader.GetAttribute("discontinued"));
return product;
}
public IEnumerable<Product> Map(Stream stream)
{
if (stream == null) throw new ArgumentNullException("Stream used when mapping cannot be null.");
var reader = XmlReader.Create(stream);
var products = new List<Product>();
while (reader.Read())
{
if (reader.Name != "product") continue;
var product = MapItem(reader);
products.Add(product);
}
return products;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment