Friday, April 13, 2012

Repository Pattern

There are two ways that the repository can query business entities. It can submit a query object to the client's business logic or it can use methods that specify the business criteria. In the latter case, the repository forms the query on the client's behalf. The repository returns a matching set of entities that satisfy the query.
http://msdn.microsoft.com/en-us/library/ff649690.aspx

A good practice that’s gaining well-deserved popularity is wrapping data access code in façade classes known as repositories. A repository consists of an interface and an implementation class. You typically have a repository for each significant class in the model. A significant class in an object model is a class that controls its own persistence and stands on its own in the domain without depending on other classes. In general, for example, Customer is a significant class, whereas OrderDetails is not, because you’ll always use order details if you have an order. In DDD, a significant class is said to be an aggregate root.
 http://msdn.microsoft.com/en-us/magazine/hh456393.aspx

A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. Client objects construct query specifications declaratively and submit them to Repository for satisfaction. Objects can be added to and removed from the Repository, as they can from a simple collection of objects, and the mapping code encapsulated by the Repository will carry out the appropriate operations behind the scenes.
 http://martinfowler.com/eaaCatalog/repository.html

I suspect that Customer should be a separate aggregate without a list of orders, and Order should be an aggregate with a list of order lines. If you need to perform operations on each order for a customer then use orderRepository.GetOrdersForCustomer(customerID); make your changes then use orderRespository.Save(order);
David Masters - http://stackoverflow.com/questions/5017969/repository-pattern-without-an-orm

In many systems every Entity has a Repository. Repository is a term gaining popularity over the Dao acronym. Repository is a nice word I guess, but we all call them Daos; so let's just go with it. Each Entity has a Dao. Let the Entity drive the Dao design. Let your domain drive the Dao design. For god's sakes though, don't get on a high horse and try to define it for them with some junk you found on the internet.
http://raykrueger.blogspot.com/2007/09/best-generic-dao-interface-ever.html

@Alberto using Lambdas you don't have to create lots of FindByXXXX, just create a repository that recieves a Expression <func<t,bool>
as a predicate.
I'd say that's the biggest mistake they've done with the Specification <t class. They've abstracted away a part of the language which they shouldn't have. They should've used Expression <func<t,bool>
. That would solve a lot of problems (not all) that people have with repositories.
 Linkgoron
----
I would like to offer a mild defense of repositories. First I want to wholeheartedly agree that the generic repository and the repository-per-class pattern are useless crap. - Jamie Ide

 http://ayende.com/blog/4784/architecting-in-the-pit-of-doom-the-evils-of-the-repository-abstraction-layer

 The Repository represents the domain’s contract with a data store (another common word we may use here is that it is the seam).
 http://codebetter.com/gregyoung/2009/01/16/ddd-the-generic-repository/

Note that repository doesn’t talk in terms of “data”, it talks in terms of Aggregate Roots. You can tell your repository to add an Aggregate Root into its collection, or you can ask it for a particular Aggregate Root. When you remember that Aggregate Roots may comprise one or many Entities and Value Objects, this makes it fairly different to a traditional DAL that returns you back a set of rows from your database tables.
http://www.codeproject.com/Articles/339725/Domain-Driven-Design-Clear-Your-Concepts-Before-Yo

In such systems it can be worthwhile to build another layer of abstraction over the mapping layer where query construction code is concentrated. ... A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. Client objects construct query specifications declaratively and submit them to Repository for satisfaction. Objects can be added to and removed from the Repository, as they can from a simple collection of objects...
http://martinfowler.com/eaaCatalog/repository.html

Thursday, April 12, 2012

DAL versus BLL

Also, business logic methods from an application can be mapped to the Data Access Layer. So, for example, instead of making a query into a database to fetch all users from several tables the application can call a single method from a DAL which abstracts those database calls.
http://en.wikipedia.org/wiki/Data_access_layer
We'll start with creating a software architecture composed of a Data Access Layer (DAL) using Typed DataSets, a Business Logic Layer (BLL) that enforces custom business rules, and a presentation layer
http://msdn.microsoft.com/en-us/library/aa581778.aspx


The application logic [BLL] orchestrates the DAL, domain classes and services to pursue the expected behavior. The application logic communicates with the presentation layer through view model objects and communicates with the DAL through domain objects. The DAL, in turn, references the model and the ORM assembly.
 http://msdn.microsoft.com/en-us/magazine/hh456393.aspx

