C# Design Questions [closed] - c#

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.

Related

Implementing a domain service with DDD in C#

I'm working on a domain model writing my software all DDD and stuff doing a great job, when I suddenly bump into the same problem I have been facing over and over again and now it's time to share some insights. The root of the problem lies in the uniqueness of data.
For example, let's say we're writing this awesome domain model for a user. Obviously the username is unique and just to be as flexible as possible we want the user to be able to change his name, so I implemented the following method:
public void SetUsername(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
throw new UserException(UserErrorCode.UsernameNullOrEmpty,
"The username cannot be null or empty");
}
if (!Regex.IsMatch(value, RegularExpressions.Username))
{
throw new UserException(UserErrorCode.InvalidUsername,
"The username {value} does not meet the required ");
}
if (!Equals(Username, value))
{
Username = value;
SetState(TrackingState.Modified);
}
}
Again, this is all fine and fancy, but this function lacks the ability to check if the username is unique or not. So writing all these nice articles about DDD, this would be a nice use-case for a Domain Service. Ideally, I would inject that service using dependency injection but this ruins the constructor of my domain model. Alternatively, I can demand an instance of a domain service as a function argument like so: public void SetUsername(string value, IUsersDomainService service) and to be honest I don't see any solid alternatives.
Who has faced this problem and maybe came up with a nice rock-solid solution?
I agree with #TomTom. But as most times with software decisions, it depends, there is almost always a tradeoff. As a rule of thumb, you gain more by not injecting a domain service into an entity. This is a common question when one is starting with DDD and CQRS+ES. And has been thoroughly discussed in the CQRS mailing list here
However, there are some cases where the approach you suggested (known as method injection) might be beneficial it depends on the scenario. I’ll try and drive some analysis points next.
Consider the case where you want to make some validation before creating an entity. Let's think of a hypothetical and way oversimplified international banking context, with the following entity:
public class BankNote
{
private BankNote() {}
public static FromCurrency(
Currency currency,
ISupportedCurrencyService currencyService)
{
currencyService.IsAvailable(currency);
}
}
I am using the factory method pattern FromCurrency inside your entity to abstract the entity creation process and add some validation so that the entity is always created in the correct state.
Since the supported currencies might change overtime, and the logic of which currencies are supported is a different responsibility than the bank note issuing logic, injecting the ISupportedCurrencyService in the factory method gives us the following benefits:
By the way, the method dependency injection for domain services is suggested in the book: Hands-On Domain-Driven Design with .NET Core
By Alexey Zimarev. Chapter 5 "Implementing the Model" page 120
Pros
The BankNote is always created with a supported Currency, even if the currencies supported change overtime.
Since we are depending on an interface instead of a concrete implementation, we can easily swap and change the implementation without changing the entity.
The service is never stored as an instance variable of the class, so no risk of depending on it more than we need.
Cons
If we keep going this way we might add a lot of dependencies injected into the entity and it will become hard to maintain overtime.
We still are adding a loosely coupled dependency to the entity and hence the entity now needs to know about that interface. We are violating the Single Responsibility Principle, and now you would need to mock the ISupportedCurrencyService to test the factory method.
We can’t instantiate the entity without depending on a service implemented externally from the domain. This can cause serious memory leak and performance issues depending on the scenario.
Another approach
You can avoid all the cons if you call the service before trying to instantiate the entity. Say having a different class for the factory instead of a factory method, and make that separate factory use the ISupportedCurrencyService and only then call the entity constructor.
public class BankNoteFactory
{
private readonly ISupportedCurrencyService _currencyService;
private BankNoteFactory(
ISupportedCurrencyService currencyService)
=> _currencyService = currencyService;
public BankNote FromCurrency(
Currency currency)
{
if(_currencyService.IsAvailable(currency))
return new BanckNote(currency);
// To call the constructor here you would also need
// to change the constructor visibility to internal.
}
}
Using this approach you would end with one extra class and an entity that could be instantiated with unsupported currencies, but with better SRP compliance.

Correct implementation of UnitOfWork and Repository pattern in Entity Framework

