OOP Value Objects and Entities in the same class - oop

I am refactoring an old procedural PHP website into a tasty OOP application with a light sprinkling of Domain Driven Design for added flavour.
I keep stumbling upon cases where I have a need for classes that can have subclasses which are either entities or value objects.
An url object, for example. There are a zillion urls out there and so they all cannot really be entities. But some are very special urls, like my home page. That is an entity.
Another example is, say, a 'configuration object'. I'd like some configurations to have identities so i can create 'presets' and administer them via an online control panel. For those a finder/repository is needed to find them and ORM is needed to manage their lifetimes. But, for others 'not-presets' (of the same class hierarchy) I'd like to be able to load them up with data that has been customised on the fly and does not need to be persisted.
I am envisaging a lot of :
class factory {
reconstitute($rawdata) {
if (raw data has identity)
load up and return entity version of the class
else
load up and return anonymous/value object version of the class
It all seems a bit odd.
Is there any pattern out there that discusses the best way to handle this issue?

I'm not sure I totally understand your scenerio but... does that really matter?
In my experience with EFs/ORMs the best way (that I can think of) to do what you are wanting to do is to let your entity class decide whether or not to load/persist itself from/to a database based on business rules defined in the class.
$url = new URLClass('KEY_DATA') // returns loaded object url if key if found in database
$url = new URLClass() // returns new url object
$url = new URLClass('', '110011000110010001000011101010010100') // returns new url with data loaded from raw data
Not sure if that really helps you out or if it even applies.

Related

What is the best practice when adding data in one-to-many relationship?

I am developing a website for a beauty salon. There is an admin part of the website, where the esthetician can add a new care. A care is linked to a care category (all cares related to hands, feets, massages, ...). To solve this I wrote this code into the CareRepository in the .NET API :
public async Task<Care?> AddAsync(Care care)
{
// var dbCareCategory = await this._careCategoryRepository.GetByNameAsync(care.CareCategoryName);
if (string.IsNullOrEmpty(care.CareCategoryName) || string.IsNullOrWhiteSpace(care.CareCategoryName))
return null;
var dbCareCategory = await this._instituteDbContext.CareCategories
.Where(careCategory => Equals(careCategory.Name, care.CareCategoryName))
.Include(careCategory => careCategory.Cares)
.FirstOrDefaultAsync();
if (dbCareCategory == null || dbCareCategory.Cares.Contains(care))
return null; // TODO : improve handling
dbCareCategory.Cares.Add(care);
await this._instituteDbContext.SaveChangesAsync();
return care;
}
My problem here is that I am a bit struggling with the best practice to have, because in order to add a care to a category, I have to get the category first. At the first place, I called the CareCategoryRepository to get the care (commented line). But then, EF was not tracking the change, so when I tried to add the care, it was not registered in the database. But once I call the category from the CareRepository, EF tracks the change and saves the Care in the database.
I assume this is because when calling from another repository, it is a different db context that tracks the changes of my entity. Please correct me if my assumption is wrong.
So, I am wondering, what is the best practice in this case ?
Keep doing what I am doing here, there is no issue to be calling the category entities from the care repository.
Change my solution and put the AddCare method into the CareCategoryRepository, because it makes more sense to call the categories entities from the CareCategoryRepository.
Something else ?
This solution works fine, however I feel like it may not be the best way to solve this.
The issue with passing entities around in web applications is that when your controller passes an entity to serve as a model for the view, this goes to the view engine on the server to consume and build the HTML for the view, but what comes back to the controller when a form is posted or an AJAX call is made is not an entity. It is a block of data cast to look like an entity.
A better way to think of it is that your Add method accepts a view model called AddCareViewModel which contains all of the fields and FKs needed to create a new Care entity. Think about the process you would use in that case. You would want to validate that the required fields are present, and that the FKs (CareCategory etc.) are valid, then construct a Care entity with that data. Accepting an "entity" from the client side of the request is trusting the client browser to construct a valid entity without any way to validate it. Never trust anything from the client.
Personally I use the repository pattern to serve as a factory for entities, though this could also be a separate class. I use the Repository since it already has access to everything needed. Factory methods offer a standard way of composing a new entity and ensuring that all required data is provided:
var care = _careRepository.Create(addCareViewModel.CareCategoryId,
/* all other required fields */);
care.OptionalField = addCareViewModel.OptionalField; // copy across optional data.
_context.SaveChanges(); // or ideally committed via a Unit of Work wrapper.
So for instance if a new Care requires a name, a category Id, and several other required fields, the Create method accepts those required fields and validates that they are provided. When it comes to FKs, the repository can load a reference to set the navigation property. (Also ensuring that a valid ID was given at the same time)
I don't recommend using a Generic Repository pattern with EF. (I.e. Repository()) Arguably the only reason to use a Repository pattern at all with EF would be to facilitate unit testing. Your code will be a lot simpler to understand/maintain, and almost certainly perform faster without a Repository. The DbContext already serves all of those needs and as a Unit of Work. When using a Repository to serve as a point of abstraction for enabling unit testing, instead of Generic, or per-entity repositories, I would suggest defining repositories like you would a Controller, with effectively a one-to-one responsibility.
If I have a CareController then I'd have a CareRepository that served all needs of the CareController. (Not just Care entities) The alternative is that the CareController would need several repository references, and each Repository would now potentially serve several controllers meaning it would have several reasons to change. Scoping a repository to serve the needs of a controller gives it only one reason to change. Sure, several repositories would potentially have methods to retrieve the same entity, but only one repository/controller should be typically responsible for creating/updating entities. (Plus repositories can always reference one another if you really want to see something as simple as Read methods implemented only once)
If using multiple repositories, the next thing to check is to ensure that the DbContext instance used is always scoped to the Web Request, and not something like Transient.
For instance if I have a CareRepository with a Create method that calls a CareCategoryRepository to get a CareCategory reference:
public Care Create(string name, int careCategoryId)
{
if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameOf(name));
var care = new Care { Name = name };
var careCategory = _careCategoryRepository.GetById(careCategoryId);
care.CareCategory = careCategory;
_context.Cares.Add(care);
}
We would want to ensure that the DbContext reference (_context) in all of our repositories, and our controller/UnitOfWork if the controller is going to signal the commit with SaveChanges, are pointing at the exact same single reference. This applies whether repositories call each other or a controller fetches data from multiple repositories.

How is SaveChanges() called in BreezeController?

It appears that all the existing breezejs examples are passing entity models to and from the BreezeController.
But almost all our pages built are using some form of view models. In the days we have no BreezeJs, we retrieve the data (domain model) from a repository to populate (using AutoMapper or manually) a view model, which contains only the necessary data for that view. The WebAPI sends only the view model data over to the browser where we can populate a client-side view model (usually a knockout observable).
When saving data, we collect data from a <form> to populate an input view model, send only that data over to the server, where data in the input view model is mapped to the domain model. The update is saved by calling SaveChanges() on the DbContext entity in the repository.
Now, BreezeJs is to take over all our repository code by creating an EFContextProvider. The examples I have seen usually retrieve the domain model data and then pass it all to the client side.
[HttpGet]
public IQueryable<Item> Items() {
return _contextProvider.Context.Items;
}
It is the client-side javascript's job to build a view model.
Of course it is possible for us to build the view model at the server side:
[HttpGet]
public List<ItemViewModel> Items() {
var items = _contextProvider.Context.Items
.Include("RelatedEntity")
.ToList();
var model = new List<ItemViewModel>();
.... some code to build model from items ....
return model;
}
The benefit is that less data is transferred across the network, and we can do many manipulations on the server side. But I don't know if it is a good practice to modify this BreezeController like that. But at least, it returns data needed to list all the items.
The real trouble came when I tried to POST data back.
In the BreezeJs examples I found, they use a ko.observableArray() to store all the domain model data, let's say vm.items. Then the new record newItem is build by manager.createEntity into a domain model. After validating the data, item.entityAspect.validateEntity(), the newItem is pushed into vm.items and manager.saveChanges() is called, which somehow invokes SaveChanges() on the BreezeController.
[HttpPost]
public SaveResult SaveChanges(JObject saveBundle) {
return _contextProvider.SaveChanges(saveBundle);
}
I find too many things have been taken over! (Laugh at me if you disagree.) My questions are:
Can I just createEntity and then saveChanges?
I only have an empty form to fill in and submit. There is certainly no need to build a whole items array on the client-side.
Can I pass an input view model as a JObject and do some server-side processing before calling _contextProvider.SaveChanges()?
It turns out to be a super long post again. Thank you for reading it all through. Really appreciate it!
Good questions. Unfortunately, our demo code seems to have obscured the real capabilities of Breeze on both client and server. Breeze is not constrained in the ways that your fear.
I don't want to repeat everything that is in our documentation. We really do talk about these issues. We need more examples to be sure.
You are describing a CQRS design. I think it over-complicates most applications. But it's your prerogative.
If you want to send ItemViewModel instead of Item, you can. If you want that to be treated as an entity on the Breeze client - have the EntityManager turn it into a KO observable and manage it in cache, change track it, validate it -, you'll have to provide metadata for it ... either on server or client. That's true for Breeze ... and every other system you can name (Ember, Backbone, etc). Soon we will make it easier to create metadata on the server for an arbitrary CLR model; that may help.
You have complete control over the query on the server, btw, whether Item or ItemViewModel. You don't have to expose an open-ended query for either. You seem to know that by virtue of your 2nd example query.
On to the Command side.
You wrote: "[the examples] use a ko.observableArray() to store all the domain model data, let's say vm.items"
That is not precisely true. The items array that you see in examples exists for presentation. The items array isn't storing anything from a Breeze perspective. In fact, after a query, the entities returned in the query response (if they are entities) are already in the manager's cache no matter what you do with the query result, whether you put them in an array or throw them away. An array plays no role whatsoever in the manager's tracking of the entities.
You wrote: "Can I just createEntity and then saveChanges?"
Of course! The EntityManager.createEntity method puts a new entity in cache. Again, the reason you see it being pushed into the items array is for presentation to the user. That array has no bearing on what the manager will save.
You wrote: "Can I pass an input view model ... and do some server-side processing before calling _contextProvider.SaveChanges()?"
I don't know what you mean by "an input viewmodel". The Breeze EntityManager tracks entities. If your "input viewmodel" is an entity, the EntityManager will track it. If it has changed and you call saveChanges, the manager will send it to the controller's SaveChanges method.
You own the implementation of the controller's SaveChanges method. You can do anything you want with that JObject which is simply a JSON.NET representation of the change-set data. I think you'll benefit from the work that the ContextProvider does to parse that object into a SaveMap. Read the topic on Customizing the EFContextProvider. Most people feel this provides what they need for validating and manipulating the client change-set data before passing those data onto the data access layer ... whether that is EF or something else.
If instead you want to create your own, custom DTO to POST to your own custom controller method ... go right ahead. Don't call EntityManager.saveChanges though. Call EntityManager.getChanges() and manipulate that change array of entities into your DTO. You'll be doing everything by hand. But you can. Personally, I'd have better things to do.

How can I cleanly write abstractions for interacting with RESTful resources?

I have a simple REST client that works well. In my application code I do something like this:
restClient = new RestClient(configurationData)
restClient.get('/person/1') //Get Person
restClient.get('/equipment/auto/3') //Get an Auto
restClient.get('/house/7') //Get a House
That works well but things are getting more complicated and I would like to divorce the application code from the specific resource locations.
I'd like to be able to write a wrapper around the service, which will store the resource locations and not require me to put them in my application code. I would expect my code to start looking more like this:
restClient = new RestClient(configurationData)
restClient.getPerson(1) //Get Person
restClient.getAuto(3) //Get an Auto
restClient.getHouse(7) //Get a House
I started adding these wrappers inside of my RestClient class but it got very bloated very fast, and it felt that the abstraction should be at a higher level. Mixing Resource-specifics with my client also felt wrong.
So, instead I subclassed RestClient, and each resource has its own class. The problem is that now I have to instantiate a new client for every different resource type:
personRestClient = new PersonRestClient(configurationData)
personRestClient.get(1);
autoRestClient = new AutoRestClient(configurationData)
autoRestClient.get(3);
housesRestClient = new HousesRestClient(configurationData)
housesRestClient.get(7);
But now I've created a new Client class for each Resource and I am fairly certain that is a very bad thing to do. It's also a pain because I have to tie my connection configuration data to each one, when this should only happen once.
Is there a good example or pattern I should be following when I want to write abstractions for my Resources? My base RestClient works fine but I dislike having to put the server-side API locations in my application code. But I also don't want to have to instantiate one specialized client class for each Resource I want to interact with.
I am in a similar situation, and have what I consider to be a good implementation with the appropriate abstractions. Whether my solution is the best practice or not, I cannot guarantee it, but it is fairly lightweight. Here is how I have it architected:
My UI layer needs to make calls into my REST service, so I created an abstraction called ServiceManagers.Interfaces.IAccountManager. The interface has methods called GetAccounts(Int64 userId).
Then I created a Rest.AccountManager that implemented this Interface, and injected that into my AccountController. The Rest.AccountManager is what wraps the REST specifics (URL, get/post/put..., parameters, etc).
So, now my UI code only has to call accountManager.GetAccounts(userId). You can create an all-encompassing interface so that you only have a Get, but I feel that is less expressive. It is ok to have many different interfaces for each component(ie: PersonManager, HouseManager, AutoManager), because each are a separate concern returning different data. Do not be afraid of having a lot of interfaces and classes, as long as your names are expressive.
In my example, my UI has a different manager for each controller, and the calls made fit each controller appropriately (ie. GetAccounts for AccountController, GetPeople for PeopleController).
Also, as to the root configuration data, you can just use a configurationCreationFactory class or something. That way all implementations have the appropriate configuration with the core logic in one location.
This can be a hard thing to explain, and I know I did not do a perfect job, but hopefully this helps a little. I will try to go back through and clean it up later, especially if you do not get my point :)
I am thinking something like this, again some way of mapping your end points to the client. You can have the mapping as an xml or a properties file which can be loaded and cached during the app start. The file should have key value pairs
PERSON_ENDPOINT=/person/
AUTO_ENDPOINT=/equipment/auto/...
The client should pass this key to the factory may be ClientFactory which has this xml cache and retrieves the end point from the cached file. The parameters can be passed to the factory as custom object or a map. The factory gives back the complete end point say "/person/1" which you can pass to your client. This way you dont need to have different classes for the client. If you dont like the xml or a file you can have it as a static map with key value pairs. If its an xml or file you dont need a code change every time that is the advantage.
Hope this helps you.

