Created
July 12, 2012 22:52
-
-
Save ferclaverino/3101629 to your computer and use it in GitHub Desktop.
Single responsability example, step 4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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