I am trying to figure out how to correctly implement UoW and Repository pattern with Entity Framework. I saw a lot of post against it but it still seems like the right way to go.
I am trying to do it according to this blog post. The last thing I am trying to figure out is how to inject the Repositories into the UoW but in a way that lets me do it on demand. The number of repositories may grow and so will the constructor then. Furthermore instantiating all of the repositories for an operation that may require only 1 or 2 seems like a waste of resources.
How do I do it in a way that lets me write unit tests fairly easily?
The only way I found out, that lets me inject repositories NOT in the constructor (so they are not all instantiated, even when they are not needed for a particular operation) is by doing it in the getter:
private IGenericRepository<Blog> _blogRepository;
private IGenericRepository<Post> _postRepository;
public UnitOfWork(BloggingContext bloggingContext)
{
_bloggingContext = bloggingContext;
}
public IGenericRepository<Blog> BlogRepository
{
get
{
return _blogRepository = _blogRepository ?? new GenericRepository<Blog>(_bloggingContext);
}
}
However, this approach generates a lot of noise in the code because when I will have 50 repositories I will need 50 props.
You might want to combine the described approach (which I like) with the generic repository approach described here https://cpratt.co/truly-generic-repository/
Given proper implementation of the UoW pattern from the blog post you reference, you won't need the anything but the IReadOnlyRepository from the article - it will provide everything you need for the repository to be.

Mock NHibernate IQueryOverOrderBuilder object

