Implementing a domain service with DDD in C# - 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.

Related

Is it good design to have state-representative properties on a service class?

I have an application with a service class that retrieves database metadata from a database and returns it to calling classes.
To connect to the database, the service class methods accept a parameter that details the connection credentials.
I'm considering a change whereby the credentials would be stored within the service class. One of the reasons for this is that calling classes (which have the responsibility, for example, of comparing schemas on different servers) may connect to multiple different databases/servers, so the calling class would basically have a collection of these service classes, rather than a collection of connection credentials (e.g., IConnectionInfo in the following example).
Another thing I might like to do within the application is to have implementation of this service class (IDatabaseService in the following example) for different types of RDBMS (e.g., SQL Server, Oracle, etc.), and this seems like the best way of leaving it open to that (the information returned from the service would be very generic and applicable to all supported types of RDBMS).
Example code for what the service class might look like:
public class DatabaseService : IDatabaseService
{
private readonly IConnectionInfo ConnectionInfo;
public bool IsConnected; // INotifyPropertyChanged
public string ServerName => IConnectionInfo.ServerName;
public string DatabaseName => IConnectionInfo.DatabaseName;
public DatabaseService(IConnectionInfo connectionInfo)
{
ConnectionInfo = connectionInfo;
}
public IEnumerable<Table> GetTables()
{
...
}
public IEnumerable<Column> GetTableColumns(Table table)
{
...
}
}
There are a few reasons I'm a bit doubtful of this approach:
I'm implementing INotifyPropertyChanged within this class so that I can update the UI to show the user whether or not they are connected (e.g., I could switch this to false if any calls to the server failed). For this reason it seems to behave like a ViewModel (as opposed to a Service).
I'm unsure as to whether it's good practice to have properties on a service class that represent its state, e.g., ConnectionInfo, IsConnected.
Does the above look like an acceptable design?
Update: Further Thoughts and Explanation
I suppose the specific programming problem I'm trying to solve is that, for example, I might have a class for SQL Server credentials, and a class for Oracle credentials, both of which would be IConnectionCredentials. I would then have several corresponding implementations of IDataService, which would accept IConnectionCredentials as an argument. The issue would be that not all implementations of IDataService would work with all implementations of IConnectionCredentials, which seems flawed to me, and so I thought it would make sense to combine the data access layer and the "data accessor" object into one class. I suppose it might be feasible to have IDataService contain logic to determine which version of the "real" data access interface to use. For example:
public class DataService : IDataService
{
private readonly RealDataServiceFactory RealDataServiceFactory;
public IEnumerable<Table> GetTables(IConnectionCredentials connectionCredentials)
{
return RealDataServiceFactory.Create(connectionCredentials).GetTables(connectionCredentials);
}
}
public class RealDataServiceFactory
{
public IRealDataService Create(IConnectionCredentials connectionCredentials)
{
if (connectionCredentials is SqlServerConnectionCredentials)
{
return new SqlServerDataService();
}
else if ...
}
}
Another reason I wanted the IsConnected property in the data access class is because there are other reasons that the service might not return data other than the connection not working, and I didn't feel the logic to determine that belonged in the calling class, and so liked the idea that the data service could simultaneously return null to some call and also state to the application and UI, "there's a problem with my connection". In the above implementation, I would also lose this, though I suppose it could be achieved by the data service marking IsConnected as false on the incoming IConnectionCredentials before returning.
It's ultimately up to you what to do, but it sounds like this design conflates two (or more?) concerns into one:
User interface updates (INotifyPropertyChanged)
Data access
This gives the class more than a single reason to change. In other words, it violates the Single Responsibility Principle (SRP).
Now, no-one says that you must obey the SRP. This, and the other SOLID principles, are guidelines for dealing with certain kinds complexity. If you don't have the problems that SOLID addresses, then you don't have to follow those principles.
In practice, though, it can be hard to predict future problems. A code base is rarely problematic from the outset. It slowly devolves from something simple to something more complicated.
While the proposed design sounds like it has mixed concerns (as opposed to separation of concerns), perhaps it's benign in practice. After all, INotifyPropertyChanged is a base class library interface, so you're aren't introducing coupling to some specific technology. I'd be wary of expanding the scope of UI-related updated on that class, though.

Unit of Work through tiers

