where to put entity related methods? - c#

Asp.net-mvc, using nhibernate.
my vs.net layout is like:
/dao (1 class per entity for database work, using repository)
/model
/mappings
/factory (db factory that provides access to each entities Dao)
Now I need utility methods, not sure where to put them.
example:
CartItems.cs
CartIemsDao.cs
Now say I have a method like:
IList<CartItem> items = CartItemsDao.GetById(234)
Now I want to create a method that populates a Dictionary<int,CartItem> from a given IList<CartItem>. Should I create a CartItemManager.cs for this?
And what would a 'Service' type class be used for? e.g. CartService.cs
I believe someone said earlier a 'service' type class is to wrap multiple calls/logic for Dao's etc. Is that what it is?

There are several styles, you can definitely create a "helper" type that has all the static methods you need but this is not very discoverable from an API standpoint.
I would create these static methods on the data access objects themselves - this is much easier to discover. Of course nothing is stopping you from delegating the implementation of these static methods to some internal helper type.
Also as a side note: I don't personally care for the style of appending "DAO" or other similar identifiers to the names of types. The type is what it is so I would suggest that you leave off the "DAO" (but that has nothing to do with your question).

I would say that what you describe is a "Service", which I usually define loosely as [potentially] any operations I might want to make on entities that don't really fit into the entity itself (which practically by definition includes cross-aggregate operations).
To state it generally, you want transform a list of items into a dictionary of items using some function upon the item to derive the key.
With .Net generic typing, you could make a service for this so general it would fit best in a utility type of library that fits into the infrastructure layer where any other layer can utilize it.
public class CollectionToDictionaryMappingService {
IDictionary<TKey, TValue> Map<TKey, TValue>(ICollection <TValue> items, Func<TKey, TValue> keyAccessor)
{
var dictionary = new Dictionary<TKey, TValue>();
foreach (TValue val in items) {
dictionary.Add(keyAccessor(val), val);
}
return dictionary;
}
}

I propose to view it from a layered architecture point of view.
App layers
It depends how are you architecturing you app. I generally use two diferents layers for DAO and for Business/Logic.
In an information system logic layer generally replicates the methods of DAO, because the methods needed for implementing the use cases are get data / update data... much the same that the DAO layer. BUT I think it's important to separate them because you can add extra logic in the logic/business layer, things more complex (or composite) than the DAO.
List -> Dictionary case
I don't know if you need that method for business logic. If it's the case maybe the method can be private to some business class that uses it. Or it can be a public method of a protected helper class in the business layer.
If it's not the case I'd publish it in the business layer anyway.
BUT, if I follow the layered point of view... The service layer should provide methods for implementing the use cases. It is: it should provide the data structures needed. in this case: it should provide the dictionary.
So:
the convert method should be private to the business layer
or
be a generic conversion method like the proposed by qstarin

Related

repo method naming convention

I'm creating a reference model for the Repository layer in a new app. I'm starting with UserRepository. I like the idea of following a CRUD (Create-Read-Update-Delete) naming convention at the repo level. This feels natural for the GetById method:
public User Read(int userId)
It seems to feel less natural for the Search method:
public List<User> Read(UserQuery query)
Do you ever try to follow a CRUD naming convention for your repositories? Would you define a Search method signature in the way I defined my second method signature above or would you follow a different naming convention?
I like to give my repositories collection semantics. Something along the lines of Add(), Remove() and a series of Get()'s.
Not necessarily Update(), since it doesn't make a lot of sense to tell a collection to update an element, you usually get the object from the collection then modify it directly instead.
This comes from a Domain Driven Design perspective where the original definition of a Repository is an illusion of an in-memory collection. The repository interface is defined in the Domain layer, so it is not supposed to have any reference to persistence-related things.
To put it simply, a Repository is just a bag of things that you can look into, add to and remove from.
Search() fits perfectly in this vision. You can also use the Specification pattern to make search criteria more fluent and reusable.

How to keep a one-to-one relationship between polymorphic classes in different layers?

