Design Patterns: Factory and Repository - user-interface

I have been wondering if the Factory Pattern and the Repository Pattern is keened to go hand in hand in a Domain Driven Design project?
The reason i ask is the way i'm doing this is like so:
GUI -> ClassFactory -> ClassProduct (is in the Domain Model) -> ClassProductRepository -> Datasource
The GUI calls the ClassFactory to separate the GUI from business logic. The ClassProduct calls the ClassProductRepository to separate the business logic from the datasource.
Is this a wrong approach of using these Design Patterns with Domain Driven Design? If so, please state your opinion on this subject.

Your on the right track. As Chad pointed out, you'll want to use a GUI interface separation pattern as an additional layer between your domain and the UI. MVC, MVP, Presentation Model, etc are established and well documented patterns for UI separation. Martin Fowler's excellent PoEAA covers many of them
As for your main question. Yes. Factories and Repositories work very well together. In fact, Evans suggests in DDD that in some cases you can delegate responsibility for object creation from your repository to your factory classes when you're reconstructing objects from the data store.
client <=> repository -> factory
|
v
database
The client requests an object from
the repository.
The repository queries the database.
The repository sends raw data to the
factory.
The factory returns object.
An over simplification but you get the idea. One point that isn't touched on by Evans (but which Fowler covers) is dependency injection. As your domain complexity continues to grow you may want to consider moving to an IoC container for managing object life cycles.

I would suggest sticking to MVC as a generic approach to separate your business logic from your view and your controller. This has been well documented and well studied approach, though its the best that we have currently.
Though, it seems like you're trying to use the pattern just for the reason of using the pattern. This is good for learning,but in most application systems I've seen the patterns you have described either don't exist and a simpler approach works or that its a nightmare to maintain.
Please see my previous answer to a question similar like this, that has a video that can help you in your design in the future.
Linky

Related

What is the pros and cons of using Generic DAO and Generic Service Pattern in Spring MVC with Hibernate

I have a thought to implement Generic DAO and Generic Service in my new project. I have seen lot of examples in the web.
Before start I want to know the pros and cons of using this design pattern.
Can any one tell Is it advisable to use this pattern?
I think, it will be better to have an other opinion about DAO and generic DAO. Some words about Pros (My suggestions are valid if you use ORM, Hibernate for an example, not plain JDBC).
Creates a nice abstraction layer of the actual storage system.
It is a marketing bullshit. In real life we have problems to migrate between various RDBMS (Oracle RDBMS -> PostgreSQL). Not speaking about change of a storage system type (RDBMS -> NoSQL for example).
Provide a more object-oriented view of the persistence layer.
No! It is very hard to do properly. Most DAO implementations have a dozens of methods like
getSomething(String x, String y, String z);
getSomethingOther(String x, String z);
Provide a clean separation between the domain class and code which will perform the data access from databse.[using JDBC,ORM[like
hibernate] or JPA].
May be, but usefulness of this separation is exaggerated.
Once you have the general CRUD flow set, the same layout can be repeated for other DAOs.
It is correct.
Generic DAO design pattern comes into picture when more then one DAO classes wants to communicate with database (as per example CRUD(Create,Read ,Update and Delete) ),with out this design pattern you will end up writing separate code to make database call (using session) for each of your DAO classes which is a tedious work in general because with each new implementation of DAO classes you have to write you own code to deal with database.
Below are some Pros and cons of using Generic DAO.
Note: Details give below are what I have learned from answers given to SO Question Pros and Cons of the use of DAO pattern
Pros
1. Creates a nice abstraction layer of the actual storage system.
2. Provide a more object-oriented view of the persistence layer .
3. Provide a clean separation between the domain class and code which
will perform the data access from databse.[using JDBC,ORM[like
hibernate] or JPA]
4. Once you have the general CRUD flow set, the same layout can be
repeated for other DAOs.
Cons
1. If you handwrite the DAOs, then the code can become tedious and repetitive you have to use code generators/templates and ORM.
Q - Can any one tell Is it advisable to use this pattern?
A- After Observing above pros and cons I used Generic DAO in my application as abstraction layer to communicate with database in Terms Of CRUD which actual helped me reduces lots of duplicate code to do same thing other DAOs.At first it will take time to get used to it of afterwards use of Generic DAO will make you life easy.

