Save Me on a Business Object - c#

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
}
}

Related

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.

Entity Framework business object transformation

I am trying to create a small personal project which uses EF to handle data access. My project architecture has a UI layer, a service layer, a business layer and a data access layer. The EF is contained within the DAL. I don't think it's right to then make reference to my DAL, from my UI. So I want to create custom classes for 'business objects' which is shared between all my layers.
Example: I have a User table. EF creates a User entity. I have a method to maybe GetListOfUsers(). That, in the presentation, shouldn't reply on a List, as the UI then has a direct link to the DAL. I need to maybe have a method exposed in the DAL to maybe be something like:
List<MyUserObject> GetListOfUsers();
That would then call my internal method which would GetListOfUsers which returns a list of user entities, and then transforms them into my MyUserObejcts, which is then passed back through the layers to my UI.
Is that correct design? I don't feel the UI, or business layer for that matter, should have any knowledge of the entity framework.
What this may mean, though, is maybe I need a 'Transformation layer' between my DAL and my Business layer, which transforms my entities into my custom objects?
Edit:
Here is an example of what I am doing:
I have a data access project, which will contain the Entity Framework. In this project, I will have a method to get me a list of states.
public class DataAccessor
{
taskerEntities te = new taskerEntities();
public List<StateObject> GetStates()
{
var transformer = new Transformer();
var items = (from s in te.r_state select s).ToList();
var states = new List<StateObject>();
foreach (var rState in items)
{
var s = transformer.State(rState);
states.Add(s);
}
return states;
}
}
My UI/Business/Service projects mustn't know about entity framework objects. It, instead, must know about my custom built State objects. So, I have a Shared Library project, containing my custom built objects:
namespace SharedLib
{
public class StateObject
{
public int stateId { get; set; }
public string description { get; set; }
public Boolean isDefault { get; set; }
}
}
So, my DAL get's the items into a list of Entity objects, and then I pass them through my transformation method, to make them into custom buily objects. The tranformation takes an EF object, and outputs a custom object.
public class Transformer
{
public StateObject State (r_state state)
{
var s = new StateObject
{
description = state.description,
isDefault = state.is_default,
stateId = state.state_id
};
return s;
}
}
This seems to work. But is it a valid pattern?
So, at some point, your UI will have to work with the data and business objects that you have. It's a fact of life. You could try to abstract farther, but that would only succeed in the interaction being deferred elsewhere.
I agree that business processes should stand alone from the UI. I also agree that your UI should not directly act with how you access your data. What have you suggested (something along the lines of "GetListOfUsers()") is known as the Repository Pattern.
The purpose of the repository pattern is to:
separate the logic that retrieves the data and maps it to the entity
model from the business logic that acts on the model. The business
logic should be agnostic to the type of data that comprises the data
source layer
My recommendation is to use the Repository Pattern to hide HOW you're accessing your data (and, allow a better separation of concerns) and just be concerned with the fact that you "just want a list of users" or you "just want to calculate the sum of all time sheets" or whatever it is that you want your application to actually focus on. Read the link for a more detailed description.
First, do you really need all that layers in your 'small personal project'?
Second, I think your suggested architecture is a bit unclear.
If I get you right, you want to decouple your UI from your DAL. For that purpose you can for example extract interface of MyUserObject (defined in DAL obviously) class, lets call it IMyUserObject, and instead of referencing DAL from UI, reference some abstract project, where all types are data-agnostic. Also, I suggest that you'd have some service layer which would provide your presentation layer (UI) with concrete objects. If you utilize MVC you can have a link to services from your controller class. Service layer in turn can use Repository or some other technique to deal with DAL (it depends on the complexity you choose)
Considering transformation layer, I think people deal with mapping from one type to another when they have one simple model (DTO) to communicate with DB, another one - domain model, that deals with all the subtleties of business logic, and another one - presentational model, that is suited best to let user interact with. Such layering separates concerns to good measure, making each task simpler, but making app more complicated in general.
So you may end having MyUserObjectDTO, MyUserObject and MyUserObjectView and some mapping or transformation btw them.

DDD and Repository pattern where to put behavior concerning CRUD