Beans, methods, access and change? What is the recommened practice for handling them (i.e. in ColdFusion)?

I am new to programming (6 weeks now). i am reading a lot of books, sites and blogs right now and i learn something new every day.
Right now i am using coldfusion (job). I have read many of the oop and cf related articles on the web and i am planning to get into mxunit next and after that to look at some frameworks.
One thing bothers me and i am not able to find a satisfactory answer. Beans are sometimes described as DataTransferObjects, they hold Data from one or many sources.
What is the recommended practice to handle this data?
Should i use a separate Object that reads the data, mutates it and than writes it back to the bean, so that the bean is just a storage for data (accessible through getters) or should i implement the methods to manipulate the data in the bean.
I see two options.
1. The bean is only storage, other objects have to do something with its data.
2. The bean is storage and logic, other objects tell it to do something with its data.
The second option seems to me to adhere more to encapsulation while the first seems to be the way that beans are used.
I am sure both options fit someones need and are recommended in a specific context but what is recommended in general, especially when someone does not know enough about the greater application picture and is a beginner?
Example:
I have created a bean that holds an Item from a database with the item id, a name, and an 1d-array. Every array element is a struct that holds a user with its id, its name and its amount of the item. Through a getter i output the data in a table in which i can also change the amount for each user or check a user for deletion from this item.
Where do i put the logic to handle the application users input?
Do i tell the bean to change its array according to the user input?
Or do i create an object that changes the array and writes that new array into the bean?
(All database access (CreateReadUpdateDelete) is handled through a DataAccessObject that gets the bean as an argument. The DAO also contains a gateway method to read more than one record from the database. I use this method to get a table of items, which i can click to create the bean and its data.)
You're observing something known as "anemic domain model". Yes, it's very common, and no, it's not good OO design. Generally, logic should be with the data it operates on.
However, there's also the matter of separation of concerns - you don't want to stuff everything into the domain model. For example, database access is often considered a technically separate layer and not something the domain models themselves should be doing - it seems you already have that separated. What exactly should and should not be part of the domain model depends on the concrete case - good design can't really be expressed in absolute rules.
Another concern is models that get transferred over the network, e.g. between an app server and a web frontend. You want these to contain only the data itself to reduce badnwidth usage and latency. But that doesn't mean they can't contain logic, since methods are not part of the serialized objects. Derived fields and caches are - but they can usually be marked as transient in some way so that they are not transferred.
Your bean should contain both your data and logic.
Data Transfer Objects are used to transfer objects over the network, such as from ColdFusion to a Flex application in the browser. DTOs only contain relevant fields of an object's data.
Where possible you should try to minimise exposing the internal implementation of your bean, (such as the array of user structs) to other objects. To change the array you should just call mutator functions directly on your bean, such as yourBean.addUser(user) which appends the user struct to the internal array.
No need to create a separate DAO with a composed Gateway object for your data access. Just put all of your database access methods (CRUD plus table queries) into a single Gateway object.

