Friday, December 7, 2012

Setting up Session State in MVC

In Global.asax.cs add:

        protected void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started
            if (HttpContext.Current.Session["SearchSettings"] == null)
            {
                HttpContext.Current.Session["SearchSettings"] = 
new SearchSettingsModel
                {
                    DefaultSearchKeyword = "Microsoft", 
                    QueryServiceUrl = "http://spsite/_vti_bin/search.asmx" };
            }
        }

Then in SearchController.cs put:
        public ActionResult SearchSettings()
        {
            var settingsModel = ControllerContext.HttpContext.Session["SearchSettings"] 
as SearchSettingsModel;

            return View(settingsModel);
        }

        [HttpPost]
        public ActionResult SearchSettings(SearchSettingsModel model,
 string returnUrl)
        {
            if (ModelState.IsValid)
            {

            }

            // If we got this far, something failed, redisplay form
            return RedirectToAction("SearchSettings"); 
//per http://blog.jorritsalverda.nl/2010/03/10/maintainable-mvc-post-redirect-get-pattern/
        }


Wednesday, October 31, 2012

Forms folder missing error

http://aarohblah.blogspot.com/2009/12/issues-and-solutions-in-sharepoint.html provides the simple fix for this error "Could not find a part of the path" that occurs when deploying a workflow feature.

Add <Property Key="RegisterForms" Value="*.xsn" /> to the Feature.xml

Tuesday, October 16, 2012

Sunday, October 14, 2012

Spline Keyframes

Tool here to calculate the first and second control points of Bezier curve used in a SplineDoubleKeyFrame

Saturday, October 6, 2012

MVC vs MVVM

Model-View-Controller works very well if you want to have a single model and multiple views of the data, which is something you often want with a list. However, there are also many scenarios where you may want to have multiple models of the same or related data. In that sort of scenario, you may want to consider the Model-View-ViewModel that has become so popular.
http://loosexaml.wordpress.com/model-view-controller-for-a-list/

Wednesday, August 29, 2012

WPF Properties

Any dependency property can be an inherited property, simply by specifying a flag in the metadata provided when registering that property with the dependency property system of WPF. 
http://msdn.microsoft.com/en-us/magazine/cc700358.aspx

Thursday, August 23, 2012

Identifying Workflow Instance

Match the ows_WorkflowInstanceID value from the Xml tab of Task item in SharePoint Manager 2007 with the WorkflowInstanceID query string variable of the Doc lib item's particular workflow status (Wrkstat.aspx) page.

Some tips on accessing object model: http://web.archive.org/web/20090403083734/http://mossytips.blogspot.com/2008/08/how-to-get-workflow-instance-of-task.html
and Shelton's "Part 4 - Custom Workflow Forms (TaskEdit Form).pdf p. 14.

Saturday, August 11, 2012

Asynchronous Silverlight

Silverlight 2 web services still have thread affinity with the UI thread, it's just now there is some behind the scenes processing taking place. When a web service call is made, it is placed in a queue to be actioned by the UI thread. ...  Once the call completes the ...Completed handler is invoked on the same thread that the ...Async call was made. 
This is with regard to the proxy generated by the WCF service reference wizard.
http://www.codeproject.com/Articles/31018/Synchronous-Web-Service-Calls-with-Silverlight-Dis

Thursday, August 9, 2012

Working around GetListItemsAsync

First to step through References.cs comment out [System.Diagnostics.DebuggerStepThroughAttribute()] of ListsSoapClient. Tried making OnBeginGetListItems public and calling from custom class.cs without success. See this for possible workaround.
I could just chain call backs but IMO that is code smell (i.e. a leaky abstraction) because it "violate[s] implementation visibility by requiring consumers to know that they shouldn't expect to receive a return value [...]".

Wednesday, August 8, 2012

Asynchronous Events

(ProTip: If I initialize the event to an empty delegate{}, I don’t have to null-check the event before raising it.)  
http://www.headspring.com/blog/developer-deep-dive/using-waithandles-to-test-asynchronous-events/

Versioning Scheme