Databases are designed to be very fast and efficient with CRUD operations. They are not designed to format telephone numbers, calculate optimum usage and peak periods of utility usage, determine geographic destinations and routings of shipments, and so on. Yet, I have seen all of these cases, and even more complex ones implemented mostly or even wholly inside stored procedures. ... Which tables are affected is business logic as well. The database should not have any knowledge of which tables constitute a customer on the business level. ... But stored procedures should not do anything other than join data when returning data. For updating data it should do exactly and only that and should not interpret the data in any way.
http://www.codeproject.com/Articles/10746/Dude-where-s-my-business-logic

Tuesday, April 10, 2012

Anemic Domain Model

Means "business logic is implemented outside the domain objects." - http://en.wikipedia.org/wiki/Anemic_Domain_Model

What "business logic?" According to the above wikipedia article, the "validation and mutation logic," (presumably excluding basic setter and getter methods? Or are those traits of DTOs, and if so what's left in the domain model objects, which are a super-set of DTOs?).

Description of BLL

Within a BLL objects can further be partitioned into business processes (business activities) and business entities. Business process objects typically implement the controller pattern, i.e. they contain no data elements but have methods that orchestrate interaction among business entities. Business entities typically correspond to entities in the logical domain model, rather than the physical database model. Domain entities are a super-set of data layer entities or data transfer objects, and may aggregate zero or more Dies/DTOs.
[I]n many cases [the BLL is] just the bridge in between the presentation layer and the data access layer with having nothing much, except taking from one and passing to the other... The business entities should meaningfully define considering various types of requirements and functioning of your system. It is recommended to identify the business entities to encapsulate the functional/ UI (User Interface) requirements of your application, rather than define a separate business entity for each table of your database.
Business Rule Layer
This layer is implemented in order to encapsulate your business rules. If you have followed best practices, you will have created a set of documents which describe your business. In the best of cases, you will have a set of use-cases describing your business in precise detail. From this you will have been able to create a class association diagram which will help you create your business layer.

Here we find classes which implement your business functionality. They neither access data (except through the data layer) nor do they bother with the display or presentation of this data to the user. All we are interested in at this point are the complexities of the business itself. By isolating this functionality, we are able to concentrate on the guts of our system without the worry of design, workflow, or database access and related concurrency problems. If the business changes, only the business layer is affected, again considerably simplifying future maintenance and/or enhancements.

http://www.dotnetspider.com/forum/166048-use-n-tier-architechture.aspx

It's also worth emphasizing that putting behavior into the domain objects should not contradict the solid approach of using layering to separate domain logic from such things as persistence and presentation responsibilities. The logic that should be in a domain object is domain logic - validations, calculations, business rules - whatever you like to call it.

http://martinfowler.com/bliki/AnemicDomainModel.html

  In the very center we see the Domain Model, which represents the state and behavior combination that models truth for the organization. ... the Domain Model is only coupled to itself.
  http://jeffreypalermo.com/blog/the-onion-architecture-part-1/


[W]e have decided that Castle Validators are a natural fit for validating data integrity of the EditModel (the type being bound by the model binder when a form is submitted to a controller action).  This is not business rule validation.  This is merely things like: “can the characters that were submitted be parsed into a date, an int, a guid”, etc.  Once we get passed data type validation, then the domain model can work on the more interesting business rules.

 http://jeffreypalermo.com/blog/you-should-not-use-asp.net-mvc-if/

Business logic is the if statements and the loops and the stuff that actually does work...

Miško Hevery - http://www.youtube.com/watch?v=wEhu57pih5w

This offers an excellent benefits in real word scenarios where you have certain methods on an entity that return an IQueryable of T and some methods return List<T>. But then you have business rule filter that needs to be applied on all the collection regardless if the collection is returned as IQueryable of T or IEnumerable of T. From a performance stand point, you really want to leverage executing the business filter on the database if the collection implements IQueryable otherwise fall back to apply the business filter in memory using Linq to object implementation of delegates.

http://weblogs.asp.net/zeeshanhirani/archive/2008/07/31/using-asqueryable-with-linq-to-objects-and-linq-to-sql.aspx

The presentation (that is, the codebehind or controller class) references the application logic, namely a component that implements the application’s use cases. The application logic technically belongs to the business layer or tier, and in very simple cases may be merged with the presentation. This is what happens in some tutorials that are either too simple to really feel the need for isolating application logic in its own layer, or poorly designed and splitting application logic between the presentation and the data access layer (DAL).
 
The application logic orchestrates the DAL, domain classes and services to pursue the expected behavior. The application logic communicates with the presentation layer through view model objects and communicates with the DAL through domain objects. The DAL, in turn, references the model and the ORM assembly.
 http://msdn.microsoft.com/en-us/magazine/hh456393.aspx

Remember that the business logic in Microsoft Dynamics AX can be used though COM from other applications. For example, an X++ script can access the business logic that creates a sales quotation. This underscores the importance of not letting the business logic be dependent on a specific Microsoft Dynamics AX form or report.
  http://msdn.microsoft.com/en-us/library/aa857073.aspx

In deleting a customer however there are many business logic decisions to be taken. Can the customer be deleted? What are the processes that must be performed before and after? What are safeguards that must be checked first? From which tables the records are to be deleted, or updated as a consequence? ... [re phone numbers] It is important that although it is formatting, it's not user interface, and although the urge for any centralization often ends up in the database, this is clearly business logic. Implementing formatting in the business layer eliminates duplicate data, and allows for implementation using a development language rather than shoe horning it into a data language.
http://www.codeproject.com/Articles/10746/Dude-where-s-my-business-logic

Description of DAL

All code that is specific to the underlying data source – such as creating a connection to the database, issuing SELECT, INSERT, UPDATE, and DELETE commands, and so on – should be located in the DAL.

[DAL] methods could simply return a DataSet or DataReader populated by the database query, but ideally these results should be returned using strongly-typed objects. A strongly-typed object is one whose schema is rigidly defined at compile time, whereas the opposite, a loosely-typed object, is one whose schema is not known until runtime.

http://msdn.microsoft.com/en-us/library/aa581776.aspx


Thus, your business tier contains logic for retrieving persistent data from the data-tier and placing it into business objects and, conversely, logic that persists data from business objects into the data tier. This is called data access logic.
 http://www.simple-talk.com/dotnet/.net-framework/.net-application-architecture-the-data-access-layer/


The DAL should have no knowledge at all about the Business Logic Layer. It should, in theory, be able to be called from any client. For example, what if you wanted to seperate the DAL from the application and deploy it as a seperate service exposing itself via WCF?
As mentioned, the DAL operations, e.g. SaveNewsItem should be be accessed by the BO via interfaces, perhaps via dependency injection/IoC.
ng5000 H
2009-01-19 16:18:31

Yes, I agree - it is better that the DAL does not know about the BLL. Instead the DAL should have some sort of abstraction so that the BLL can construct its entites from 'raw data' ie DAOs (or XML or a map of key/value pairs for example). These factories are better separated from the domain logic
 http://www.techques.com/question/1-458098/Business-Logic-Layer-and-Data-Access-layer:-circular-dependency

Static Entity Class

  • The class is not an instance class, so we don't do anything like wrap each list field with a property. This might not be as convenient for the caller, but means we don't have to worry about whether the data item is 'dirty'


Above indicates one use of leaving the model entity as static, at least in SharePoint...

http://www.sharepointnutsandbolts.com/2008/11/simple-data-access-pattern-for.html

Wednesday, April 4, 2012

.NET Event Handlers

Example is the FormClosedEventHandler:
When you create a FormClosedEventHandler delegate, you identify the method that will handle the event. To associate the event with your event handler, add an instance of the delegate to the event.

The associated event has the following signature: public event FormClosedEventHandler FormClosed

This is the signature of the FormClosedEventHandler:

public delegate void FormClosedEventHandler(
Object sender,
FormClosedEventArgs e
)


http://msdn.microsoft.com/en-us/library/system.windows.forms.formclosedeventhandler.aspx

example from a Form1.Designer.cs:
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.Form1_FormClosed)
;

Depending on the precise data the event passes to handlers, you may be able to use an existing event data class in the .NET Framework. For example, if your event handler allows the action associated with the event to be cancelled, you can use the CancelEventArgs class.


http://msdn.microsoft.com/en-us/library/wkzf914z.aspx

On events vs delegates:

[Events] are a modifier [sic] on the delegate type, which adds some restrictions that the compiler enforces and also adds two accessors (similar to the get and set for properties).


http://blog.monstuff.com/archives/000040.html