When you work with ORM which implement UnitOfWork pattern (NHibernate's Session, Entity 开发者_如何转开发Framework's ObjectContext, etc.), there are two types of data services methods: those which save/commit changes and those which just modify model properties.
In some time it becomes difficult to support this mess: when you call a method you are not sure, whether it will save changes or not (if it doesn't you need to do it in some of outer methods).
How can I solve this problem? The only idea I have is a special naming. For example, AddCustomer for saving method and FillForAddCustomer for non-saving method. Any other ideas?
There are a couple of ways to handle this, and they each have their own pros and cons.
The first way would be to do something like you suggest and handle the difference between "persisted" methods and "un-persisted" methods via convention. Ruby takes a similar approach with methods by indicating "dangerous" methods (ie those that modify the object they are called on or their arguments) by ending the method name with an exclamation mark (!
). Depending on your development culture, such a convention may work very well, or it may not. The problem I have with conventions like this is that it's one more thing I have to remember, is hard to check for consistency, and is less obvious to someone new to the codebase that the convention exists.
Another way to approach the problem is to use the Command Query Responsibility Segregation (CQRS) pattern. The idea here is that rather than have one Repository
for a domain object that takes care of both getting the persisted objects, and persisting new or updated ones, you split those two responsibilities up. In addition to it being much more clear regarding which methods persist things (you are using classes from entirely different namespaces), you are also separating the reading from the writing, which allows for more easily tuning the application for better performance down the road.
Some may argue that, for purposes of simply knowing which methods persist and which don't, CQRS is the same thing as a naming convention, just moved up a level. While that is true to some extent, by moving the convention up to the namespace level, rather than the method name level, you are able to better trace, via dependency graphs, if you are being inconsistent with where persisting is taking place and allows you to refactor more easily.
精彩评论