How do Gang of Four Design Patterns fit into the MVC paradigm?

I've mulled over Design Patterns for some time now and I am just starting to see how I might actually begin incorporating some of these more deliberately in my development work. However, I am still confused about their treatment of MVC in the beginning of the book and how it relates to the rest of the book.
Most of the frameworks I have worked with - Spring, Yii, ASP.NET, and even Objective-C Cocoa (UIKit) - cater to the MVC paradigm. I get MVC because to me it is a useful way of classifying objects and how they should message or interact with each other. Plus, these frameworks kind of force it upon you even if you are not setting out to think in the MVC way.
I also feel that I understand the premise of Design Patterns: they really don't like subclassing, they love abstract interfaces, and they strive for loose coupling. I can't say I fully understand all of the patterns yet or how they are useful, but I am getting a feel for it.
My question is this: what is the interplay between MVC and design patterns? What were they getting at in the first chapter of the book with the MVC application example? Are certain design patterns just not relevant in the MVC paradigm? I wonder, for example, how the Command pattern is supposed to fit into MVC. It seems incredibly useful, but do we create a CommandModel and CommandController to send to other controllers? Do we just create a Command object as prescribed in the book? Basically, I am wondering if the ideas of MVC and Design Patterns are wholly disjoint and I just don't understand, or if there are some patterns that do not fit into the mold.
My personnal opinion is that MVC is a simplified version of the Observer Pattern which is a simplified version of the Mediator Pattern.
MVC: One Model, One view, the Controler manages the communication between them.
Observer Pattern: One Model, Multiples views ( observers/subscribers ), and the publisher manages the communication
Mediator Pattern: Several different Models, Several views, and the mediator manages the communications between them.
The MVC in the GoF book is for the desktop, it uses the observer pattern to update views. The command example in the GoF book is for an editor.
There are other flavors of MVC where the use of other design patterns may not be obvious:
What is the difference between MVC and MVVM?
Presentation abstraction control
The GoF book says:
...
Taken at face value, this example reflects a design that decouples views from models. But the design is applicable to a more general problem: decoupling objects so that changes to one can affect any number of others without requiring the changed object to know details of the others. This more general design is described by the Observer (page 293) design pattern.
Another feature of MVC is that views can be nested. For example, a control panel of buttons might be implemented as a complex view containing nested button views. The user interface for an object inspector can consist of nested views that may be reused in a debugger. MVC supports nested views with the CompositeView class, a subclass of View. CompositeView objects act just like View objects; a composite view can be used wherever a view can be used, but it also contains and manages nested views.
Again, we could think of this as a design that lets us treat a composite view just like we treat one of its components. But the design is applicable to a more general problem, which occurs whenever we want to group objects and treat the group like an individual object. This more general design is described by the Composite (163) design pattern. It lets you create a class hierarchy in which some subclasses define primitive objects (e.g., Button) and other classes define composite objects (CompositeView) that assemble the primitives into more complex objects.
MVC also lets you change the way a view responds to user input without changing its visual presentation. You might want to change the way it responds to the keyboard, for example, or have it use a pop-up menu instead of command keys. MVC encapsulates the response mechanism in a Controller object. There is a class hierarchy of controllers, making it easy to create a new controller as a variation on an existing one.
A view uses an instance of a Controller subclass to implement a particular response strategy; to implement a different strategy, simply replace the instance with a different kind of controller. It's even possible to change a view's controller at run-time to let the view change the way it responds to user input. For example, a view can be disabled so that it doesn't accept input simply by giving it a controller that ignores input events.
The View-Controller relationship is an example of the Strategy (315) design pattern. A Strategy is an object that represents an algorithm. It's useful when you want to replace the algorithm either statically or dynamically, when you have a lot of variants of the algorithm, or when the algorithm has complex data structures that you want to encapsulate.
MVC uses other design patterns, such as Factory Method (107) to specify the default controller class for a view and Decorator (175) to add scrolling to a view. But the main relationships in MVC are given by the Observer, Composite, and Strategy design patterns.
...
MVC is a pattern. But it only covers a small aspect of a web application. Another common pattern that gets used with MVC is the Repository. These are more architectural patterns.... their scope has a bigger impact on the overall project.
the GOF patterns will introduce themselves in little ways all over the place. They can help build MVC infrastructure depending on design choices. eg, Strategy gets used a lot so you can plug in different ways of doing things like "authentication" etc.
You don't have to use the patterns as they are, they don't even have to be the exact same code structure. Its more the design principle / goal of the pattern that you employ in the design.
MVC is an architectural pattern. It perfectly fits with other design patterns like Command Pattern. But you do not apply patterns just because they exist and they are written in an authoritative book. You apply patterns when you have a programming/design problem and there is a way to solve that problem that was discovered by someone else and was written down. The way to solve a problem is a pattern. For example, you have an application that saves data to the database. Data to be saved is quite complex: some records must be inserted, some records updated and some deleted. The sequence of steps is important because the records to be inserted into one table depend on records to be inserted into another table. So, a database transaction must be used. One of possible ways to implement the transaction is to use Command Pattern. The way to do it is very well explained in Larman's "Applying UML and Patterns" book (chapter "Designing a Persistence Framework wth Patterns", section "Designing a Transaction with the Command Pattern" - scroll down to the page 556). PersistentObject is an abstract Model class there. All other Model classes extend it. In that example MVC is implemented in the UI, Application and Domain layers but Command is implemented in the Persistence layer. These patterns help to solve different problems and they are mutually supportive in that example.

