I've been following Josh Smith's excellent article on the MVVM pattern. In his example, he has a CustomerRepository that fetches data from a source:
public CustomerRepository(string customerDataFile)
{
_customers = LoadCustomers(customerDataFile);
}
What I don't understand is the fact that he calls a static method, LoadCustomers, straight from his constructor:
static List<Customer> LoadCustomers(string customerDataFile)
{
// In a real application, the data would come from an external source,
// but for this demo let's keep things simple and use a resource file.
using (Stream stream = GetResourceStream(customerDataFile))
using (XmlReader xmlRdr = new XmlTextReader(stream))
return
(from customerElem in XDocument.Load(xmlRdr).Element("customers").Elements("customer")
select Customer.CreateCustomer(
(double)customerElem.Attribute("totalSales"),
(string)customerElem.Attribute("firstName"),
(string)customerElem.Attribute("lastName"),
(bool)customerElem.Attribute("isCompany"),
(string)customerElem.Attribute("email")
)).ToList();
}
Is this some kind of lazy-loading pattern, or is there some other specific reason a developer would do this?
I don't think that this is specifically related to repositories.
The method is static because it does not use any of the classes instance variables. There is a small performance improvement as you don't need to transfer the this reference over the stack.
As it is also private, you can safely mark it as static. For non-private methods, this is different, because if you use a static method from the outside, callers bind themselves to the concrete type that the static method defines. This makes the design less flexible and reduces testability. But as stated before, this is not an issue for a private method.
(1) This is not Lazy loading.
(2) If you see the comment within LoadCustomers, he clearly mentioned 'In a real application, the data would come from an external source,but for this demo let's keep things simple and use a resource file.'. This means, his intention was to show some data in UI rather the best way of bring data from some store to UI.
As mentioned via comments, in production quality code, we mostly follow some well define d pattern. Eg: Injecting repository object via dependency injection in your view model.
Related
I would like to preface that I have not used Dynamic Objects very often, and only recently came across this problem. I have a specific scenario that I will explain below, but I was wondering what exactly were the advantages of implementing a dynamic object compared to creating a class for that object.
I have a method that takes a dynamic object as a parameter. For the sake of length I will not post much code just enough to get the point across:
public static Tax GetEmployeeTax(string Id, Employee employee, dynamic inputObject)
{
var temp = new Employee();
//use the dynamic object properties
return temp;
}
In this case, inputObject will have properties that help identify the employee taxes without directly being related to the employee class. Primarily I have given the inputObject the following properties:
dynamic dynamicEmployeeTax = new ExpandoObject();
dynamicEmployeeTax.FederalTaxInfo = "Some information";
dynamicEmployeeTax.StateTaxInfo = "Some other information";
Are there any advantages to making this it's own class versus using a dynamic object? Are there any benefits one way or the other?
There are several reasons why you want to create a class:
Strong typing leverages the compiler to ensure correctness.
Every class that encapsulates data is like a contract. You can imagine how's used by examining the class.
You force the guy after you to read how it works. It is simpler to read class properties and image its utility.
It is a sign a bad planning and engineering. You are creating blobs of data instead of structured data sets that solve a specific problem. Think mud pits versus Lego blocks.
The list goes on ad infinitum. I think the consensus here is to avoid it. There are extreme rare cases where this is useful. For most, stick to contracts and coding to abstractions not implementation details.
At work we are using a 'pattern' that I didn't really find in the GoF book (but that may be due to lack of competence in this matter, I just skimmed the patterns) and that I'm still doubting somewhat.
Say, if we have a multi-project solution containing a project DataAccess that manages, well, the data access. Then usually I see it having a structure like this:
Providers (Folder)
- DataAccessProvider.cs
Interfaces (Folder)
- IFileLoader.cs
Implementors (Folder)
- FileLoader.cs
Here, FileLoader would be an internal implementation of the interface IFileLoader, and the provider looks like this:
public static class DataAccessProvider
{
public static IFileLoader FileLoader
{
get { return new FileLoader(); }
}
}
What kind of design pattern is this (if any), and what are its real uses besides masking the specific implementation of the IFileLoader interface?
And secondly, is this really 'good style'? I wonder, for example, what happens if there are many calls like
string content = DataAccessProvider.FileLoader.LoadContentFromFile("abc.txt");
This would call new FileLoader() whenever it is used. Isn't there a more elegant way to do a similar approach?
In this example the DataAccessProvider is an example of a simple Factory Method (pattern). Normally you would have a method called GetFileLoader() or CreateFileLoader() instead of a Property version, but the result is the same.
The purpose of returning the IFileProvider instead of FileProvider is for Dependency Inversion, this way one could write other types of FileProvider and inject them into the application without needed to rework or recompile all of the object that depend on an IFileProvider. It's not about masking.
If one is concerned about how many instances of FileLoader are created, then one could use the Singleton pattern for that object. However, this is normally not an issue if the FileLoader is a lightweight object, since the CLR garbage collector will take care of that automatically for you.
In the projects I worked on I have classes that query/update database, like this one,
public class CompanyInfoManager
{
public List<string> GetCompanyNames()
{
//Query database and return list of company names
}
}
as I keep creating more and more classes of this sort, I realize that maybe I should make this type of class static. By doing so the obvious benefit is avoid the need to create class instances every time I need to query the database. But since for the static class, there is only one copy of the class, will this result in hundreds of requests contend for only one copy of static class?
Thanks,
I would not make that class static but instead would use dependency injection and pass in needed resources to that class. This way you can create a mock repository (that implements the IRepository interface) to test with. If you make the class static and don't pass in your repository then it is very difficult to test since you can't control what the static class is connecting to.
Note: The code below is a rough example and is only intended to convey the point, not necessarily compile and execute.
public interface IRepository
{
public DataSet ExecuteQuery(string aQuery);
//Other methods to interact with the DB (such as update or insert) are defined here.
}
public class CompanyInfoManager
{
private IRepository theRepository;
public CompanyInfoManager(IRepository aRepository)
{
//A repository is required so that we always know what
//we are talking to.
theRepository = aRepository;
}
public List<string> GetCompanyNames()
{
//Query database and return list of company names
string query = "SELECT * FROM COMPANIES";
DataSet results = theRepository.ExecuteQuery(query);
//Process the results...
return listOfNames;
}
}
To test CompanyInfoManager:
//Class to test CompanyInfoManager
public class MockRepository : IRepository
{
//This method will always return a known value.
public DataSet ExecuteQuery(string aQuery)
{
DataSet returnResults = new DataSet();
//Fill the data set with known values...
return returnResults;
}
}
//This will always contain known values that you can test.
IList<string> names = new CompanyInfoManager(new MockRepository()).GetCompanyNames();
I didn't want to ramble on about dependency injection. Misko Hevery's blog goes into great detail with a great post to get started.
It depends. Will you ever need to make your program multithreaded? Will you ever need to connect to more than one database? Will you ever need to store state in this class? Do you need to control the lifetime of your connections? Will you need data caching in the future? If you answer yes to any of these, a static class will make things awkward.
My personal advice would be to make it an instance as this is more OO and would give you flexibility you might need in the future.
You have to be careful making this class static. In a web app, each request is handled on its own thread. Static utilities can be thread-unsafe if you are not careful. And if that happens you are not going to be happy.
I would highly recommend you follow the DAO pattern. Use a tool like Spring to make this easy for you. All you have to do is configure a datasource and your DB access and transactions will be a breeze.
If you go for a static class you will have to design it such that its largely stateless. The usual tactic is to create a base class with common data access functions and then derive them in specific classes for, say, loading Customers.
If object creation is actually the overhead in the entire operation, then you could also look at pooling pre-created objects. However, I highly doubt this is the case.
You might find that a lot of your common data access code could be made into static methods, but a static class for all data access seems like the design is lost somewhere.
Static classes don't have any issues with multi-threaded access per-se, but obviously locks and static or shared state is problematic.
By making the class static, you would have a hard time unit testing it, as then you
would probably have to manage internally the reading of the connection string in a non-clear manner, either by reading it inside the class from a configuration file or requesting it from some class that manages these constants. I'd rather instantiate such a class in a traditional way
var manager = new CompanyInfoManager(string connectionString /*...and possible other dependencies too*/)
and then assign it to a global/public static variable, if that makes sense for the class, ie
//this can be accessed globally
public static CompanyInfoManager = manager;
so now you would not sacrifice any flexibility for your unit tests, since all of the class's dependencies are passed to it through its constructor
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
How to approach unit testing of private methods?
I have a class that loads Employee data into a database. Here is a sample:
>
public class EmployeeFacade
{
public Employees EmployeeRepository = new Employees();
public TaxDatas TaxRepository = new TaxDatas();
public Accounts AccountRepository = new Accounts();
//and so on for about 20 more repositories etc.
public bool LoadAllEmployeeData(Employee employee)
{
if (employee == null)
throw new Exception("...");
bool exists = EmployeeRepository.FetchExisting(emps.Id);
if (!exists)
{
EmployeeRepository.AddNew();
}
try
{
EmployeeRepository.Id = employee.Id;
EmployeeRepository.Name = employee.EmployeeDetails.PersonalDetails.Active.Names.FirstName;
EmployeeRepository.SomeOtherAttribute;
}
catch() {}
try
{
emps.Save();
}
catch(){}
try
{
LoadorUpdateTaxData(employee.TaxData);
}
catch() {}
try
{
LoadorUpdateAccountData(employee.AccountData);
}
catch() {}
... etc. for about 20 more other employee objects
}
private bool LoadorUpdateTaxData(employeeId, TaxData taxData)
{
if (taxData == null)
throw new Exception("...");
...same format as above but using AccountRepository
}
private bool LoadorUpdateAccountData(employee.TaxData)
{
...same format as above but using TaxRepository
}
}
I am writing an application to take serialised objects(e.g. Employee above) and load the data to the database.
I have a few design question that I would like opinions on:
A - I am calling this class "EmployeeFacade" because I am (attempting?) to use the facade pattern. Is it good practace to name the pattern on the class name?
B - Is it good to call the concrete entities of my DAL layer classes "Repositories" e.g. "EmployeeRepository" ?
C - Is using the repositories in this way sensible or should I create a method on the repository itself to take, say, the Employee and then load the data from there e.g. EmployeeRepository.LoadAllEmployeeData(Employee employee)? I am aim for cohesive class and but this will requrie the repository to have knowledge of the Employee object which may not be good?
D - Is there any nice way around of not having to check if an object is null at the begining of each method?
E - I have a EmployeeRepository, TaxRepository, AccountRepository declared as public for unit testing purpose. These are really private enities but I need to be able to substitute these with stubs so that the won't write to my database(I overload the save() method to do nothing). Is there anyway around this or do I have to expose them?
F - How can I test the private methods - or is this done (something tells me it's not)?
G- "emps.Name = employee.EmployeeDetails.PersonalDetails.Active.Names.FirstName;" this breaks the Law of Demeter but how do I adjust my objects to abide by the law?
A - I wouldn't call it XXXFacade, but something more meaningful (which may in fact mean you should call it XXXFacade)
B - I would call them XXXRepository
C - I don't really understand your model here - you're passing in an Employee object and assigning its values to the equivilent values in EmployeeRepository. The Repository shouldn't contain data fields - each instance of the repository does not represent a row in the database. The Repository is a way of getting data in and out of the database, by operating on collections of entities from the database (ie: Repository is the table, Entities are the rows). I would expect the Repository object to have a Save method which takes an Employee object as a parameter and it persists it to the database. As well as a Load method which takes an Id and returns and Employee:
Employee myEmployee = repository.Load(112345);
myEmployee.Name = "New Name";
repository.Save(myEmployee);
The Repository base class doesn't need to know about the specific implementation of the Employee class, through the use of generics and polymorphism. Take a look at Sh#rpArchitecture for a good example of this pattern.
D - yes, put that common logic in an abstract base class (Repository)
E - don't make them public if they should be private. If you need the use the logic of the repository in your unit tests to simulate fetching data, implement a common interface and then mock that interface out in your tests. You don't need to test that the repository returns the correct data since data is transient and inconsistent in reality. Better to fake it and test your behaviour does what you expect on precanned data from a mock repository.
F - Don't. Test behaviour not implementation.
G - I don't think this issue exists if you examine your architecture as described above.
How to approach unit testing of private methods?
You shouldn't write tests for private methods.
The only possible way of creating private methods is a refactorings of already tested public methods.
A - I am calling this class
"EmployeeFacade" because I am
(attempting?) to use the facade
pattern. Is it good practace to name
the pattern on the class name?
I don't think testing private methods a good idea; however, you can test "internal" classes, which are similar to private in the sense that external assemblies will not have access to them, by marking them as Internal Visible to your unit test project.
AssemblyInfo.cs --
[assembly: InternalsVisibleTo("YourClass.Tests")]
B - Is it good to call the concrete
entities of my DAL layer classes
"Repositories" e.g.
"EmployeeRepository" ?
I do this frequently, I don't think there is anything wrong with it.
C - Is using the repositories in this
way sensible or should I create a
method on the repository itself to
take, say, the Employee and then load
the data from there e.g.
EmployeeRepository.LoadAllEmployeeData(Employee
employee)? I am aim for cohesive class
and but this will requrie the
repository to have knowledge of the
Employee object which may not be good?
Unless I don't understand correctly, I would keep them seperate. I typically use my Repository classes as simply CRUD helpers, I would write a wrapper around the repository that exposes the functionality you need.
D - Is there any nice way around of
not having to check if an object is
null at the begining of each method?
If there is, I don't know it, I would just use ArgumentNullException()
E - I have a EmployeeRepository,
TaxRepository, AccountRepository
declared as public for unit testing
purpose. These are really private
enities but I need to be able to
substitute these with stubs so that
the won't write to my database(I
overload the save() method to do
nothing). Is there anyway around this
or do I have to expose them?
See my answer for A, marking them as Internal and then setting InternalsVisible To your unit test assembly. See also MSDN.
F - How can I test the private methods
- or is this done (something tells me it's not)?
I do not typically test private methods, and private classes that need to tested I mark as internal and use them in my test assembly.
A - I don't think its particularly bad to use the pattern name in the class name, though I honestly don't know how often it's done.
F - I think zerkms is right, you probably have to make them public, test them, then make them private when you're satisfied. Once their private, you could still test public methods that make use of the private methods to ensure they continue working.
As for your DAL and such, I would suggest looking into LINQ to SQL, available in .NET 3.0 and higher. It's a nice framework for handling the abstraction layer between your business logic and the database. Here are a few links to check out...
Quick Tutorial for LINQ to SQL in C#
Part 1 of Scott Guthrie's blog
Scott Guthrie has a lot of good stuff on LINQ, if you're interested, you should check out more of his posts.
A - IMO, yes. It immediate remind you the pattern, and help you understand the code, and this is maybe one of the important practices in code writing - letting other people understand your code.
B - I prefer the xxDAO convention (Data Access Object).
C - I prefer "service oriented programming", meaning a service that "knows" to save an employee and not a "repository object" that mix between "model" and "control".
D - Maybe using Aspect, but I don't recommend it.
E - You can create an interface for those classed, and inject them from "outside" using setters (just like spring does), or get them from some kind of factory, In that way it will be easy for you to replace the classes with mock, and still leave the members "private".
F - I think that those methods should be extracted out side of the "load employee" and be self services. IMO, you should abstract the "employee data" objects (especially if you got 20 of them :-)). and write a simple service that know to load a "employee data object" of any kind.
Hope that I helped,
Shay
Your naming convention seems ok.
By calling concrete repositories you are tightly coupling the system. Pass them repo objects in constructor. Or use a DI/IOC container.
If repository is returning employee it will know of it. You might want the repo to know the contract for an employee class.
If you are getting null value for something, you should make sure provider code does not send down nulls.
You can achieve that by implementing dependency injection properly and using interfaces.
Standard unit testing frameworks will not give you that, you will need something like Moles. A sample is show on this post
Use inheritance more than composition if you can. But if the object model requires that, then you are helpless in my opinion.
The problem is really simple, I have a class "Stock", I want to load its property "StockName", "StockCode' from the db.
so which patten should I use?
pattern 1) Use service class to create it
public interface IStockService{
Stock GetStock(string stockCode);
void SaveStock(Stock stock);
}
public class StockService : IStockService{
}
IStockService stockService = new StockService();
Stock stock = stockService.GetStock();
pattern 2) Use static method in Stock
public class Stock{
public static Stock GetStock(){
Stock stock = new Stock;
//load stock from db and do mapping.
return stock;
}
public void Save(){
}
}
pattern 3) Use constructor to load
public class Stock{
public Stock(){
//load stock from db and do mapping.
this.stockName = ...
this.stockCode = ...
}
}
for pattern 1: it seems it use so many code to create a stock object, and the "SaveStock" method seems a little not object-orient.
for pattern 2: the "Save" method seems ok, but the GetStock method is a static method, it seems a Utility class which always use static method.
for pattern 3: the constructor will load the data from db when on initialize. it seems confused also.
pattern 2) is the factory (method) patten and reminds me of singletons (static = singleton). Note singletons are evil. The factory method is not not polymorph. You can't change it for tests (i.e. you can't mock it). It's evil! Avoid it!
pattern 3) violates that the constructor should not do too much. Querying the database is too much for a ctor in my opinion. The object and it's creation are different concerns and should be separated. Further more creation of an instance should be separated from the instance, so try to use factories (or injectors). You can replace the factory easier than the "new Class" spread throught your code.
pattern 1) remains, which is an abstract factory pattern. It is good. You can use another implementation for testing (a mock). It separates the creation from the object. (Single responsibility principle as Carl Bergquist calls it.)
So I would go with pattern 1.
Pattern 1:
- Easier to test
- Single responsibility principle
- Can require more code.
Pattern 2:
- Static classes/methods can make mocking much harder. I try to avoid it as much as I can.
Pattern 3:
- Is ok for small classes. But keep logic away from the constructor
But I think Orm and serialization cover most parts(object creation).
You are missing an important piece. Specifically, where do you get your connection string for talking to the database?
Update each of your examples with where the connection string comes from and I think it will make the right answer pop out.
Personally I like have my objects abstracted from their data source, so I'd go with a method like #1. #3 you definitely don't want to do...too much processing in constructors can get you in trouble. The preference of #1 vs #2 is likely to come down to how 'loaded' you want your data objects to be.
If you ever foresee getting your object from another data source you'll want to stick with #1 since it gives much better flexibility.
I would go with pattern 1. It presents a clear separation of concerns between the domain model and the data access. It is also easier to unit test.
if you want it to be initialized automatically, then use static constructor which been called by class loader .net service.
something similar to method 1 where you should be calling into the DB layer classes to get the object loaded from there, though you may want to use an ORM to take care of all the data access for you
you should seperate the entity class(stock) and the logic that populates it(stockservice), but instead of writing a stockservice class just use an orm to map db to your entity class(stock).