Monday, April 30, 2012

Active Record Pattern


Therefore, typical implementations of the Active Record pattern consist of instance properties representing a record’s fields in the database, instance methods that act on that specific record and static methods acting on all records, i.e. the database table or view.
http://misko.hevery.com/2009/05/05/the-problem-with-active-record/


Data Mapper Pattern

Additionally, sometimes people split the Data Mapper part into the mapping part ("this attribute maps to this column") and a separate service part ("here's how to insert data"), which further separates the concerns.
John Feminella - http://stackoverflow.com/questions/1977120/data-mapper-an-domain-object-should-never-call-its-data-mapper


In the DataMapper pattern you have one domain object that holds all the business logic, for exmaple user.getLinkToProfile() (or something similar) but knows nothing about the database in question, in addition to this you have a mapper-object that is responsible for saving, updating, selecting, etc. user objects from the database which would have UserMapper::find(1), UserMapper.save(user)
thr - http://stackoverflow.com/questions/93773/how-does-the-activerecord-pattern-differ-from-the-domain-object-or-data-mapper-p

 http://blog.steveklabnik.com/posts/2012-05-07-mixins--a-refactoring-anti-pattern discusses use of DataMapper to reduce surface area of ActiveRecord classes. Essentially an ActiveRecord should not have any public methods; properties are set by DataMapper or Repository through its constructor.

Sunday, April 29, 2012

Business Logic


In addition to field-level validation, there may be high-level custom business rules that involve different entities or concepts not expressible at the single column level, such as:
  • If a product is discontinued, its UnitPrice cannot be updated
  • An employee's country of residence must be the same as their manager's country of residence
  • A product cannot be discontinued if it is the only product provided by the supplier  
http://msdn.microsoft.com/en-us/library/aa581779.aspx


A Service Layer defines an application's boundary [Cockburn PloP] and its set of available operations from the perspective of interfacing client layers. It encapsulates the application's business logic, controlling transactions and coor-dinating responses in the implementation of its operations.
http://martinfowler.com/eaaCatalog/serviceLayer.html

Operations such as account.AcceptTransaction(transaction) and account.CalculateCurrentBalance() are domain logic which should go on those very same anemic entities.
George Mauer - http://lostechies.com/jimmybogard/2009/12/03/persistence-model-and-domain-anemia/

Each interaction between a client system and a server system contains a certain amount of logic. In some cases this can be as simple as displaying information in the database. In others it may involve many steps of validations and calculations.
http://martinfowler.com/eaaCatalog/transactionScript.html

...your code should either be in the business of doing business logic or in the business of instantiating and wiring other objects together. What this effectively means is that your either have classes with ifs and loops (your business logic) or you have classes with new operators (your factories).  
http://misko.hevery.com/2009/03/30/collaborator-vs-the-factory/

 ...They might, for instance, when changing the sex of an employee, have to go over to the health insurance screen and mark that the person does not need prenatal care. That's what the software is supposed to do for you! That's business logic.
Gregg Young Presentation - http://skillsmatter.com/podcast/design-architecture/architectural-innovation-eventing-event-sourcing/

Raising Exceptions in Components

So, instead of calling the MsgBox function from a component when an exception occurs, the proper thing to do is to use the Visual Basic Err object's Raise method, and hope that the code that the client code using the component has an appropriate error handler defined. Basically, when it comes to handling exceptions, COM components should have the "Something unexpected has happened and I can't continue processing, so whoever called me needs to do something about it" attitude. .. I suggest that all errors that a given class might raise be defined as Public Enums in the class module's General Declaration section.
http://www.informit.com/articles/article.aspx?p=22679&seqNum=5

Presentation Logic vs. Business Logic

How do you know which logic goes in which tier? There is no absolute rule, but a good rule of thumb is the following: If it's a piece of logic that might be executed no matter what type of UI (Web or Windows), it probably should be coded in the middle tier.
http://www.informit.com/articles/article.aspx?p=22679&seqNum=3