What are your best practices when using an MVC-based web framework?

A few general questions to those who are well-versed in developing web-based applications.
Question 1:
How do you avoid the problem of "dependency carrying"? From what I understand, the first point of object retrieval should happen in your controller's action method. From there, you can use a variety of models, classes, services, and components that can require certain objects.
How do you avoid the need to pass an object to another just because an object it uses requires it? I'd like to avoid going to the database/cache to get the data again, but I also don't want to create functions that require a ton of parameters. Should the controller action be the place where you create every object that you'll eventually need for the request?
Question 2:
What data do you store in the session? My understanding is that you should generally only store things like user id, email address, name, and access permissions.
What if you have data that needs to be analyzed for every request when a user is logged in? Should you store the entire user object in the cache versus the session?
Question 3:
Do you place your data-retrieval methods in the model itself or in a separate object that gets the data and returns a model? What are the advantages to this approach?
Question 4:
If your site is driven by a user id, how do you unit test your code base? Is this why you should have all of your data-retrieval methods in a centralized place so you can override it in your unit tests?
Question 5:
Generally speaking, do you unit test your controllers? I have heard many say that it's a difficult and even a bad practice. What is your opinion of it? What exactly do you test within your controllers?
Any other tidbits of information that you'd like to share regarding best practices are welcome! I'm always willing to learn more.
How do you avoid the problem of "dependency carrying"?
Good object oriented design of a BaseController SuperClass can handle a lot of the heavy lifting of instantiating commonly used objects etc. Usage of Composite types to share data across calls is a not so uncommon practice. E.g. creating some Context Object unique to your application within the Controller to share information among processes isn't a terrible idea.
What data do you store in the session?
As few things as is humanly possible.
If there is some data intensive operation which requires a lot of overhead to process AND it's required quite often by the application, it is a suitable candidate for session storage. And yes, storage of information such as User Id and other personalization information is not a bad practice for session state. Generally though the usage of cookies is the preferred method for personalization. Always remember though to never, ever, trust the content of cookies e.g. properly validate what's read before trusting it.
Do you place your data-retrieval methods in the model itself or in a separate object that gets the data and returns a model?
I prefer to use the Repository pattern for my models. The model itself usually contains simple business rule validations etc while the Repository hits a Business Object for results and transformations/manipulations. There are a lot of Patterns and ORM tools out in the market and this is a heavily debated topic so it sometimes just comes down to familiarity with tools etc...
What are the advantages to this approach?
The advantage I see with the Repository Pattern is the dumber your models are, the easier they are to modify. If they are representatives of a Business Object (such as a web service or data table), changes to those underlying objects is sufficiently abstracted from the presentation logic that is my MVC application. If I implement all the logic to load the model within the model itself, I am kind of violating a separation of concerns pattern. Again though, this is all very subjective.
If your site is driven by a user id, how do you unit test your code base?
It is highly advised to use Dependency Injection whenever possible in code. Some IoC Containers take care of this rather efficiently and once understood greatly improve your overall architecture and design. That being said, the user context itself should be implemented via some form of known interface that can then be "mocked" in your application. You can then, in your test harness, mock any user you wish and all dependent objects won't know the difference because they will be simply looking at an interface.
Generally speaking, do you unit test your controllers?
Absolutely. Since controllers are expected to return known content-types, with the proper testing tools we can use practices to mock the HttpContext information, call the Action Method and view the results to see they match our expectations. Sometimes this results in looking only for HTTP status codes when the result is some massive HTML document, but in the cases of a JSON response we can readily see that the action method is returning all scenario's information as expected
What exactly do you test within your controllers?
Any and all publicly declared members of your controller should be tested thoroughly.
Long question, longer answer. Hope this helps anyone and please just take this all as my own opinion. A lot of these questions are religious debates and you're always safe just practicing proper Object Oriented Design, SOLID, Interface Programming, DRY etc...
Regarding dependency explosion, the book Dependency Injection in .NET (which is excellent) explains that too many dependencies reveals that your controller is taking on too much responsibility, i.e. is violating the single responsibility principle. Some of that responsibility should be abstracted behind aggregates that perform multiple operations.
Basically, your controller should be dumb. If it needs that many dependencies to do its job, it's doing too much! It should just take user input (e.g. URLs, query strings, or POST data) and pass along that data, in the appropriate format, to your service layer.
Example, drawn from the book
We start with an OrderService with dependencies on OrderRepository, IMessageService, IBillingSystem, IInventoryManagement, and ILocationService. It's not a controller, but the same principle applies.
We notice that ILocationService and IInventoryManagement are both really implementation details of an order fulfillment algorithm (use the location service to find the closest warehouse, then manage its inventory). So we abstract them into IOrderFulfillment, and a concrete implementation LocationOrderFulfillment that uses IInventoryManagement and ILocationService. This is cool, because we have hidden some details away from our OrderService and furthermore brought to light an important domain concept: order fulfillment. We could implement this domain concept in a non-location-based way now, without having to change OrderService, since it only depends on the interface.
Next we notice that IMessageService, IBillingSystem, and our new IOrderFulfillment abstractions are all really used in the same way: they are notified about the order. So we create an INotificationService, and make MessageNotification a concrete implementation of both INotificationService and IMessageService. Similarly for BillingNotification and OrderFulfillmentNotification.
Now here's the trick: we create a new CompositeNotificationService, which derives from INotificationService and delegates to various "child" INotificationService instances. The concrete instance we use to solve our original problem will delegate in particular to MessageNotification, BillingNotification, and OrderFulfillmentNotification. But if we wish to notify more systems, we don' have to go edit our controller: we just have to implement our particular CompositeNotificationService differently.
Our OrderService now depends only on OrderRepository and INotificationService, which is much more reasonable! It has two constructor parameters instead of 5, and most importantly, it takes on almost no responsibility for figuring out what to do.