I'm refactoring an existing MVC.Net application to include the unit of work pattern to make data management a bit more obvious and straight forward.
The application is currently split into
Presentation/UI (MVC Controllers delivering views OR JsonResults for AngularJS)
Business Logic (Containing well... business logic)
DAL (Repositories and EF)
I'm having a hard time trying to figure out how I need to be structuring dependency injection and UoW passing to keep things sensible and testable.
I'm anticipating something like the following to be an example:
public class SomeMVCController : Controller
{
private readonly IStoreFrontLogic _storeFrontLogic;
public SomeMVCController(IStoreFrontLogic storeFrontLogic)
{
_storeFrontLogic = storeFrontLogic;
var uow = new UnitOfWork(User);
_storeFrontLogic.UnitOfWork = uow;
}
public ActionResult SomeRequest()
{
var myViewModel = _storeFrontLogic.OffersForUser();
return View(myViewModel);
}
}
public class StoreFrontLogic : IStoreFrontLogic
{
public UnitOfWork unitOfWork;
public OffersModel OffersForUser()
{
//some logic taking into account the current user in the uow
var prevOrders = unitOfWork.OrdersRepo.GetUsersOrders();
// special offers logic
return specialOffers;
}
}
Does this seem sensible?
I'm not too keen on the requirement to manually push the uow into my logic classes whenever they're required. Is there a more sensible way?
As I said above, this is hard to answer without a specific question or specific domain model but I'll give it a shot.
My understanding of such things is focused pretty heavily through a Domain Driven Design lens.
First of, you should read this series of papers on effective aggregate design. The fact that you need units of work and to do queries from inside your domain classes implies that your model needs work.
Some other thoughts on UOW - having uow produce your repositories is good, but I think you will likely start hitting lots of difficulties with implementation. UoW is super useful in small targeted areas but is very difficult to implement across an entire application. What for example happens when you save? Can you never use EF directly? Is everything thread safe? You might want to simplify what you are trying to achieve.
In your example uow can be scoped to the HttpRequest. Many IoC containers (eg Structuremap) provide a simple way to configure this. You can then have a post-action filter (or even better an OWIN module) to attempt the commit (what happens if there are errors is yet another implementation difficulty to deal with). This will eliminate a lot of the property-assignment nonsense
I'm not sure what type of object is your StoreFrontLogic. It doesn't seem like a domain entity but it contains significant business logic. It could be something similar to a transaction script, but in that case the uow should be fully internal to it.
Is it a stateless service? In that case everything that method uses - orders for user included - should be passed in via a parameter.
If, on the other hand it's an entity then it shouldn't access the database at all, it should already have all orders for the user. Purposeful database denormalization can help quite a bit here.
At the very least pass uow as a parameter to OffersForUser rather than expecting for a property to be set.

Should factories set model properties?

As part of an overall S.O.L.I.D. programming effort I created a factory interface & an abstract factory within a base framework API.
People are already starting to overload the factories Create method. The problem is people are overloading the Create method with model properties (and thereby expecting the factory to populate them).
In my opinion, property setting should not be done by the factory. Am I wrong?
public interface IFactory
{
I Create<C, I>();
I Create<C, I>(long id); //<--- I feel doing this is incorrect
IFactoryTransformer Transformer { get; }
IFactoryDataAccessor DataAccessor { get; }
IFactoryValidator Validator { get; }
}
UPDATE - For those unfamiliar with SOLID principles, here are a few of them:
Single Responsibility Principle
It states that every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class
Open/Closed Principle
The meaning of this principle is that when a get a request for a feature that needs to be added to your application, you should be able to handle it without modifying old classes, only by adding subclasses and new implementations.
Dependency Inversion Principle
It says that you should decouple your software modules. To achieve that you’d need to isolate dependencies.
Overall:
I'm 90% sure I know the answer. However, I would like some good discussion from people already using SOLID. Thank you for your valuable opinions.
UPDATE - So what do I think a a SOLID factory should do?
IMHO a SOLID factory serves-up appropriate object-instances...but does so in a manner that hides the complexity of object-instantiation. For example, if you have an Employee model...you would ask the factory to get you the appropriate one. The DataAccessorFactory would give you the correct data-access object, the ValidatorFactory would give you the correct validation object etc.
For example:
var employee = Factory.Create<ExxonMobilEmployee, IEmployee>();
var dataAccessorLdap = Factory.DataAccessor.Create<LDAP, IEmployee>();
var dataAccessorSqlServer = Factory.DataAccessor.Create<SqlServer, IEmployee>();
var validator = Factory.Validator.Create<ExxonMobilEmployee, IEmployee>();
Taking the example further we would...
var audit = new Framework.Audit(); // Or have the factory hand it to you
var result = new Framework.Result(); // Or have the factory hand it to you
// Save your AuditInfo
audit.username = 'prisonerzero';
// Get from LDAP (example only)
employee.Id = 10;
result = dataAccessorLdap.Get(employee, audit);
employee = result.Instance; // All operations use the same Result object
// Update model
employee.FirstName = 'Scooby'
employee.LastName = 'Doo'
// Validate
result = validator.Validate(employee);
// Save to SQL
if(result.HasErrors)
dataAccessorSqlServer.Add(employee, audit);
UPDATE - So why am I adamant about this separation?
I feel segregating responsibilities makes for smaller objects, smaller Unit Tests and it enhances reliability & maintenance. I recognize it does so at the cost of creating more objects...but that is what the SOLID Factory protects me from...it hides the complexity of gathering and instantiating said objects.
I'd say it's sticking to DRY principle, and as long as it's simple values wiring I don't see it being problem/violation. Instead of having
var model = this.factory.Create();
model.Id = 10;
model.Name = "X20";
scattered all around your code base, it's almost always better to have it in one place. Future contract changes, refactorings or new requirements will be much easier to handle.
It's worth noting that if such object creation and then immediately properties setting is common, then that's a pattern your team has evolved and developers adding overloads is only a response to this fact (notably, a good one). Introducing an API to simplify this process is what should be done.
And again, if it narrows down to simple assignments (like in your example) I wouldn't hesitate to keep the overloads, especially if it's something you notice often. When things get more complicated, it would be a sign of new patterns being discovered and perhaps then you should resort to other standard solutions (like the builder pattern for example).
Assuming that your factory interface is used from application code (as opposed to infrastructural Composition Root), it actually represents a Service Locator, which can be considered an anti-pattern with respect to Dependency Injection. See also Service Locator: roles vs. mechanics.
Note that code like the following:
var employee = Factory.Create<ExxonMobilEmployee, IEmployee>();
is just syntax sugar. It doesn't remove dependency on concrete ExxonMobilEmployee implementation.
You might also be interested in Weakly-typed versus Strongly-typed Message Channels and Message Dispatching without Service Location (those illustrate how such interfaces violate the SRP) and other publications by Mark Seemann.
After about 6 months of experience in Dependency Injection, I've only discovered few cases where factories should set properties:
If the setter is marked as internal, and the properties are expected to be set once by the factory only. This usually happens on interfaces with only getter properties whose implementations are expected to be created thru a factory.
When the model uses property injection. I rarely see classes that use property injection (I also try to avoid building these), but when I do see one, and the needed service is only available elsewhere, it's a case where you have no choice.
For the bottom line, leave public setters out of factories. Only set properties that are marked as internal Let the clients decide on what properties they need to set if they are allowed to do so. This will keep your factories clean of unneeded functions.