The EXEC CICS RECEIVE and EXEC CICS SEND MAP commands are part of the transaction’s presentation logic, while the EXEC CICS READ UPDATE and EXEC CICS REWRITE commands are part of the business logic.
http://publib.boulder.ibm.com/infocenter/cicsts/v2r3/index.jsp?topic=/com.ibm.cics.ts23.doc/dfhp3/dfhp3pu.htm

The part of an application program that performs the required data processing of the business. It refers to the routines that perform the data entry, update, query and report processing, and more specifically to the processing that takes place behind the scenes rather than the presentation logic required to display the data on the screen (GUI processing).
 http://www.pcmag.com/encyclopedia_term/0,1233,t=business+logic&i=39074,00.asp

[S]ome duplication, especially for validation purposes should exist in the client as well. Such rules should be reinforced by the business layer.
http://www.codeproject.com/Articles/10746/Dude-where-s-my-business-logic

Friday, April 27, 2012

Command Pattern vs. Anemic Domain Model

One of the risks of the Command Pattern is you end up with an anemic Domain model, with all the logic pushed out to the commands. By relying on generic commands and reflection, you keep the logic in the domain model, and you don't end up writing that many commands.
Robert Watkins - http://www.corvine.org/blog/archives/2005/09/why_i_love_test.html

Friday, April 20, 2012

Object-Oriented Programming

One of the fundamental principles of object-oriented programming is to localize all logic operating on state to the object holding the state, and to hide an object's internal structures and their state transitions. The emphasis should be on how objects communicate with other objects in the environment when triggered by an event.
 http://msdn.microsoft.com/en-us/magazine/dd882516.aspx

Most PMs end up as property bags. It is either that the ORM framework forces you to use public getter/setters or that programmers make PM a property bag even if the ORM supports private setters. Either case, you end up with classes that expose all (or most) of their inner state through properties which breaks class encapsulation and makes classes more tightly coupled. An almost inevitable side effect of this is violation of Tell Don't Ask and Single Responsibility Principle principles.
 http://www.mehdi-khalili.com/orm-anti-patterns-part-4-persistence-domain-model

A class is a coupling of state and behaviour, where the behaviour modifies that state, and this is called encapsulation. Generally you try and encapsulate as much as possible, which means that the state should be manipulated by the object itself (and only that object). Only for behaviour that cannot be modelled within the class would you delegate to an external class, such as a manager, which is why the existence of manager classes is often considered a sign of poorly-written object-oriented code.
Kylotan - http://gamedev.stackexchange.com/questions/18305/is-domain-driven-design-good-for-games

One can find a quick smell to help identify the places where we may have incorrectly applied SRP and created procedural code by noticing the parameter arguments that are being passed. If we are passing an Employee how are we accessing it? Are we breaking state encapsulation? If we have getters and setters being called in that method we should really be reconsidering whether that code actually falls under the responsibility of our object.

 http://codebetter.com/gregyoung/2010/03/24/the-98th-thing-every-programmer-should-know/

ASP.NET MVC Controller & ViewModels


ASP.NET MVC requests are routed to a controller. It’s the controller that decides what view to call and what data (model) to pass to it. ...
 [U]sing a base class with a categories property and have ViewModel classes inherit from it would just be bloating models with unrelated data and concerns.

  http://www.arrangeactassert.com/when-to-use-html-renderpartial-and-html-renderaction-in-asp-net-mvc-razor-views/

Infrastructure Layer

 Book, which is in the domain layer, only need to know how to communicate through the interface IBookRepository (which also resides in the domain layer). The concrete BookRepository resides in the infrastructure layer which the domain layer knows nothing about. Some people call this the onion architecture

 http://johanleino.wordpress.com/2009/03/12/unity-and-sharepoint-%e2%80%93-part-3/

Wednesday, April 18, 2012

Internal Service, DTOs, and Ceremony Code