So I'm trying to write some test cases for my business logic layer. I've already mocked up my data access layer (which returns NHibernate IQueryOver objects). I created a MockQueryOver class that implements the IQueryOver interface because I chain functions in the business logic layer so creating a stubbed IQueryOver didn't make sense to me.
Anyway, that all works, but the problem I'm having is when I try to do an OrderBy() on the QueryOver. In my MockQueryOver class, I implement the OrderBy() method like this right now:
public IQueryOverOrderBuilder<TRoot, TSubType> OrderBy(Expression<Func<TSubType, object>> path)
{
var func = path.Compile();
IList<TSubType> result = m_data.OrderBy(func).ToList();
var mockRepo = new MockRepository();
var queryOver = new MockQueryOver<TRoot, TSubType>(m_data);
IQueryOverOrderBuilder<TRoot, TSubType> mockOrderBuilder = mockRepo.StrictMock<IQueryOverOrderBuilder<TRoot, TSubType>>(queryOver, path);
mockOrderBuilder.Stub(x => x.Desc).Return(queryOver);
mockOrderBuilder.Stub(x => x.Asc).Return(queryOver);
return mockOrderBuilder;
}
The problem is that RhinoMocks throws an exception on any of the Stub methods. This is the exception:
System.NullReferenceException : Object reference not set to an instance of an object.
at NHibernate.Criterion.Lambda.QueryOverOrderBuilderBase`3.AddOrder(Func`2 orderStringDelegate, Func`2 orderDelegate)
at NHibernate.Criterion.Lambda.QueryOverOrderBuilderBase`3.get_Desc()
at NHibernate.Criterion.QueryOverBuilderExtensions.Desc(IQueryOverOrderBuilder`2 builder)
at BLL.Tests.Mock_Objects.MockQueryOver`2.<OrderBy>b__7(IQueryOverOrderBuilder`2 x) in MockQueryOverSubType.cs: line 239
I'm new to NHibernate and RhinoMocks, so I'm not sure what it's doing behind the scenes, but it seems like even though I'm creating a mock of an interface, it still calls concrete extension methods when I try to stub a method.
Can someone please clarify this or help me out with this problem? Also, since I'm just beginning to write these test cases, I don't mind switching mocking frameworks, as long as it's free to use.
Thanks a lot!
Are you certain IQueryOverOrderBuilder is an interface? It seems to be a confusingly-named class that implements QueryOverOrderBuilderBase. I'm not entirely sure what the behaviour is in this situation, but I think your StrictMock of IQueryOverOrderBuilder is actually calling through to that base class, which probably isn't set up, and is throwing the exception you're seeing.
I think that perhaps you might need add another abstraction layer in between your business logic and NHibernate, with classes that you can reliably mock. I don't think there's a way of mocking a concrete class like IQueryOverOrderBuilder with RhinoMocks (but I'm happy to be corrected if there is :).
To create another abstraction layer, analyse the operations in your business logic that currently interact with NHibernate, and define a new interface of functions to encapsulate those operations (say, IRepository). Code that adds something to the database through NHibernate might become a function on the interface named AddItem. Move the code that interacts with NHibernate behind this interface into new functions on a new class (there's no reason why it needs to be a single class - you could group logically-related code into separate classes with separate interfaces). The new interface might be able to reference some NHibernate classes and interfaces that can be easily instantiated or mocked, respectively (ideally, the interface wouldn't reference NHibernate at all, but you're doing this for testing, not to fully decouple your code from NHibernate, so it's fine). Once you've done this, your business logic can be unit-tested against a mock (or mocks) of the new interface, and the class or classes that implement that interface can be integration tested against an actual database. This is, loosely, the Adapter pattern. Without seeing exactly what your business logic does, it's difficult to comment further on the design. I hope this is helpful.
Finally, if you're creating your own MockRepository, I think you need to call Replay() on the mocks you create (or ReplayAll() on the MockRepository) after you stub them. You don't need to do this if you create your mocks from the static methods on MockRepository. Seems unrelated to your current issue (although, try calling it after your Stub calls and see if it makes any difference), but I thought I'd mention it anyway.

How can I avoid adding getters to facilitate unit testing?

After reading a blog post mentioning how it seems wrong to expose a public getter just to facilitate testing, I couldn't find any concrete examples of better practices.
Suppose we have this simple example:
public class ProductNameList
{
private IList<string> _products;
public void AddProductName(string productName)
{
_products.Add(productName);
}
}
Let's say for object-oriented design reasons, I have no need to publicly expose the list of products. How then can I test whether AddProductName() did its job? (Maybe it added the product twice, or not at all.)
One solution is to expose a read-only version of _products where I can test whether it has only one product name -- the one I passed to AddProductName().
The blog post I mentioned earlier says it's more about interaction (i.e., did the product name get added) rather than state. However, state is exactly what I'm checking. I already know AddProductName() has been called -- I want to test whether the object's state is correct once that method has done its work.
Disclaimer: Although this question is similar to
Balancing Design Principles: Unit Testing, (1) the language is different (C# instead of Java), (2) this question has sample code, and (3) I don't feel the question was adequately answered (i.e., code would have helped demonstrate the concept).
Unit tests should test the public API.
If you have "no need to publicly expose the list of products", then why would you care whether AddProductName did its job? What possible difference would it make if the list is entirely private and never, ever affected anything else?
Find out what affect AddProductName has on the state that can be detected using the API, and test that.
Very similar question here: Domain Model (Exposing Public Properties)
You could make your accessors protected so you can mock or you could use internal so that you can access the property in a test but that IMO would be wrong as you have suggested.
I think sometimes we get so caught up in wanting to make sure that every little thing in our code is tested. Sometime we need to take a step back and ask why are we storing this value, and what is its purpose? Then instead of testing that the value gets set we can then start testing that the behaviour of the component is correct.
EDIT
One thing you can do in your scenario is to have a bastard constructor where you inject an IList and then you test that you have added a product:
public class ProductNameList
{
private IList<string> _products;
internal ProductNameList(IList<string> products)
{
_products = products;
}
...
}
You would then test it like this:
[Test]
public void FooTest()
{
var productList = new List<string>();
var productNameList = new ProductNameList(productList);
productNameList.AddProductName("Foo");
Assert.IsTrue(productList[0] == "Foo");
}
You will need to remember to make internals visable to your test assembly.
Make _products protected instead of private. In your mock, you can add an accessor.
To test if AddProductName() did it's job, instead of using a public getter for _ProductNames, make a call to GetProductNames() - or the equivalent that's defined in your API. Such a function may not necessarily be in the same class.
Now, if your API does not expose any way to get information about product names, then AddProductName() has no observable side effects (In which case, it is a meaningless function).
If AddProductName() does have side effects, but they are indirect - say, a method in ProductList that writes the list of product names to a file, then ProductList should be split into two classes - one that manages the list, and the other that calls it's Add and Get API, and performs side effects.

How to initialize a class?

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).

Categories

Resources