I try to put as much business logic as possible in my Domain Model.
Every time MyEntity is updated, I want two things to happen:
Send a message to the user who created it
Check if the changes apply to certain business rules
If the entity is not a child of an aggregate root.
Normally I would get the specific entity from the repository. Change the entity, and persist it
back to the DB using MyRepository.Save()
In this case I'd have to put the business logic in my application or in the DAL, not in the Domain Model. I'm trying to avoid using a business logic layer unless absolutely necessary, but I can't seem to fit this in unless I make a method called MyEntity.Update() or something like that but I have a feeling that is not the right way to do it.
First let me state, I am not against Repository patterns. I recently used one successfully on a project.
I would say exercise caution ... and if you can't encapsulate the requirements in your objects your OO approach might need to be looked at again. Introducing a Data Access layer for the purposes of doing other things seems to be a code smell. I have used a Service Layor to receive requests and manage transactions and versioning however not for additional things like validation and so on. Potentially your service layor could look like the following.
public enum UpdateResult
{
Success,
NoMyEntityFound,
StaleData,
InvalidRequest
}
public class MyService
{
...
...
public UpdateResult Update(...)
{
...Start Tran
...Load var m = MyEntity
...do the bare minimum here
...m.Update()
...Commit Tran
return UpdateResult.Success;
}
}
Having said all that a cautionary tail on repositories
http://ayende.com/blog/3955/repository-is-the-new-singleton

Constructive criticism on this class

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.

How much logic should i put my repository methods when using repository pattern?

i'm struggling a bit with repositories. I'm using C# and NHibernate. The question i have is : how much should my repository do before it calls a save or a get?
For example i have a user class which is an aggregate root. I want to call a method called "register" which will add the user and set some default values based on business rules and create some other entities which are also sub parts of the "user" root (ie address, groups, etc) . Should i call
userRepo.Register(newUser);
which would be(ignoring the obvious issues):
Regsiter(User newUser){
newUser.SomeProp = "Default Data";
Group g= new Group;
g.SomeProp2 = "Default Data";
newUser.Groups.Add(g);
Session.Save(g);
Session.Save(newUser);
}
or should i have put register in a business layer and have it do:
Regsiter(User newUser){
newUser.SomeProp = "Default Data";
Group g= new Group;
g.SomeProp2 = "Default Data";
newUser.Groups.Add(g);
userRepo.Register(newUser, g);// this does session.save on both objects.
}
Both seems slightly wrong.
What's the correct approach?
edit -------------------------------
thanks for all the responses. I can't decide who is the most right and therefore which answer to accept.
Generally everyone is saying put the business rules in another layer. that makes sense but i'm unsure about the data calls for groups - since groups aren't an aggregate root they shouldn't have their own repository so how do i go about adding and saving them? In my project adding a group to the user's group collection doesn't automatically create the group in the db; i also need to call session.save on the object. so do i put that into the user repo as userRepo.SaveGroup(g)?
If i have a createGroup() in the other layer then it'll either need to use it's own repo or the users. or am i being thick?
Personally, I keep the repository pattern as a substitute for sprocs. So my repository would have methods like getById(int id), save(), add(DomainObject obj) etc.
In a business tier, I'd have userManager.registerUser(string username, /* params, etc */). This would create the domain object. This method would just call the add() method in the data tier.
In short, the business tier is business-y, and the data tier is data-y.
What is your motivation for using the repository pattern in the first place? Usually, the repository is the abstraction of your object persistence logic. It retrieves items from (usually) a database and also handles updates, inserts and deletes.
If you were writing a test to check some logic and didn't want to hit the database what objects would you have to mock out? Usually the repository.
In scenario A) you cannot test a new user is created with the correct default data without directly hitting the database. Because of this, I would advocate keeping all business logic outside of the repositories and go with your second design
Determine where you want your Register method, maybe in a UserServices class. You can delegate object creation to a UserFactory. In a CreateNewUser() method, set up your defaults for the user and the Groups collection. Then call UserRepository.Save(newUser) to persist the data.
// UserServices class
public void Register(User newUser)
{
// add custom registration stuff.
_userRepository.Save(newUser);
}
// Application code
User user = UserFactory.CreateNewUser();
_userServices.Register(user);
// UserFactory
public User CreateNewUser()
{
// all new user, group creation
}
From your code example, I would call the Register method a service operation. As a service operation, it would belong on a service, or on a business component, rather than a repository. According to Evans (of DDD fame), a repository is a collection-like interface to entities stored in your database. The general idea is that you provide basic CRUD-like access to your entities through a repository to abstract the rest of your code away from lower-level data access details like an ORM tool.
For your example with Register...your service method would validate input, build the User object, and then call your repository to "Add" your new entity to the "repository" (which could be a database...but could also be something else...as far as your domain is concerned, it doesn't matter...its just a repository.)
I see two potential "wrongness" issues (since you didn't really indicate what you thought was wrong with them).
If the problem revolves around saving the group in the user registration method, or saving the user in the group methods, then you should separate these into different methods. (i.e. Register() would call RegisterGroup() or GetGroup()
If the problem revolves around saving things before the user really is ready to conceptually save things, then keep track of what they wanted to add and wait until the overall "save" method is called before putting any of this information into storage.

Categories

Resources