Essentially, an internal service's operations will be either queries or commands. When it comes to queries, why not just do the simplest thing possible? In most cases, it's sufficient to just return the data in the exact same form that the data will be displayed in. Quite often, that means a denormalized set of data where the data comes from more than one type of entity/table. There's no reason to send a bunch of entity-mimicking DTO's that reference each other to the client if you're going to use the data to populate a grid.


http://davybrion.com/blog/2012/02/dtos-should-transfer-data-not-entities/

Data transfer object differs from the above two patterns, mainly because it is a distribution pattern and not a data source pattern as above two patterns. Use it mainly when you are working with remote interface and need to make your calls less chatty as each call can get expensive. So usually design an DTO which can be serialized over wire that can carry all the data back to the server for applying further business rules or processing.
CodeToGlory - http://stackoverflow.com/questions/804751/what-is-the-difference-between-the-data-mapper-table-data-gateway-gateway-da

State Pattern Vs. Polymorphic Employee

Plenty of reasons to favor the State Pattern:

In this case, implementing the promote logic in the subclasses would be quite challenging as we can not change the type of a class at runtime. It could be done by changing the Promote method signature to return an Employee. The subclasses could then each implement Promote that returned an appropriate subclass of employee. However, this solution feels contrived. It is also more difficult to understand for a future maintenance programmer and could lead to hard to find bugs.

Another reason we may not wish to have a polymoprhic Employee class is because there may be multiple state objects in a single domain object. What if we need not only to compensate and promote employees based upon their position, but also to assign vacation days based upon the project to which the empoloyee is currently assigned? A situation where we needed a class for TechnicalLeadWhoIsWorkingOnProjectX arises.

Another reason [...]


http://nathan.whiteboard-it.com/archive/2008/09/01/state-pattern.aspx

Tuesday, April 17, 2012

Domain Model

A domain model can be seen as an interface or a pipe between the Requirement Engineering phase and the Design Phase of the software development life cycle.
http://www.site.uottawa.ca/~ssome/UCEdWeb/publis/domainGen.pdf

Rule of thumb: If you are passing around primitive data types among object collaborators, it may be an indication you are not communicating at the right level of abstraction. You need to see whether the primitive data types represent concepts in your domain that you may have missed. 
 http://msdn.microsoft.com/en-us/magazine/dd882516.aspx

Let’s begin by using slightly different names. Let’s call the model of data that you persist the domain model and call the data you manage in the view the view model. I should mention that domain model isn’t exactly a neutral term in software, as it refers to an object model designed according to a number of additional rules. In the scope of this article, I’m not using the meaning that results from the Domain-Driven Design (DDD) methodology. For me, here, the domain model is simply the object model you persist—entity model might be another equivalent—and less confusing—term.
 http://msdn.microsoft.com/en-us/magazine/hh456393.aspx

I'll just add that at the heart of the application, there isn't necessarily *a* Domain Model, but possible *some* Domain Models.
The same application can have several aspects, or contexts, that might be modelled differently.
the cool stuff - all aspects might share the same storage mechanism (i.e. RDBMS tables), and it would fit perfectly in the Domain-driven Onion modelling of the system

 Ken Egozi - http://jeffreypalermo.com/blog/the-onion-architecture-part-1/

GUI will ask Repository to get domain object by id.. and once GUI has the domain object you could navigate it to reach other objects.. This way Domain layer does not need to know anything about repositories..
 StackUnderflow - http://www.techques.com/question/1-458098/Business-Logic-Layer-and-Data-Access-layer:-circular-dependency see also on idea of splitting BLL into Service/Business Logic Layer and Domain Model Layer


The Domain Model is a self-contained component – it doesn’t take dependencies on anything else. What it does is raise events that external code can use to make decisions about which external “service” to call.
http://www.udidahan.com/2008/02/15/from-crud-to-domain-driven-fluency/

The definition fat model means having as many domain objects as needed. Be it reports, validators, filters, entities, strategies and so on.
http://www.thedeveloperday.com/skinny-controllers/

