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

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.

Related

Passing state between view models

Just wondering really if there's a consensus on the 'right' way to do this, for MVVM, DDD, and other philosophies . . .
So I've got a login screen, represented by a ViewModel, LoginViewModel. It can take a name and password. It also takes in through dependency injection a LoginService, that implements the logic of taking the username and password, and retrieving the Employee object.
My question is what's the 'right' way to get this information to the next view model? Let's say it's AccountSettings, which needs to know about the logged in employee. How do we encapsulate that? I've got an AccountSettingsViewModel, but should it require
a) An instance of the LoginViewModel?
b) An instance of the LoginService, which keeps a reference to the logged in employee
c) A shared object or field on a global object, like App or something?
Thanks in advance!
Personally all my view models in DDD or otherwise are simple data containers, used to restrict the data that gets sent from the application to the UI/view. I might include some code in my view models that's specific to transforming data for that view. I also consider my view models to be coupled to my views (I only mention this because I've seen 2 teams put them in their own separate project/assembly away from the views!).
If I have anything copying data, or performing actions to get the data needed for the view model, this would live in either my domain model or my application layer, probably in a service. I wouldn't ever inject a service into a view model.

Using repository pattern with ORM

I have created a little project where I pass data from my controllers to a service class which uses an ORM to for example save an object:
Something like this:
The UserController receives the post data and passes it to the UserService.
The UserService creates a user object and saves it to the database with $user.save();
Now I'm struggling with two things:
First:
Let's say I use a repository to add the user, it would be like this:
Controller passes post data to the service which creates the user object and passes it to the repository. The only thing the repository has to do is call $user.save(), isn't that a bit weird? Why not calling save in my service, because using a repository just to call a save method seems overkill to me.
Second:
I read that when you use repositories, you can easily change storage methods because your application isn't aware which one is used. But before passing an object to your repository, you have to create it.
Using an ORM, each one has a different way: Doctrine uses $user = new User while Propel uses $user = new User(), idiorm uses $user = ORM::for_table('user')->create(); So when switching to another ORM for some reason comes with changing this in your project too, no?
First: Have a read about the responsibilities of Model View and Controller. There's a reasonable explanation with an example at this site: http://tomdalling.com/blog/software-design/model-view-controller-explained/
With regard to the Model and your ORM - the ORM would probably exist within the Model. So you should be asking your Model to create a new object (which may represent a single table or a series of related tables - your Model should understand these relationships). You can then pass data to your Model and your Model should then store the data into the appropriate columns in the appropriate tables. A simple example, imagine creating an object called 'Family' where you might specify 2 parent names, a variable number of children names and then tell the Model to save this. The Model may take this 'Family' object and create a single Family table record and 5 Person table records, flagging some as parents and others as children.
Second: The 'Storage Methods' referred to are (in my opinion) referring to the database you use. For example I know that Propel supports MySQL, PostgreSql, MSQL, Oracle, and others. My switch the configuration to a different database Propel will automatically start talking the appropriate language for the new database.

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.

OOP Value Objects and Entities in the same class

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.

Where to put NHibernate query logic?

I am trying to set up proper domain architecture using Fluent NHibernate and Linq to NHibernate. I have my controllers calling my Repository classes, which do the NHibernate thang under the hood and pass back ICollections of data. This seems to work well because it abstracts the data access and keeps the NHibernate functionality in the "fine print".
However, now I'm finding situations where my controllers need to use the same data calls in a different context. For example, my repo returns a list of Users. That's great when I want to display a list of users, but when I want to start utilizing the child classes to show roles, etc., I run into SELECT N+1 issues. I know how to change that in NHibernate so it uses joins instead, but my specific question is WHERE do I put this logic? I don't want every GetAllUsers() call to return the roles also, but I do want some of them to.
So here are my three options that I see:
Change the setting in my mapping so the roles are joined to my query.
Create two Repository calls - GetAllUsers() and GetUsersAndRoles().
Return my IQueryable object from the Repository to the Controller and use the NHibernate Expand method.
Sorry if I didn't explain this very well. I'm just jumping into DDD and a lot of this terminology is still new to me. Thanks!
As lomaxx points out, you need query.Expand.
To prevent your repository from becoming obscured with all kinds of methods for every possible situation, you could create Query Objects which make configurable queries.
I posted some examples using the ICriteria API on my blog. The ICriteria API has FetchMode instead of Expand, but the idea is the same.
I try and keep all the query logic in my repositories and try to only pass back the ICollection from them.
In your situation, I'd pass in some parameters to determine if you want to eager load roles or not and construct the IQueryable that way. For example:
GetAllUsers(bool loadRoles)
{
var query = session.Linq<Users>();
if(loadRoles)
query.Expand("Roles");
return query.ToList();
}
I would choose 2, creating two repositories. And perhaps would I consider creating another repository call to GetRoleByUser(User user). So, you could access a user's role upon user selection change on a seperate thread, if required, so it would increment your performance and won't load every user's roles for each of your users, which would require most resources.
It sounds like you are asking if it is possible to make GetAllUsers() sometimes return just the Users entities and sometimes return the Users and the roles.
I would either make a separate repository method called GetRolesForUser(User user), use lazy loading for Roles, or use the GetAllUsers(bool loadRoles) mentioned by lomaxx's answer.
I would lean toward lazy loading roles or a separate method in your repository.