What are the main advantages of MVC pattern over the old fashioned 3-layer pattern

I am contemplating about using an MVC pattern in my new project and I can clearly see the main advantage of being able to put the data layer (the model) a little closer to the presentation layer (the view), which will allow a little increase in application speed. But apart from performance stand point are there any other advantages of MVC over the view-logic-data layered type pattern?
EDIT:
For those who's interested I just uploaded a sample PHP code that I created to test the use of MVC. I purposly omitted all the security checks to make the code a little easier to read. Please don't critisize it too much, because I know it could be a lot more refined and advanced, but nevertheless - it works!!! I will welcome questions and suggestions: Here is the link: http://www.sourcecodester.com/sites/default/files/download/techexpert/test_mvc.zip
The separation of concerns that's quoted as being an advantage of MVC is actually also an advance of a 3-layer/3-tier system. There too, the business logic is independent and can be used from different presentation tiers.
A main difference is that in classic MVC the model can have a reference back to the view. This means when data is updated the model can push this data back to possibly multiple views. The prime example is a desktop application where data is visualized in multiple ways. This can be as simple as a table and graph. A change in the table (which is a change in one view) is first pushed via the controller to the model, which then pushes it back to the graph (the other view). The graph then updates itself.
Since desktop development is on the decline, a lot of programmers have only come in touch with MVC in some web variant, e.g. via JSF in Java EE.
In those cases the model almost never has a reference to the view. This is because the web is mainly request/response based and after a request has been served, the server cannot send additional information. I.e. an update pushed from the model to the client would be meaningless. With reverse ajax/comet this is changing, but many web based MVC frameworks still don't fully utilize this.
Thus, in the case of web based MVC, the typical "triangle" between M, V and C is less there and that MVC variant is actually closer to an n-tier model than 'true' MVC is.
Also note that some web MVC frameworks have an intermediate plumbing part between M, V and C called a backing bean (Java/JSF) or code behind (ASP.NET). In JSF the controller is provided by the framework, and the view often doesn't bind directly to the model but uses this backing bean as an intermediary. The backing bean is very slim and basically just pre-fetches data from the model one way and translates model specific messages (e.g. exceptions) into view specific messages (e.g. some human readable text).
Beside
code reuse,
separating of concerns,
less coupling between the layers,
already mentioned by #bakoyaro and #arjan
i think that MVC is better than 3-tier when combined with the "convention over configuration" pattern. (i.e. "ruby on rails" or Microsofts "MVC for asp.net").
In my opinion this combination leads to to better and easier code maintanance.
In the first place it makes learning the mvc-framework a bit more difficuilt since you have to learn the conventions (a la controllers go into the controllers folder and must be named xxxxxcontroller)
But after you learned the conventions it is easier to maintain your own and foreign code.
Forget increasing application speed by moving to MVC. I have found the biggest benefit to be ease of code reuse. Once you move to MVC, there are no dependencies on the presentation of your data or the storage of the actual data.
For example you could write a servlet that served up .jsp pages as your presentation layer one day, and the next day write a web service as another presentation layer to your existing Model and Controller. Like wise if you want or need to switch your DBMS. Since accessing the Model is completely separate from everything else, you would just need to re-write just your data access objects to return the data in a way your Controller can handle it.
By separating concerns into 3 distinct pieces, you also facilitate true unit testing. Your Presentation layer can be tested free of the Model or Controller, and vice-a-versa.
On a side note, I've often felt that the MVC abbreviation was inaccurate. Whenever I see it I think of it as View->Controller->Model. The presentation layer will never have DAO code in it, and the model will never have presentation logic in it. The Controller is forced to act as a go-between.
Where 3-tier separates presentation from business and data access, MVC is a presentation layer pattern which further separates Model (data) from View (screen) and Controller (input).
There is no choosing MVC over 3-tier/3-layered. Use them both.