Reused Abstractions Principle

To program to interfaces or not? That is the question...

I introduced this principle 10 years ago when discussing OO design to counter the trend for speculative abstractions in many of the projects I encountered. Most particularly, the trend for putting interfaces everywhere, regardless of whether that interface represented some commonality betweren two or more types of object - which is what they're really for.

So I will stress that "programming to interfaces" is not good OO design, any more than "don't use getters and setters" is. These are overly simplistic formulas that mask more fundamental and nuanced principles. If the only class that ever implements the Customer interface is CustomerImpl, you don't really have polymorphism and substitutability because there is nothing in practice to substitute at runtime. It's fake generality. All you have is indirection and code clutter, which just makes the code harder to understand.
http://codemanship.co.uk/parlezuml/blog/?postid=934

Restricted OO versus Full OO

On "OO-as-we-knew-it-before-DCI" - https://groups.google.com/forum/#!msg/object-composition/umY_w1rXBEw/hyAF-jPgFn4J

Disadvantage of Static Classes

@Mark: Of course not. That wasn't really the point of the example. You still have to instantiate an object of that type in order to call its Copy method. Is there a reason you think that is preferred?Cody Gray Dec 6 '10 at 14:40
1
@Cody Gray: Yes. Static classes can't implement interfaces, so they lead towards tightly coupled code.Mark Seemann Dec 6 '10 at 14:41
http://stackoverflow.com/questions/4367347/constructor-parameters-vs-method-parameters

Sunday, April 15, 2012

Decorator Pattern

See solution (ptomli) at http://stackoverflow.com/questions/1425749/anaemic-domain-models-or-where-to-put-logic

also Mark Seemann's comment which seems to allude to use of the strategy pattern in place of an "evil" enum:
but I would change the Channel type to an abstract type that has a GetProductCode method that takes an IProduct as input. Then you could have two concrete implementations (RetailChannel and TradeChannel) the implement that method differently.



Service Layer


As for calculating Order totals etc. Your Service layer would be the natural home. A SalesOrderCalculator class with LineTotal(LineItem lineItem) and OrderTotal(Order order) methods would be fine. You may also wish to consider creating an appropriate Factory e.g. OrderServices.CreateOrderCalculator() to switch the implementation if required (tax on order discount has country specific rules for instance). This could also form a single entry point to Order services and make finding things easy through IntelliSense.



Most SERVICES discussed in the literature are purely technical and belong in the infrastructure layer. Domain and application SERVICES collaborate with these infrastructure SERVICES. For example, bank might have an application that sends an e-mail to a customer when an account balance falls below a specific threshold. The interface that encapsulates the e-mail system., and perhaps alternate means of notification, is a SERVICE in the infrastructure layer. ... It can be harder to distinguish application SERVICES from domain SERVICES, The application layer is responsible for ordering the notification. The domain layer is responsible for determining if a threshold was met--though this task probably does not call for a SERVICE, because it would fit the responsibility of an "account" object. ... Funds transfer has a meaning in the banking domain language, and it involves fundamental business logic. Technical SERVICES should lack any business meaning at all.



Service: A service is a group of related functionality. Think of it as if you are splitting your architecture horizontally, you have a "Business Logic" layer, if you split that vertically you will have services.


Your service layer methods should reflect the actions that you need to accomplish from a business sense. Frequently I find that my controller Actions match up very closely to service methods.
In your example, I would have the service build and relate to the necessary entities and talk to repos to save them; that way if there is a problem along the way of talking to the repos it can roll itself back and do whatever cleanup is necessary.
Repos should be relatively dumb. Services should do the relationship and business work (barring something like NHib, and maybe even then).

Chad Ruppert - http://stackoverflow.com/questions/1562247/how-much-resposibility-should-my-repository-service-have