Trying to simplify our repository pattern

Currently we have implemented a repository pattern at work. All our repositories sit behind their own interfaces and are mapped via Ninject. Our project is quite large and there are a couple quirks with this pattern I'm trying to solve.
First, there are some controllers where we need upwards of 10 to 15 repositories all in the same controller. The constructor gets rather ugly when asking for so many repositories. The second quirk reveals itself after you call methods on multiple repositories. After doing work with multiple repositories we need to call the SaveChanges method, but which repository should we call it on? Every repository has one. All repositories have the same instance of the Entity Framework data context injected so picking any random repository to call save on will work. It just seems so messy.
I looked up the "Unit Of Work" pattern and came up with a solution that I think solves both problems, but I'm not 100% confident in this solution. I created a class called DataBucket.
// Slimmed down for readability
public class DataBucket
{
private DataContext _dataContext;
public IReportsRepository ReportRepository { get; set; }
public IEmployeeRepository EmployeeRepository { get; set; }
public IDashboardRepository DashboardRepository { get; set; }
public DataBucket(DataContext dataContext,
IReportsRepository reportsRepository,
IEmployeeRepository employeeRepository,
IDashboardRepository dashboardRepository)
{
_dataContext = dataContext;
this.ReportRepository = reportsRepository;
this.EmployeeRepository = employeeRepository;
this.DashboardRepository = dashboardRepository;
}
public void SaveChanges()
{
_dataContext.SaveChanges();
}
}
This appears to solve both issues. There is now only one SaveChanges method on the data bucket itself and you only inject one object, the data bucket. You then access all the repositories as properties. The data bucket would be a little messy looking since it would be accepting ALL (easily 50 or more) of our repositories in its constructor.
The process of adding a new repository would now include: creating the interface, creating the repository, mapping the interface and repository in Ninject, and adding a property to the data bucket and populating it.
I did think of an alternative to this that would eliminate a step from above.
public class DataBucket
{
private DataContext _dataContext;
public IReportsRepository ReportRepository { get; set; }
public IEmployeeRepository EmployeeRepository { get; set; }
public IDashboardRepository DashboardRepository { get; set; }
public DataBucket(DataContext dataContext)
{
_dataContext = dataContext;
this.ReportRepository = new ReportsRepository(dataContext);
this.EmployeeRepository = new EmployeeRepository(dataContext);
this.DashboardRepository = new DashboardRepository(dataContext);
}
public void SaveChanges()
{
_dataContext.SaveChanges();
}
}
This one pretty much eliminates all the repository mappings in Ninject because they are all instantiated in the data bucket. So now the steps to adding a new repository include: Create interface, create repository, add property to data bucket and instantiate.
Can you see any flaws with this model? On the surface it seems much more convenient to consume our repositories in this way. Is this a problem that has been addressed before? If so, what is the most common and/or most efficient approach to this issue?
First, there are some controllers where we need upwards of 10 to 15 repositories all in the same controller.
Say hello to Abstract factory pattern. Instead of registering all repositories in Ninject and injecting them to controllers register just single implementation of the factory which will be able to provide any repository you need - you can even create them lazily only if the controller really needs them. Than inject the factory to controller.
Yes it also has some disadvantages - you are giving controller permission to get any repository. Is it problem for you? You can always create multiple factories for some sub systems if you need or simply expose multiple factory interfaces on single implementation. It still doesn't cover all cases but it is better than passing 15 parameters to constructor. Btw. are you sure those controllers should not be split?
Note: This is not Service provider anti-pattern.
After doing work with multiple repositories we need to call the SaveChanges method, but which repository should we call it on?
Say hello to Unit of Work pattern. Unit of Work is logical transaction in your application. It persists all changes from logical transaction together. Repository should not be responsible for persisting changes - the unit of work should be. Somebody mentioned that DbContext is implementation of Repository pattern. It is not. It is implementation of Unit of Work pattern and DbSet is implementation of Repository pattern.
What you need is central class holding the instance of the context. The context will be also passed to repositories because they need it to retrieve data but only the central class (unit of work) will offer saving changes. It can also handle database transaction if you for example need to change isolation level.
Where should be unit of work handled? That depends where your logical operation is orchestrated. If the operation is orchestrated directly in controller's actions you need to have unit of work in the action as well and call SaveChanges once all modifications are done.
If you don't care about separation of concerns too much you can even combine unit of work and factory into single class. That brings us to your DataBucket.
I think you are absolutely right to use the Unit of Work pattern in this case. Not only does this prevent you from needing a SaveChanges method on every repository, it provides you a nice way to handle transactions from within code rather than in your database itself. I included a Rollback method with my UOW so that if there was an exception I could undo any of the changes the operation had already made on my DataContext.
One thing you could do to prevent weird dependency issues would be to group related repositories on their own Unit of Work, rather than having one big DataBucket that holds every Repository you have (if that was your intent). Each UOW would only need to be accessible at the same level as the repositories it contained, and other repositories should probably not depend on other UOWs themselves (your repositories shouldn't need to use other repositories).
If wanted to be an even bigger purist of the pattern, you could also structure your UOWs to represent just that, a single Unit of Work. You define them to represent a specific operation in your domain, and provide it with the repositories required to complete that operation. Individual repositories could exist on more than one UOW, if it made sense to be used by more than one operation in your domain.
For example, a PlaceCustomerOrderUnitOfWork may need a CustomerRepository, OrderRepository, BillingRepository, and a ShippingRepository
An CreateCustomerUnitOfWork may need just a CustomerRepository. Either way, you can easily pass that dependency around to its consumers, more fine grained interfaces for your UOW can help target your testing and reduce the effort to create a mock.
The notion of every repository having a SaveChanges is flawed because calling it saves everything. It is not possible to modify part of a DataContext, you always save everything. So a central DataContext holder class is a good idea.
Alternatively, you could have a repository with generic methods that can operate on any entity type (GetTable<T>, Query<T>, ...). That would get rid of all those classes and merge them into one (basically, only DataBucket remains).
It might even be the case that you don't need repositories at all: You can inject the DataContext itself! The DataContext by itself is a repository and a full fledged data access layer. It doesn't lend itself to mocking though.
If you can do this depends on what you need the "repository" do provide.
The only issue with having that DataBucket class would be that this class needs to know about all entities and all repositories. So it sits very high in the software stack (at the top). At the same time it is being used by basically everything so it sits at the bottom, too. Wait! That is a dependency cycle over the whole codebase.
This means that everything using it and everything being used by it must sit in the same assembly.
What I have done in the past was to create child injection containers (I was using Unity) and register a data context with a ContainerControlledLifetime. So that when the repositories are instantiated, they always have the same data context injected into them. I then hang on to that data context and when my "Unit of Work" is complete, I call DataContext.SaveChanges() flushing all the changes out to the database.
This has some other advantages such as (with EF) some local caching, such that if more than one repository needs to get the same entity, only the first repository actually causes a database round trip.
It's also a nice way to "batch up" the changes and make sure they execute as a single atomic transaction.

C# Design Questions [closed]

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.

Categories

Resources