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).
Related
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.
I am working with .net c# Mvc, using ninject repository pattern. My problem is that when developing I am using reusing in the functions, and everytime I want more info from db and need access to another table, I need to pass the repositories from all the places that are calling this function. Am I doing it wrong? ot this is the way, which is alot longer to develop then just opening a connection and disposing at the end of the function.
If your class needs to have loads of repositories passed in this can sometimes be a sign that your class is doing too many things and probably breaking the Single Responsibility Principle.
Perhaps if you broke this class into smaller more specialized classes the problem would not be so bad.
On the other hand, sometimes passing in loads of repositories is unavoidable. You might consider making a factory class that creates the class suffering from 'constructor jam' for you - this should save some typing as the hefty constructor initialization is just in one place (in the factory class).
edit: A really simple 'factory' class might be as follows:
public class FactoryClass
{
public ClassWithLotsOfRepositories GetClassWithLotsOfRepositories()
{
return new ClassWithLotsOfRepositories(new repository1(),
new repository2(), new repository3() );
}
}
So you can now create an instance of ClassWithLotsOfRepositories without having to specify the repositories in the constructor each time.
ClassWithLotsOfRepositories myClassThatUsesLotsOfRepositories = new FactoryClass().GetClassWithLotsOfRepositories();
My example has concrete classes passed in through the constructor. You are using Ninject so presumably have interfaces that need resolving - I'm just keeping this example simple to illustrate the concept.
use a unit of work the new up all of the repositories. That way you can pass in the uow into your controllers and have access to all repos when needed.
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.
I've just reviewed some code that looked like this before
public class ProductChecker
{
// some std stuff
public ProductChecker(int AccountNumber)
{
var account = new AccountPersonalDetails(AccountNumber);
//Get some info from account and populate class fields
}
public bool ProductACriteriaPassed()
{
//return some criteria based on stuff in account class
//but now accessible in private fields
}
}
There has now been some extra criteria added which needs data not in the AccountPersonalDetails class
the new code looks like this
public class ProductChecker
{
// some std stuff
public ProductChecker(int AccountNumber)
{
var account = new AccountPersonalDetails(AccountNumber);
var otherinfo = getOtherInfo(AccountNumber)
//Get some info from account and populate class fields
}
public bool ProductACriteriaPassed()
{
//return some criteria based on stuff in account class
// but now accessible in private fields and other info
}
public otherinfo getOtherInfo(int AccountNumber)
{
//DIRECT CALL TO DB TO GET OTHERINFO
}
}
I'm bothered by the db part but can people spell out to me why this is wrong? Or is it?
In a layered view of your system, it looks like ProductChecker belongs to the business rules / business logic layer(s), so it shouldn't be "contaminated" with either user interaction functionality (that belongs in the layer(s) above) or -- and that's germane to your case -- storage functionality (that belongs in the layer(s) below).
The "other info" should be encapsulated in its own class for the storage layers, and that class should be the one handling persist/retrieve functionality (just like I imagine AccountPersonalDetails is doing for its own stuff). Whether the "personal details" and "other info" are best kept as separate classes or joined into one I can't tell from the info presented, but the option should be critically considered and carefully weighed.
The rule of thumb of keeping layers separate may feel rigid at times, and it's often tempting to shortcut it to add a feature by miscegenation of the layers -- but to keep your system maintainable and clean as it grows, I do almost invariably argue for layer separation whenever such a design issue arises. In OOP terms, it speaks to "strong cohesion but weak coupling"; but in a sense it's more fundamental than OOP since it also applies to other programming paradigms, and mixes thereof!-)
It seems like the extra data grabbed in getOtherInfo should be encapsulated as part of the AccountPersonalDetails class, and thus already part of your account variable in the constructor when you create a new AccountPersonalDetails object. You pass in AccountNumber to both, so why not make AccountPersonalDetails gather all the info you need? Then you won't have to tack on extra stuff externally, as you're doing now.
It definitely looks like there might be something going haywire with the design of the class...but it's hard to tell without knowing the complete architecture of the application.
First of all, if the OtherInfo object pertains to the Account rather than the Product you're checking on...it's introducing responsibilities to your class that shouldn't be there.
Second of all, if you have a Data Access layer...then the ProductChecker class should be using the Data Access layer to retrieve data from the database rather than making direct calls in to retrieve the data it needs.
Third of all, I'm not sure that the GetOtherInfo method needs to be public. It looks like something that should only be used internally to your class (if, in fact, it actually belongs there to begin with). In that case, you also shouldn't need to pass around the accountId (you class should hold that somewhere already).
But...if OtherInfo pertains to the Product you're checking on AND you have no real Data Access layer then I can see how this might be a valid design.
Still, I'm on your side. I don't like it.
considering that an accountNumber was passed into the constructor you shouldn't have to pass it to another method like that.
A few points
The parameter names are pascal case, instead of camel (this maybe a mistake)
getOtherInfo() looks like it's a responsibility of AccountPersonalDetails and so should be in that class
You may want to use a Façade class or Repository pattern to retrieve your AccountPersonalDetails instead of using a constructor
getOtherInfo() may also be relevant for this refactor, so the database logic isn't embedded inside the domain object, but in a service class (the Façade/Repository)
ProductACriteriaPassed() is in the right place
I would recommend this:
public class AccountPersonalDetails
{
public OtherInfo OtherInfo { get; private set; }
}
public class ProductChecker
{
public ProductChecker(AccountPersonalDetails) {}
}
// and here's the important piece
public class EitherServiceOrRepository
{
public static AccountPersonalDetails GetAccountDetailsByNumber(int accountNumber)
{
// access db here
}
// you may also feel like a bit more convinience via helpers
// this may be inside ProductCheckerService, though
public static ProductChecker GetProductChecker(int accountNumber)
{
return new ProductChecker(GetAccountDetailsByNumber(accountNumber));
}
}
I'm not expert in Domain-Driven Design but I believe this is what DDD is about. You keep your logic clean of DB concerns, moving this to external services/repositories. Will be glad if somebody correct me if I'm wrong.
Whats good. It looks like you have a productChecker with a nice clear purpose. Check products. You'd refactor or alter this because your have a need to. If you don't need to, you wouldn't. Here's what I would probably do.
It "feels" clunky to create a new instance of the class for each account number. A constructor argument should be something required for the class to behave correctly. Its a parameter of the class, not a dependency. It leads to the tempation to do a lot of work in the constructor. Usage of the class should look like this:
result = new ProductChecker().ProductACriteriaPassed(accountNumber)
Which I'd quickly rename to indicate it does work.
result = new ProductChecker().PassesProductACriteria(accountNumber)
A few others have mentioned that you may want to split out the database logic. You'd want to do this if you want unit tests that are fast. Most programs want unit tests (unless you are just playing around), and they are nicer if they are fast. They are fast when you can get the database out of the way.
Let's make a dummy object representing results of the database, and pass it to a method that determines whether the product passes. If not for testibility, this would be a private. Testability wins. Suppose I want to verify a rule such as "the product must be green if the account number is prime." This approach to unit testing works great without fancy infrastructure.
// Maybe this is just a number of items.
DataRequiredToEvaluateProduct data = // Fill in data
// Yes, the next method call could be static.
result = new ProductChecker().CheckCriteria(accountNumber, data)
// Assert result
Now we need to connect the database. The database is a dependency, its required for the class to behave correctly. It should be provided in the constructor.
public class ProductRepository {} // Define data access here.
// Use the ProductChecker as follows.
result = new ProductChecker(new ProductRepository()).CheckCriteria(accountNumber)
If the constructor gets annoyingly lengthy (it probably has to read a config file to find the database), create a factory to sort it out for you.
result = ProductCheckerFactory().GimmeProductChecker().CheckCriteria(accountNumber)
So far, I haven't used any infrastructure code. Typically, we'd make the above easier and prettier with mocks and dependency injection (I use rhinomocks and autofac). I won't go into that. That is only easier if you already have it in place.
I've commonly seen examples like this on business objects:
public void Save()
{
if(this.id > 0)
{
ThingyRepository.UpdateThingy(this);
}
else
{
int id = 0;
ThingyRepository.AddThingy(this, out id);
this.id = id;
}
}
So why here, on the business object? This seems like contextual or data related more so than business logic.
For example, a consumer of this object might go through something like this...
...Get form values from a web app...
Thingy thingy = Thingy.CreateNew(Form["name"].Value, Form["gadget"].Value, Form["process"].Value);
thingy.Save();
Or, something like this for an update...
... Get form values from a web app...
Thingy thingy = Thingy.GetThingyByID(Int32.Parse(Form["id"].Value));
Thingy.Name = Form["name"].Value;
Thingy.Save();
So why is this? Why not contain actual business logic such as calculations, business specific rules, etc., and avoid retrieval/persistence?
Using this approach, the code might look like this:
... Get form values from a web app...
Thingy thingy = Thingy.CreateNew(Form["name"].Value, Form["gadget"].Value, Form["process"].Value);
ThingyRepository.AddThingy(ref thingy, out id);
Or, something like this for an update...
... get form values from a web app ...
Thingy thingy = ThingyRepository.GetThingyByID(Int32.Parse(Form["id"].Value));
thingy.Name = Form["Name"].Value;
ThingyRepository.UpdateThingy(ref thingy);
In both of these examples, the consumer, who knows best what is being done to the object, calls the repository and either requests an ADD or an UPDATE. The object remains DUMB in that context, but still provides it's core business logic as pertains to itself, not how it is retrieved or persisted.
In short, I am not seeing the benefit of consolidating the GET and SAVE methods within the business object itself.
Should I just stop complaining and conform, or am I missing something?
This leads into the Active Record pattern (see P of EAA p. 160).
Personally I am not a fan. Tightly coupling business objects and persistence mechanisms so that changing the persistence mechanism requires a change in the business object? Mixing data layer with domain layer? Violating the single responsibility principle? If my business object is Account then I have the instance method Account.Save but to find an account I have the static method Account.Find? Yucky.
That said, it has its uses. For small projects with objects that directly conform to the database schema and have simple domain logic and aren't concerned with ease of testing, refactoring, dependency injection, open/closed, separation of concerns, etc., it can be a fine choice.
Your domain objects should have no reference to persistance concerns.
Create a repository interface in the domain that will represent a persistance service, and implement it outside the domain (you can implement it in a separate assembly).
This way your aggregate root doesn't need to reference the repository (since it's an aggregate root, it should already have everyting it needs), and it will be free of any dependency or persistance concern. Hence easier to test, and domain focused.
While I have no understanding of DDD, it makes sense to have 1 method (which will do UPSERT. Insert if record doesn't exist, Update otherwise).
User of the class can act dumb and call Save on an existing record and Update on a new record.
Having one point of action is much clearer.
EDIT: The decision of whether to do an INSERT or UPDATE is better left to the repository. User can call Repository.Save(....), which can result in a new record (if record is not already in DB) or an update.
If you don't like their approach make your own. Personally Save() instance methods on business objects smell really good to me. One less class name I need to remember. However, I don't have a problem with a factory save but I don't see why it would be so difficult to have both. IE
class myObject
{
public Save()
{
myObjFactory.Save(this);
}
}
...
class myObjectFactory
{
public void Save(myObject obj)
{
// Upsert myObject
}
}