I have a domain logic layer in which an abstract superclass exists, let's call it DomainAbstractClass.
Many concrete classes inherit from this class, let's call them ConcreteDomainClass1, ConcreteDomainClass2 and so on.
Now, in a different assembly, which is my presentation logic layer, I have a similar hierarchy in which an abstract super class, let's call it PresentationAbstractClass, is implemented by many concrete classes ConcretePresentationClass1, ConcretePresentationClass2 and so on.
There is a natural one-to-one relationship between ConcreteDomainClass1 and ConcretePresentationClass1, ConcreteDomainClass2 and ConcretePresentationClass2, etc... since the presentation classes encapsulate the specific presentation logic of each specific domain entity.
Since I want to keep my domain logic layer as dependency free as possible, my presentation logic layer has a reference to the domain logic layer, but not the other way around.
Now, the presentation logic layer calls a method in the domain logic layer that returns an AbstractDomainClass, and I need to create the appropiate ConcretePresentationClassN according to the ConcreteDomainClassN that the abstract domain class really is.
Is there a creational pattern that allows me to accomplish this without having to resort to this ugly thing?
if(abstractClass is ConcreteDomainClass1)
new ConcretePresentationClass1();
else if (abstractClass is ConcreteDomainClass2)
new ConcretePresentationClass2();
// ... and so on
I'd suggest using the factory pattern by wrapping the whole thing up in a simple factory method and use a dictionary to map between the classes:
private Dictionary<Type, Func<DomainAbstractClass, PresentationAbstractClass>> factory =
new Dictionary<Type, Func<DomainAbstractClass, PresentationAbstractClass>>
{
{ typeof(ConcreteDomainClass1), (x) => new ConcretePresentationClass1(x) },
{ typeof(ConcreteDomainClass2), (x) => new ConcretePresentationClass2(x) },
....
};
public PresentationAbstractClass ObtainPresentationClassFromDomainClass(DomainAbstractClass domainClass)
{
return factory[domainClass.GetType()](domainClass);
}
The situation is as follows:
---Presentation layer--- ---Domain layer--- ---Repository layer---
1. --- control flow ---> --- control flow---> --- control flow---
2. --- creation of PO--- <-- creation of DO -- <----- data -----|
where creation of DO is the creation of a particular domain object, and creation of PO is the creation of a particular presentation object, which depends on domain object type, which depends on the data.
Unavoidably, this chain of dependencies makes the type of the desired presentation object dependent transitively on the data. This is somehow a normal case, but the creation control flow here seems to be some kind of an ill-conditioning for this pattern. Usually the "creation chain" is like this: a View instantiates (or references) a ViewModel which references a particular Model.
Thus the only solution (not considering redesign) is to use some kind of registry/factory which create appropriate presentation object depending on domain object's type. Which unfortunately is equivalent to switching on object's type.
Your question is a bit unclear. What I get is that you want to create a presentation class, based on input from another presentation class, that is being processed by domain class.
If you want it to be magically resolved / generated, there are some IOC Container out there who can help you to resolve the concrete class by logic and configuration (AutoFac, Simple Injector, Castle Windsor, etc). However I don't has any experience so I cannot share much (but I know those container has the ability for the configuration).
For your starting point, the technique is named Convention over Configuration, used by Asp.Net MVC controller - view resolver.
However, this is the manual logic by using reflection:
public AbstractFactory{
public AbstractFactory (IConfiguration config){
this.presentationClassNameSpace = config.PresentationClassNameSpace;
}
private readonly string presentationClassNameSpace;
public AbstractPresentationClass Resolve(Type t){
string className = t.Name;
className = className.Replace("Domain", "Presentation");
AbstractPresentationClass resultClass =
(AbstractPresentationClass) System.Activator.CreateInstance(
Type.GetType(presentationClassNameSpace + "." + className);
return resultClass;
}
}
Note:
You can use generic type instead of Type t if you want to inject the AbstractDomainClass, and based on the injected object you get the type by GetType();. The advantage is you can create another abstract factory with specific method from give concrete domain class.
Or you can inject AbstractDomainClass instead and get the type by GetType();.
You can use generic at method level to resolve the type as you wish if you want, however I do not recommend it.

One big repository vs. many little ones?

I have several product tables in my database:
ProductTypes
ProductCategories
ProductCategoryItems
ProductInventory
The way I see it now, I can make IProduct which would have methods such as:
FindAllTypes()
FindAllCategories(int typeId)
FindAllItems(int categoryId)
Or, I can separate each to mimic the table structure: IProductType, IProductCategory, etc.
Is there a reason to go with one over another?
The idea of repositories is to delegate each one with responsibility for a single entity. In this case making a repository for each entity is recommended. You can go for the big repository one as well, but is not the best solution. In the end you'll get a HUGE class with lots of methods and really tight coupled. Also difficult to give maintenance to.
I don't think having a huge repository is really a good idea, then you'd basically have a data access god class that does everything.
I like to have a base Repository<T> which does common operations such as GetById and GetAll. I normally have all my repositories inherit this base class to get the common methods for free, so I don't have to keep rewriting the same code.
In my opinion it very much depends on the business domain model, it's very important to determine what are your main business entities. Not necessarily every table in the DB is directly mapped to a business entity. Tables are just representations of your one or many entities in a normalized way for relational databases.
Try to picture your domain model beyond the restrictions of normalized relational databases, is there really more than one business concept? Repositories should be constructed around solid, whole, first-class business entities.
My advice would be to have an IProductRepository with the necessary methods to implement CRUD operations and grow it as needed. You don't want to get too ambitious interfaces beacuse you may not need most of it, and it could be a burden. The important thing about interfaces is to decouple your code from the persistence schema, so you can latter offer the flexibility to switch between them.
Maybe in the future the business will need to evolve to a more detailed representation of -for instance- the product's providers, and in that moment you'll use your good judgement to decide wether that represents an important business entity worthy of a dedicated repository or not.
Hope this helps.
I disagree with the others (edit: except with Isaac). The small repositories are a facade (not the pattern).
If the entity types are coupled (have navigation properties to each other) then they are not really separatable.
Modifying one entity type and committing the changes may commit change to others.
Also, you can not create any small repository above the same unit of work,
since the ORM only has a limited amount of entities mapped to the database.
Divide your model into separatable domains and create one specific unit of work for each domain.
On these unit of works create aggregate roots for each entity type that you may require immediate access to.
Each root should have specifically typed add, remove, getbykeys, query and etc methods.
The unit of work should have the commitchanges and alike methods on it.
Each of the roots is similar to the small repositories the others mentioned, however, the unit of work is the real medium sized repository (of which your model may have more than one type of).
Example:
// Create one of these
interface IUnitOfWork
{
void Commit();
}
// Create one of these
interface IEntitySet<TEntity> where TEntity : class
{
void Add(TEntity entity);
void Remove(TEntity entity);
TEntity Create<TSpecificEntity>() where TSpecificEntity : TEntity;
IQueryable<TEntity> Query();
}
// Create one of these per entity type
interace IEntitySetOfTEntity1 : IEntitySet<Entity1>
{
TEntity1 GetByKeys(int key1);
}
interace IEntitySetOfTEntity2 : IEntitySet<Entity2>
{
TEntity1 GetByKeys(short key1, short key2);
}
// Create one of these per separatable domain
interface IDomain1UnitOfWork : IUnitOfWork
{
IEntitySetOfTEntity1 Entity1s
{
get;
}
IEntitySetOfTEntity2 Entity2s
{
get;
}
}
All these interfaces and their implementations can be auto-generated.
These interfaces and their implementations are very light weight and by no means are any of them "a HUGE class with lots of methods". Since they can be auto-generated, maintenance is easy.
Specific functionalities can be added to the interfaces IDomain1UnitOfWork, IEntitySetOfTEntity1 and alike by using:
a. extension methods
b. partial interfaces and classes (less recommended, since this results in a less clean DAL)
The IEntitySetOfTEntity1 like interfaces can be disgarded if you use extension methods to add the GetByKeys() methods to IEntitySet<Entity1>.

Is this physical collection class that contains only static methods an Anti-Pattern?

I'm trying to figure out if I should continue on with a current pattern in an application I'm working in, or refactor this into something else.
I have a set of collection classes off a generic base of List. These classes have public constructors but contain only static methods that return collections. They look like this:
public class UserObjCollection : BaseCollection<UserObj>
{
public static UserObjCollection GetAllUserObj()
{
UserObjCollection obj = new UserObjCollection();
obj.MapObjects(new UserObjDataService().GetAllUserObj());
return obj;
}
}
Is this a Pattern or Anti-Pattern and what are the merits of this over a straight factory pattern?
EDIT: I'm leaning towards removing these physical collections, and moving their static methods into the data access layer (UserObjDataService). There are a lot of object types so I need to keep the code in seprate places, but they almost all have a 1 to 1 factory object in the datalayer.
UserObjCollection does not add anything to BaseCollection<UserObj>, objects of both classes are identical, functionality wise. It would be nicer to remove UserObjCollection and put GetAllUserObj() in BaseCollection<T> (Factory Method). You can also put GetAllUserObj() in a seperate static class. I don't think the abstract factory pattern is necessary here, as you're not creating different object families.
The reason why I would remove UserObjCollection is because this class might cause other developers to add to it without thinking it through. If it later turns out that UserObjCollection is in fact sufficiently different from BaseCollection<UserObj> that it warrants a separate class, you can re-add UserObjCollection then.
I tend to call this factory method pattern (possibly incorrectly).
Because I am doing only Test Driven Development these days, I tend to avoid it, because it is very difficult to test. In your static method you create a lot of concrete classes, so you can't really mock any of these objects. Moreover you can't mock the whole static method either, which makes all the classes fairly tightly coupled. A straight factory patterns would at least allow to mock the whole factory object, which makes testing much easier.

DAL Design/Load methods with NHibernate

public MyClass(int someUniqueID)
{
using(//Session logic)
{
var databaseVersionOfMyClass = session.CreateCriteria(/*criteria*/)
.UniqueResult<MyClass>();
//Load logic
}
}
The code sample above is my current direction, although I've reached a point where I need a bit of a sanity check.
With NHibernate(I'm green in this area), is it common or best practice to instantiate an object from a database within the class constructor? The alternative I believe, would be to have a static method that returns the object from the database.
I've also come across a relevent question regarding constructors vs factory methods, however I don't believe this implementation fits the factory methodology.
To add an additional question onto the above, if instantiation within the constructor is the way to go, I've always used some sort of Load() method in the past. Either a specific private method that literally matches properties from the returned db object to the new class, or via a generic reflective method that assumes property names will match up. I'm curious if there is another way to "load" an object that I've missed.
I do not like this approach.
IMHO , it is better to implement some kind of repository which retrieves instances of persisted classes for you.
As an alternative, you could also follow the ActiveRecord approach, where you could have a static 'Load' method inside your class, and an instance method 'Save' for instance. (Take a look at Castle ActiveRecord).
But, for me, I prefer the Repository approach.

Categories