Services are used to fetch information from a data source (most likely a repository), process the information and return the result to the caller.
A service class can use multiple repositories to achieve the wanted result. In this layer you can also have a event system which can allow one service to take actions when another service have generated an event.
An example would be that the the UserService calls the FeedService to create a new RSS feed item for each newly created user. ..
Keep in mind that having a Save(myBusinessObject) method in a service can make it hard to extend the application later on. It's better to have methods like IncreateTax, AttachToGroup etc. A Save method is a bit too general (in most cases)
jgauffin - http://stackoverflow.com/questions/5015925/correct-use-of-repository-service-classes

Services perform tasks that the object cannot do for itself. One distinction is that services can access data stores. Your ProductId problem is a pretty good example: if ProductId were a Guid, it would be fine for Product to issue a ProductId in its constructor. In your case, you need to get ProductId from another system so you should enlist a service. – Jamie Ide
 http://stackoverflow.com/questions/756849/ddd-dependecies-between-domain-model-services-and-repositories

Services should care only about the problem domain, not the view that renders results. Return values should be expressed in terms of domain objects, not views.
duffymo - http://stackoverflow.com/questions/3002168/should-a-service-layer-return-view-models-for-an-mvc-application


  1. The service layer is inherently integration code and, as such, most suitable for integration testing (rather than unit testing).
    The advantage of services talking directly to ISession is simplicity, and the ability to use the power of the framework chosen (NHibernate).
http://www.udidahan.com/2008/02/15/from-crud-to-domain-driven-fluency/

It does not have state reflecting the business situation, but it can have state that reflects the progress of a task for the user or the program.
http://martinfowler.com/bliki/AnemicDomainModel.html

In DDD, Services are not the holders of all business logic. They only represent verbs, actions of the domain that are cross-concern to several objects and thus wouldn't fit into one of the entities or aggregate roots without breaking single responsibility principle and creating tight couplings that would muddle the entity.
 ian31 -  http://stackoverflow.com/questions/5214220/ddd-sample-cargorepository-store-could-be-used-in-a-controller

On Passthru's

Our current repository is where all of our queries reside ... i.e. FetchOrders(), FetchOrdersWithLineItems(), FetchOrdersForDate(date), etc. This makes it easy to mock the repository, but also creates a whole bunch of pass-through methods in the service layer (i.e. servicelayer.FetchOrdersForDate(date) returns repository.FetchOrdersForDate(date)).Jess Dec 19 '09 at 17:47
1
That's cool, but you might want to consider methods in the repository e.g. Fetch(), Fetch() and suchlike. These might then be called by FetchOrders() in the service tier. I bet there's a bunch of repeated code you could lose in the repository that way.Jeremy McGee Dec 19 '09 at 20:19


Saturday, April 14, 2012

CUD Operations

When you serialize entity objects such as Customers or Orders to a client over a network, those entities are detached from their data context. The data context no longer tracks their changes or their associations with other objects. This is not an issue as long as the clients are only reading the data. It is also relatively simple to enable clients to add new rows to a database. However, if your application requires that clients be able to update or delete data, then you must attach the entities to a new data context before you call System.Data.Linq.DataContext.SubmitChanges. In addition, if you are using an optimistic concurrency check with original values, then you will also need a way to provide the database both the original entity and the entity as modified. The Attach methods are provided to enable you to put entities into a new data context after they have been detached.


http://msdn.microsoft.com/en-us/library/bb546187(v=vs.110).aspx

Funcs instead of methods?

Consider using a func instead of a use-once method, e.g.

Func<DataContext, IQueryable<Customer>> queryWithoutADataContext =
dc =>
from cust in dc.Customers
where cust.name == "Bob"
select cust;

Func<DataContext, IQueryable<Customer>> moreFiltered =
dc =>
from cust in queryWithoutADataContext(dc)
where cust.IsTall
select cust;

var bobs = queryWithoutADataContext(new DataContext);
var tallbobs = moreFiltered(new DataContext);

Code snippet by David B - http://stackoverflow.com/questions/2028657/linq-datacontext-and-unit-of-work

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