Business Layer structure, how do you build yours?

I am a big fan of NTiers for my development choices, of course it doesnt fit every scenario.
I am currently working on a new project and I am trying to have a play with the way I normally work, and trying to see if I can clean it up. As I have been a very bad boy and have been putting too much code in the presentation layer.
My normal business layer structure is this (basic view of it):
Business
Services
FooComponent
FooHelpers
FooWorkflows
BahComponent
BahHelpers
BahWorkflows
Utilities
Common
ExceptionHandlers
Importers
etc...
Now with the above I have great access to directly save a Foo object and a Bah object, via their respective helpers.
The XXXHelpers give me access to Save, Edit and Load the respective objects, but where do I put the logic to save objects with child objects.
For example:
We have the below objects (not very good objects I know)
Employee
EmployeeDetails
EmployeeMembership
EmployeeProfile
Currently I would build these all up in the presentation layer and then pass them to their Helpers, I feel this is wrong, I think the data should be passed to a single point above presentation in the business layer some place and sorted out there.
But I'm at a bit of a loss as to where I would put this logic and what to call the sector, would it go under Utilities as EmployeeManager or something like this?
What would you do? and I know this is all preference.
A more detailed layout
The workflows contain all the calls directly to the DataRepository for example:
public ObjectNameGetById(Guid id)
{
return DataRepository.ObjectNameProvider.GetById(id);
}
And then the helpers provider access to the workflows:
public ObjectName GetById(Guid id)
{
return loadWorkflow.GetById(id);
}
This is to cut down on duplicate code, as you can have one call in the workflow to getBySomeProperty
and then several calls in the Helper which could do other operations and return the data in different ways, a bad example would be public GetByIdAsc and GetByIdDesc
By seperating the calls to the Data Model by using the DataRepository, it means that it would be possible to swap out the model for another instance (that was the thinking) but ProviderHelper has not been broken down so it is not interchangable, as it is hardcode to EF unfortunately.
I dont intend to change the access technology, but in the future there might be something better or just something that all the cool kids are now using that I might want to implement instead.
projectName.Core
projectName.Business
- Interfaces
- IDeleteWorkflows.cs
- ILoadWorkflows.cs
- ISaveWorkflows.cs
- IServiceHelper.cs
- IServiceViewHelper.cs
- Services
- ObjectNameComponent
- Helpers
- ObjectNameHelper.cs
- Workflows
- DeleteObjectNameWorkflow.cs
- LoadObjectNameWorkflow.cs
- SaveObjectNameWorkflow.cs
- Utilities
- Common
- SettingsManager.cs
- JavascriptManager.cs
- XmlHelper.cs
- others...
- ExceptionHandlers
- ExceptionManager.cs
- ExceptionManagerFactory.cs
- ExceptionNotifier.cs
projectName.Data
- Bases
- ObjectNameProviderBase.cs
- Helpers
- ProviderHelper.cs
- Interfaces
- IProviderBase.cs
- DataRepository.cs
projectName.Data.Model
- Database.edmx
projectName.Entities (Entities that represent the DB tables are created by EF in .Data.Model, this is for others that I may need that are not related to the database)
- Helpers
- EnumHelper.cs
projectName.Presenation
(depends what the call of the application is)
projectName.web
projectName.mvc
projectName.admin
The test Projects
projectName.Business.Tests
projectName.Data.Test
+1 for an interesting question.
So, the problem you describe is pretty common - I'd take a different approach - first with the logical tiers and secondly with the utility and helper namespaces, which I'd try and factor out completely - I'll tell you why in a second.
But first, my preferred approach here is pretty common enterprise architecture which I'll try to highlight in brief, but there's much more depth out there. It does require some radical changes in thinking - using NHibernate or Entity framework to allow you to query your object model directly and let the ORM deal with things like mapping to and from the database and lazy loading relationships etc. Doing this will allow you to implement all of your business logic within a domain model.
First the tiers (or projects in your solution);
YourApplication.Domain
The domain model - the objects representing your problem space. These are plain old CLR objects with all of your key business logic. This is where your example objects would live, and their relationships would be represented as collections. There is nothing in this layer that deals with persistence etc, it's just objects.
YourApplication.Data
Repository classes - these are classes that deal with getting the aggregate root(s) of your domain model.
For instance, it's unlikely in your sample classes that you would want to look at EmployeeDetails without also looking at Employee (an assumption I know, but you get the gist - invoice lines is a better example, you generally will get to invoice lines via an invoice rather than loading them independently). As such, the repository classes, of which you have one class per aggregate root will be responsible for getting initial entities out of the database using the ORM in question, implementing any query strategies (like paging or sorting) and returning the aggregate root to the consumer. The repository would consume the current active data context (ISession in NHibernate) - how this session is created depends on what type of app you are building.
YourApplication.Workflow
Could also be called YourApplication.Services, but this can be confused with web services
This tier is all about interrelated, complex atomic operations - rather than have a bunch of things to be called in your presentation tier, and therefore increase coupling, you can wrap such operations into workflows or services.
It's possible you could do without this in many applications.
Other tiers then depend on your architecture and the application you're implementing.
YourApplication.YourChosenPresentationTier
If you're using web services to distribute your tiers, then you would create DTO contracts that represent just the data you are exposing between the domain and the consumers. You would define assemblers that would know how to move data in and out of these contracts from the domain (you would never send domain objects over the wire!)
In this situation, and you're also creating the client, you would consume the operation and data contracts defined above in your presentation tier, probably binding to the DTOs directly as each DTO should be view specific.
If you have no need to distribute your tiers, remembering the first rule of distributed architectures is don't distribute, then you would consume the workflow/services and repositories directly from within asp.net, mvc, wpf, winforms etc.
That just leaves where the data contexts are established. In a web application, each request is usually pretty self contained, so a request scoped context is best. That means that the context and connection is established at the start of the request and disposed at the end. It's trivial to get your chosen IoC/dependency injection framework to configure per-request components for you.
In a desktop app, WPF or winforms, you would have a context per form. This ensures that edits to domain entities in an edit dialog that update the model but don't make it to the database (eg: Cancel was selected) don't interfere with other contexts or worse end up being accidentally persisted.
Dependency injection
All of the above would be defined as interfaces first, with concrete implementations realised through an IoC and dependency injection framework (my preference is castle windsor). This allows you to isolate, mock and unit test individual tiers independently and in a large application, dependency injection is a life saver!
Those namespaces
Finally, the reason I'd lose the helpers namespace is, in the model above, you don't need them, but also, like utility namespaces they give lazy developers an excuse not to think about where a piece of code logically sits. MyApp.Helpers.* and MyApp.Utility.* just means that if I have some code, say an exception handler that maybe logically belongs within MyApp.Data.Repositories.Customers (maybe it's a customer ref is not unique exception), a lazy developer can just place it in MyApp.Utility.CustomerRefNotUniqueException without really having to think.
If you have common framework type code that you need to wrap up, add a MyApp.Framework project and relevant namespaces. If your're adding a new model binder, put it in MyApp.Framework.Mvc, if it's common logging functionality, put it in MyApp.Framework.Logging and so on. In most cases, there shouldn't be any need to introduce a utility or helpers namespace.
Wrap up
So that scratches the surface - hope it's of some help. This is how I'm developing software today, and I've intentionally tried to be brief - if I can elaborate on any specifics, let me know. The final thing to say on this opinionated piece is the above is for reasonably large scale development - if you're writing notepad version 2 or a corporate phone book, the above is probably total overkill!!!
Cheers
Tony
There is a nice diagram and a description on this page about the application layout, alhtough looks further down the article the application isnt split into physical layers (seperate project) - Entity Framework POCO Repository

Resources