Consider a version format of X.Y.Z (Major.Minor.Patch). Bug fixes not affecting the API increment the patch version, backwards compatible API additions/changes increment the minor version, and backwards incompatible API changes increment the major version.
http://semver.org/

Synchronous completion

If the synchronous completion of the call is detected in the AsyncCallback delegate, it is probable that the thread that initiated the asynchronous operation is the current thread.
http://msdn.microsoft.com/en-us/library/system.iasyncresult.completedsynchronously.aspx

Thursday, July 26, 2012

Project Server

Microsoft's Project Server appears to be a good example of a combination of BLL/DAL and CQRS. See http://msdn.microsoft.com/en-us/library/office/ee767687.aspx

Saturday, July 21, 2012

Procedural Code Complements OO Objects

When we create applications we 1) Create classes that encapsulate behavior 2) Create procedural code to make objects interact
Source: AppDev

Friday, July 20, 2012

Predicate vs. Func

Predicate is just a special cased Func<T, bool> really, introduced before all of the Func and most of the Action delegates came along. I suspect that if we'd already had Func and Action in their various guises, Predicate wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func and Action are used for widely disparate purposes.
Jon Skeet - http://stackoverflow.com/questions/4317479/func-vs-action-vs-predicate

See example usage in Array.Find<T>:
http://msdn.microsoft.com/en-us/library/bfcke1bz.aspx

Sunday, July 15, 2012

Try/catch logic = Code smell

be mindful of using the try/catch block as logic. It's a code smell that my nose has a particular dislike for, and often used by newbies or those of us in a big hurry to meet a deadline.
Chris Ballance
 http://stackoverflow.com/questions/248961/c-sharp-using-statement-catch-error

RAII

The replacement for RAII in .NET is the using-pattern, which works almost as well once you get used to it.
Rasmus Faber
http://stackoverflow.com/questions/173670/why-is-there-no-raii-in-net 

There's some similar threads if you search for them but basicly what it boils down to is that if you want to RAII on .NET simply implement an IDisposable type and use the "using" statement to get deterministic Disposal
Torbjörn Gyllebring

Saturday, July 7, 2012

BIO-ENV in practice - Brainstorming

Confluence of e-commerce application  and Employee time tracking system (ETTS).
- In E-commerce, there are products, orders, and customers.
- In ETTS, there are days employees, employee-days, and employees employer

If using an e-commerce software, utilize products screen -- for managing products for ETTS purposes where a product is a day, or maybe the other way around, employee should be a product? No, because there is only one "customer", i.e. Employer? Actually, that's fine so:
"Employees, EmployeeDays, Employer (single)

EmployeeDay has status attribute ("present," "late", "sick"). Employee day time span (i.e. equiv "order") has status enum.


Who filled the order? i.e. Who marked attendance? Another order attribute or member collection based on who updated version controlled item in Sharepoint list?


Event sourcing solution? MyEDB with Sharepoint list backing store? Silverlight front-end calling Sharepoint WS?


Event = "any change of the state of a system sub-environment"


Responders responsible for creating events or alternatively Environment triggrs/invokes a change event.
Different types of events have different attributes. So EmployeeDayRecordedEvent e, has e.personwhorecordedthis, e.calendarday, e.employeeid
:= Event types = SP Content Types?

Events track state changes.

BLL? i.e. where to put rule that only first login of day creates EmplDayRecEvent? In the presentation logic? One of the environments?
Events generated in the client environment (persisted in local log files via Client App Log File Repository)

Event types = Environments ?

All business rules (BR) are represented by responder definition, i.e. responder "responds to given environment state by changing that state"

Biological Environment in Code (BEinC, pron. "Bank").

How to set Global Employee Day Record Env State with new state (Employee X set for present today).

"Passive entities" - Client responder for posting events observes that login event occured, looks through local event logs for another one from today; if none, does ajax post or WS call, which inserts event to Global Shared record store for client side events.

So essentially, client controls synchronization  of select events to shared Event store, itself an environment - "Shared Event Store Environment" (SESE).