Does anyone have a good article or good advice for class naming for n-tier web applications?

I'm used to the layout that LLBLGen gives when it generates objects based on a database structure, which might generate the following class files for a given "User" table in the database:
/EntityClasses/UserEntity.vb
/CollectionClasses/UserCollection.vb
This provides some base functionality for data access. However, when you want to implement business logic on top of that, how are you laying things out? For example, given a table structure that might look like this:
USER
userId
firstName
lastName
username
password
lockedOut
What if you wanted to lock out a user? What code would you call from the presentation layer? Would you instantiate the UserEntity class, and do:
User = new UserEntity(userId)
User.lockedOut = true
User.Save()
Or would you create a new class, such as UserHelper (/BusinessLogic/UserHelper.cs), which might have a LockOutUser function. That would change the code to be:
UH = new UserHelper()
UH.LockOutUser(userId)
Or would you extend the base UserEntity class, and create UserEntityExt that adds the new functionality? Therefore, the code from the presentation layer might look like:
User = new UserEntityExt(userId)
User.LockOutUser()
Or... would you do something else altogether?
And what would your directory/namespace structure and file/class naming conventions be?
I think what you are looking for is a service layer which would sit on top of the domain objects. You essentially have this with your second option although I might call it UserService or UserTasks. By encapsulating this LockUser process in a single place it will be easy to change later when there might be more steps or other domain objects involved. Also, this would be the place to implement transactions when dealing with multiple database calls.