Global Env subscribes to any SESE state it chooses. i.e. to update its own state resulting in a state update event (Base event type).

E.g. event tuple: (eventid, employeeid, status, calendarday)
EmplStateChangeEvent.


How to pivot this event store to view resembling the original spreadsheet file?


A "Service" (e.g. WCF service) is a collection of operations (service is made available from a service host) that facilitate synchronization of events between environments (e.g. a client event store, a user's mental model, or the global Env).
Service synchronizes both ways, i.e. a query would be the reverse direction (see Seemann's 'IContractMapper' example).


In SP can code responders as workflows?


Lists:


SharedClientEnv (person, machine, loginorlogout); attach workflow: if first in day, insert EmplStateChangeEvent to EmplDayRecordEnv


EmployeeDayRecordEnv (Sharepoint event list type for calendar view?) (person, calday, status)


If a DDD entity can be identified by primary key in DB table (see Seemann p.214), i.e. a DDD Entity can be a record, then a EmployeeDayRecordEnv record can be an Entity?!

Wednesday, July 4, 2012

Branches, Tags, and the Trunk -- and Stem


On a daily basis, developers in branches merge changes from the trunk into their branchMerge branch features back into trunk when you're ready to deployBug fixes are performed on the trunk then tagged and re-deployed
http://weblogs.asp.net/bsimser/archive/2008/05/06/day-to-day-with-subversion.aspx

So, development mostly occurs in the trunk (with the exception of cases where isolation e.g. of new features necessitates separation through branching), with branches corresponding to major releases (1.1, 1.2...).

The important takeaway is that for every main version of the software you are maintaining, you have a branch that contains the latest version of code for that version.
gregmac - http://stackoverflow.com/questions/16142/what-do-branch-tag-and-trunk-really-mean


Stem technique of version control: http://www.ronaldwidha.net/2009/10/04/branch-management-pattern-part-2-development-on-branch-stemming/

Never commit to master.The way of working that has worked well for us is the “never commit to master” approach (replace “master” with “default” if you use mercurial). 
http://www.stateofcode.com/2013/05/never-commit-to-master/

Friday, June 29, 2012

Integration Testing


We can still use the VSTS unit testing framework to write integration tests. The difference though, comes from the point of view that the test methods will not substitute in mocks for the dependencies, allowing the tests to run end-to-end testing a module/function of code right through.
 http://quickduck.com/blog/2008/02/18/unit-testing-mocking-and-dependency-injection/

Friday, June 22, 2012

Monday, June 18, 2012

Singleton Anti-Pattern

Always ask for a reference! (don’t create, or look-up a reference in global space aka Singleton design anti-pattern) 
 http://misko.hevery.com/2008/10/21/dependency-injection-myth-reference-passing/

Law of Demeter

Notice how the LoginPage violates this. It calls a new on User Repository. The issue here is that LoginPage is breaking a the Law of Demeter. LoginPage is asking for the Database even though it itself has no need for the Database (This greatly hinders testability as explained here). You can tell since LoginPage does not invoke any method on the Database.
 http://misko.hevery.com/2008/10/21/dependency-injection-myth-reference-passing/

Policy.CurrentPeriod().Renew()
...There are a couple of problems with this approach. First, I'm clearly violating the Law of Demeter. A method M of an object O should invoke only the methods of the following kinds of objects: itself, its parameters, any objects it creates or instantiates, or its direct component objects.
http://msdn.microsoft.com/en-us/magazine/dd419654.aspx - and goes on to explain how using Policy.Renew() ; i.e. invoking on Policy as the aggregate root is more expressive and less problematic.

Tuesday, June 12, 2012

DTOs are not Objects

A DTO is a representation of such a piece of data mapped into an object-oriented language. That still doesn’t make them objects in the sense of encapsulation. It would be impossible. Since all input is suspect, we can hardly enforce any invariants at all.
 http://blog.ploeh.dk/2011/05/31/AtTheBoundariesApplicationsAreNotObjectOriented.aspx


You usually can’t send the domain object itself, because it’s tied in a web of fine-grained local inter-object references. So you take all the data that the client needs and bundle it in a particular object for the transfer—hence the term.

Fowler http://www.drdobbs.com/errant-architectures/184414966

Monday, June 11, 2012

ORM vs. Repository

All other ORMs I've ever encountered are completely at odds with the Repository pattern. This goes for both L2S and EF, because they require not only that you derive from a particular base class, but also that Entities have default constructors. 
Mark Seemann http://www.manning-sandbox.com/message.jspa?messageID=105843

Monday, June 4, 2012

1NF vis-a-vis Business Rules

A practical way to think of 1NF in the above table is to ask a series of questions about the relationships that records (rows) can have between entities (tables) or attributes (columns), based on given business rules or constraints. For example, could a Subscriber record relate to many Email Address records? Could an Email Address record relate to many Subscriber records?
 http://en.wikipedia.org/wiki/First_normal_form

DCA Components

[T]he ... DCA paradigm ... explicitly describes high-level system features. The object space is partitioned into Components, where a component is an encapsulation of a number of domain objects. A component is characterized by its provided and required operations; its internal structure is invisible from its outside.
http://heim.ifi.uio.no/~trygver/2006/09-JavaZone/mvc-dca.pdf - Contrasts DCA with MVC

Wednesday, May 30, 2012

DDD vs. DCI

With DDD you end up with either "Use-case-specific logic scattered across domain model creating logical dependency to use-cases. Unstable (frequently changing) domain model." or services with "zillions of calls to property setters and getters, low level of code re-use, entity logic scattered across services, tight coupling to domain layer"

With DCI "Use-case-bound domain behavior injected into domain object by the app"
http://www.slideshare.net/johaneltes/dci-with-groovy

Sunday, May 27, 2012

DCI - My Take

DCI tries to solve the problem of how to model transactions. It introduces notions such as Roles and Contexts which your domain objects adopt and interact within respectively. The problem is deciding now what to name your domain objects and to which to assign said roles? I pretty much disagree for instance that an account should be responsible for transferring money to another account; this is simply too anthropomorphic. If accounts are and should be dumb objects then why are they conferred the knowledge of how to perform money transfers?


I still like the idea of having broker objects like servant or avatar who in the user's mental model perform the act of taking money from one dumb account and placing it into another. Why should the account be smart? or possibly a "clerk" object who depending on the context plays the role of account closer, password resetter, withdrawer, depositor, issue escalater, etc.

TS/ADM vs. DM

One of the key benefits of a domain model approach is that it hides the complexity of the different components behind the core objects of the problem domain. I like to think that in a transaction script model, the locus of control is placed outside of your core objects. In a well designed domain model, the locus of control is contained within your core objects (even if big pieces of functionality are still implemented in external services).
http://charliedigital.com/2009/07/29/domain-models-anemic-domain-models-and-transaction-scripts-oh-my/

Traits vs. Interfaces

Orthogonal concepts really. Interfaces are contracts, while traits code-reuse vehicles. I believe they are analogous to extension methods in C# and roles in DCI -- and possibly the delegate design pattern. In architectural terms they are complementary:

"creating traits that fulfill the capabilities required by an interface is the ideal use case  - rdlowrey http://stackoverflow.com/questions/9205083/php-traits-vs-interfaces

Saturday, May 26, 2012

Extension Methods

In my last project, I used extension method to attach Validate() methods to business objects. I justified this because the business objects where serializable data transfer objects and will be used in diffrent domains as they where general ecommerce entities such as product, customer, merchant etc. Well in diffrent domains the business rules may be diffrent as well so I encapsulated my late bound validation logic in a Validate method attahced to the base class of my data transfer objects.
Athens - http://stackoverflow.com/questions/487904/what-advantages-of-extension-methods-have-you-found

Specflow

"I call this project 'specs', I didin't call this 'tests'. ... These are literally executable specifications ... and if you kind of think about that in a design sense, you usually write down the specifications of what you are going to build first; then you go ahead and build what you're going to build based on those specifications -- that in a nutshell is BDD.
Testing on the other hand, if you think about science, you might come up with a theory, then you might execute some tests against that theory ... testing usually comes later; I think that's a mental block for a lot of people."
http://specflow.org/specflow/screencast.aspx

Thursday, May 24, 2012

Aggregate Roots


As we saw above, in the original creation of the Visitor entity by the Referrer, the visitor class wasn’t the aggregate root. Yet, in the user registration use case, the Visitor entity was the aggregate root. ... Aggregate roots aren’t a structural property of the domain model.
http://www.udidahan.com/2009/06/29/dont-create-aggregate-roots/ [so Dahan says aggregate roots  can vary by context?]

Aggregate Boundaries

Nothing outside the Aggregate boundary can hold a reference to anything inside, except to the root Entity.  The root Entity can hand references to the internal Entities to other objects, but they can only use them transiently (within a single method or block).
 http://lostechies.com/jimmybogard/2010/02/04/strengthening-your-domain-a-primer/

Domain Services

Domain services are the coordinators, allowing higher level functionality between many different smaller parts.  These would include things like OrderProcessor, ProductFinder, FundsTransferService, and so on.  Since Domain Services are first-class citizens of our domain model, their names and usages should be part of the Ubiquitous Language.  Meanings and responsibilities should make sense to the stakeholders or domain experts.

 http://lostechies.com/jimmybogard/2008/08/21/services-in-domain-driven-design/

Abstract Factory


The standard solution if you need short-lived or dynamically created objects is to use an injected Abstract Factory.

Static vs. Abstract Factory

The key idea of static factory method is to gain control over object creation and delegate it from constructor to static method. The decision of object to be created is like in Abstract Factory made ouside the method (in common case, but not allways). While the key (!) idea of Factory Method is to delegate decision of what instance of class to create inside Factory Method. E.g. classic Singleton implementation is a special case of static factory method.  
Grygoriy Gonchar -http://stackoverflow.com/questions/929021/what-are-static-factory-methods-in-java

Tuesday, May 15, 2012

Invariants vs. Contextual Validation


Invariants are the rules that cannot ever be broken about an entity, aggregate or VO
Contextual validation is a check that for a particular action, the entity, aggregate or VO is valid at that point.

Monday, May 14, 2012

Information Expert

Basically, put code in the same object with the data. This sounds simple, but I continually see "data only" and "code only" objects. That is the way procedural programming did things, and it is the natural result of focusing on the process while writing code. OO programming requires a certain level of design work before coding starts, and applying the Information Expert pattern is critical to that effort.
http://thinkingthroughjava.blogspot.com/2011/05/grasping-gang-of-four.html

Sunday, May 13, 2012

Transaction Script = ADM?

It would seem that your project might be suffering the side effects of an anemic domain model. As I have observed that these models tend to be used mostly with a transaction script style design, I will use these two terms interchangeably.
 http://charliedigital.com/2009/07/29/domain-models-anemic-domain-models-and-transaction-scripts-oh-my/

What I’ve achieved by applying the DDD patterns is the elimination of those transaction scripts and (most) services. The transaction script (e.g. struts action in a web application if you’re so inclined) is simply responsible for finding an appropriate entry-point into the domain, then telling that domain class to do some work.
 http://evan.bottch.com/2007/12/06/factory-and-repository-in-the-domain/

Domain Logic

[The Anemic Domain Model] [n]ecessitates a separate business layer to contain the logic otherwise located in a domain model. It also means that domain model's objects cannot guarantee their correctness at any moment, because their validation and mutation logic is placed somewhere outside (most likely in multiple places).
http://en.wikipedia.org/wiki/Anemic_Domain_Model

but...
[Some are] just technical constraints, according to Dahan: “The business doesn’t care that username fields are 8 characters. Usernames have to be unique for technical reasons to be able to select customers to check details”. Rules that are not part of genuine domain logic do not have to be implemented in the domain model, suggested he, because they do not model the domain. They may be deployed to a separate tier.
http://agile.dzone.com/news/biggest-mistakes-teams-make

Udi again:
Validation of string lengths, data ranges, etc is not domain logic and is best handled elsewhere (and a topic for a different post). The same goes for uniqueness.
http://www.udidahan.com/2009/06/29/dont-create-aggregate-roots/

Saturday, May 12, 2012

Application or Domain?

An additional question you could ask is: if, in the future, I need to build another application on top of this domain model (e.g. a web service or a rich client), would I still need to deal with the concept of a Channel? 
Mark Seemann - http://stackoverflow.com/questions/1425749/anaemic-domain-models-or-where-to-put-logic

Thursday, May 10, 2012

Workflows in DDD

Pawson says of simple task assignment systems:

What these two design principles explicitly disallow is the idea that upon completing Task A, the workflow engine regains control and then issues Task B, either to the same user or another: the conventional notion of workflow. Rather, these two design principles reflect the fact that real business processes reside in the heads of the staff, and that is the best place for them.
http://blog.nakedobjects.org/2007/11/19/workflow-a-triumph-of-hope-over-experience/

On another note, in a previous blog he alluded to direct manipulation. I would take his task system a step further and create a world model app where a user figure can be attached with task objects, e.g. by dropping them into a bucket the avatar carries. Object collections attached to avatars could be color coded or shaped in a way that easily recognizable. Thusly, transferring objects between entities is a lot more direct than using commands and/or context menus operating on tables.

Monday, May 7, 2012

CQRS

In regular client-server development, the server is responsible for providing the client with all CRUD (create, read, update, and delete) capabilities. However, when users look at data they do not often require it to be up to date to the second (given that they often look at the same screen for several seconds to minutes at a time). As such, retrieving data from the same table as that being used for highly consistent transaction processing creates contention resulting in poor performance for all CRUD actions under higher load.
  http://www.udidahan.com/2008/08/11/command-query-separation-and-soa/

Querying: - Have a look to Users, what are they really interested in? - It's not searching, it's finding; - It's not refreshing, it's looking for events
 Alberto Brandolini - http://vimeo.com/16054927 - 41:10

Sunday, May 6, 2012

Aggregate Roots

The biggest rule to keep in mind is that aggregate roots are the only kind of entity to which your software may hold a reference. 
 http://msdn.microsoft.com/en-us/magazine/dd419654.aspx

Instead of worrying too much about aggregate boundaries, we greatly reduced the relative boundaries of roots, until it was a use-case per use-case basis that determined where we drew our boundaries.
http://lostechies.com/jimmybogard/2009/09/11/wither-the-repository/ - failure of ARs

Contexts vs. Modules

Contexts are subsystems (in code different assemblies) within a domain. Each context has its own ubiquitous language; this provides context for domain entities within a given subsystem (Context).

A Context is further broken down into modules which are separated by namespaces.

see http://msdn.microsoft.com/en-us/magazine/dd419654.aspx

Entities vs. Value Objects

A value object can become an entity depending on the situation. ... If the requirement of the search functionality of your application says that, the search criteria should be saved in the database and the user can do the same search from the list of saved search criteria’s. In this scenario SearchCriteria has its own identity and thus it is an entity instead of being a value object. ... 
remember that Aggregate Roots may comprise one or many Entities and Value Objects
http://www.codeproject.com/Articles/339725/Domain-Driven-Design-Clear-Your-Concepts-Before-Yo

Value objects are immutable. see fig 2 example in http://msdn.microsoft.com/en-us/magazine/dd419654.aspx

Friday, May 4, 2012

Domain Entities

Main concern of entities should be keeping track of business state - that's enough of a responsibility and they shouldn't be concerned with validation. ...
[W]hether an entity is "valid" depends on its state and its context. George Polevoy points this out nicely in his answer and I share his opinion.
 Marijn - http://stackoverflow.com/questions/5818898/where-to-put-global-rules-validation-in-ddd

The above appears to contrast with the following advice:


Also your example seems to imply that your object can exist in an invalid state, this should be avoided, your domain object should always be in a valid state.
Kdeveloper - http://programmers.stackexchange.com/questions/70734/ddd-a-rookies-unanswered-questions


Oder is both a noun and a verb. The "Order" is the object that created as a result of "Ordering". Like any good class, it has both data and behavior (and I don't mean getters and setters). The behavior is the dynamic process that goes with the data, i.e., the ordering workflow. "Order" is the controller.
Doug Knesek -  http://stackoverflow.com/questions/1468218/domain-driven-design-where-does-the-workflow-logic-lie

 When a domain object begins to contain too many responsibilities, we start to break out those extra responsibilities into things like value objects and domain services.
 http://lostechies.com/jimmybogard/2010/03/30/strengthening-your-domain-the-double-dispatch-pattern/

Factories


But still the creation logic is kind of separate from the rest of the logic as it’s only needed during creation time and not during the rest of the lifecycle of an object. Thus when creation logic gets complex enough, like calling repositories, you should spinoff this separate concern to another object, a factory object.
 http://programmers.stackexchange.com/questions/70734/ddd-a-rookies-unanswered-questions

Wednesday, May 2, 2012

Active Record vs. DDD


  1. If i have an estate and this contains regions in the country and these contain houses, the user can add new regions to the estate and houses to regions and view the houses details.
    Does this sound like something that warrents DDD or am I trying to fit something in that just doesnt fit, I cant believe this, as nearly all web based systems are just reflections over data at their core and merely provide facilities for the users to perform basic crud methods on a system. Would you model the crud methods e.g. AddRegion as a domain method or just at the service level?
    Sorry to be a pain, but this is one of the biggest hurdles I always have with DDD, if you can suggest any reading or articles, I would be extremely grateful (where did I put Erics book…)

  2. udidahan Says:
    Andrew,
    That kind of behavior can be built using the Active Record pattern instead of the Domain Model pattern. As you said, it is simple data manipulation and, as such, doesn’t require it. That said, DDD is broader than the Domain Model pattern and there are many other useful elements to it that can still be applicable.
http://www.udidahan.com/2008/02/15/from-crud-to-domain-driven-fluency/

With the Active Record Design Pattern we will focus on persistence as a responsibility rather than as a service.
 http://web.archive.org/web/20110625073754/http://davidhayden.com/blog/dave/archive/2006/06/10/2984.aspx

DDD Examples


  1. For example, I am working on some software right now where you basically have an estate which can have a number of sites and all I seem to be modelling is Estate.AddSite, Estate.RemoveSite etc. And the only thing I seem to be putting in my domain object is validation e.g. the Site description cannot be blank…
    Would you class these as domain methods or just service layer methods?
    I think you’re right in terms of this takes a whole different mind set !

  2. udidahan Says:
    Andrew,
    I think that the issue is that the UI you’re supporting is exposing that kind of functionality to the user. DDD applies to UI design as well.
    The code in the post is indeed the implementation of service layer methods.

see main article http://www.udidahan.com/2008/02/15/from-crud-to-domain-driven-fluency/

More examples:
http://www.udidahan.com/2008/02/29/how-to-create-fully-encapsulated-domain-models/

http://msdn.microsoft.com/en-us/magazine/dd419654.aspx

By Jimmy Bogart: http://vimeo.com/43598193 He demonstrates how to transform an anemic domain model to a "wicked" domain model. One of the objectives of doing DDD he says is to protect the code from developer mistakes. The way to do so is to remove operations on properties of model objects from the calling to code to the object itself and make as much object state as necessary private (encapsulation). He also demonstrates how to refactor a switch statement down to the enum equivalent in .NET which is a pattern whereby an abstract class representing the enum (and having similar functionality) contains private classes that inherit from the outer abstract class. These private classes do/return whatever was in the case blocks. The abstract class exposes instances of these classes via separate public static getter methods with names that match enum names, and so the calling code gets polymorphic behavior based on what's returned.

DDD/OO vs. Relational Model

Foreign keys are artifacts of relational data model. Object model operates with the concept of container. So, Order contains a collection of Order Lines. Order Line contains Product, etc.

http://stackoverflow.com/questions/728040/ddd-related-entities-in-master-detail-relationships



Domain Entities

Applying commands/method invocations to an entity or aggregate root can be seen as an application of a function to a data structure where the result of the function application is an identical data structure with different data and/or version
 http://en.wikipedia.org/wiki/Domain-driven_design implies a key characteristic of entities is statefulness

Persistence Ignorance

Your questions and doubts ring an interesting alarm here, I think you went a bit too far in your interpretation of a "rich domain model". Richness doesn't go as far as implying that persistence logic must be handled by the domain objects, in other words, no, they shouldn't know how to save and delete themselves (at least not explicitely, though Hibernate actually adds some persistence logic transparently). This is often referred to as persistence ignorance.
I suggest that you keep the existing DAO injection system (a nice thing to have for unit testing) and leave the persistence layer as is while trying to move some business logic to your entities where it's fit. A good starting point to do that is to identify Aggregates and establish your Aggregate Roots. They'll often contain more business logic than the other entities.
However, this is not to say domain objects should contain all logic (especially not logic needed by many other objects across the application, which often belongs in Services).
 ian31 - http://stackoverflow.com/questions/4708689/ddd-where-to-put-persistence-logic-and-when-to-use-orm-mapping

Tuesday, May 1, 2012

DDD Lazy Loading

Now that our CustomerRepository can save customers as well as associated addresses in a decoupled manner we need to move onto the next problem, reconstituting our customer object with an address. As others have mentioned we may want to Lazy Load the address since there will be instances when it isn't needed.
public class Customer {
    public int addressKey;
    public Address Address {
       get {
         if(address == null) {
            address = new AddressRepository().Load(addressKey);
        }
         return address;
       }
 http://web.archive.org/web/20100420152400/http://steve.emxsoftware.com/Domain%20Driven%20Design/DDD%20Reconstituting%20objects%20from%20multiple%20Repositories Note! He goes on to say this is NOT the optimal solution (too much coupling)

Domain Model vs. BLL

Just to be clear, I like to think of a Business Model and Business Logic as two separate layers. Your business model are your POCOs (Plain old CLR objects). Your business logic layer would be responsible for performing validations, transactions, etc using both your business model and an interface to your DAL that could be wired up a number of ways (Spring, Castle, or your own home grown IoC container).

Trent -  http://www.techques.com/question/1-458098/Business-Logic-Layer-and-Data-Access-layer:-circular-dependency

I'd like to remove the coupling to allow us to support different address repositories as we can with the .Save within our CustomerRepository (via RepositoryFactory). I'd also like to remove any knowledge of repositories from my domain objects. Although it isn't always possible I prefer for application code to have knowledge of repositories NOT my domain objects.
 http://web.archive.org/web/20100420152400/http://steve.emxsoftware.com/Domain%20Driven%20Design/DDD%20Reconstituting%20objects%20from%20multiple%20Repositories

Project Structure

Samples in links.

http://stackoverflow.com/questions/5384246/ioc-and-managing-interfaces - David comment - note: reiterates that Domain Logic library should reference nothing.

 http://stackoverflow.com/questions/7742858/ioc-and-interfaces - Gregory A Beamer comment - note where "Test" type projects in subareas.

http://www.techques.com/question/1-458098/Business-Logic-Layer-and-Data-Access-layer:-circular-dependency - Craig Wilson comment - note repository implementations in separate projects

Layer-Specific Models

There seems to be consensus that each layer should have its own model. In addition to the core Domain Model and the ViewModel, there's also the "Persistence Model." Comment from SO:

  1. The persistance library(s) may have a different model and I may have a view model on the experience library(s). Gregory A Beamer - http://stackoverflow.com/questions/7742858/ioc-and-interfaces
The Domain Model and Data Access libraries both define a class named Product. The Domain Product is the important class that encapsulates the Domain concept of a Product. The Data Access Product class is only an artifact of the Entity Framework wizard. It can easily be renamed or made internal.
Mark Seemann - Dependency Injection in .NET p50

PM is a property bag while DM is about business logic and behavior

http://www.mehdi-khalili.com/orm-anti-patterns-part-4-persistence-domain-model

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