So it seems my pet project has been Ayende-ified; Oren has been so kind to let me have a preview at his posts and that urged me to talk a bit about what NSK is and what it is aimed for.
I started NSK in 2004 in order to have a “one size fits all” demo for the talks and classes I and my colleagues at Managed Designs were holding; all I wanted was a way to showcase topics such as:
- How an O/RM works (Unit of Work, proxies, queries & fetch plan management, …)
- How to implement common presentation design patterns (MVC, MVP, …)
- How to unit test code
Other than having that demo, I also wanted to make everyone able to have it up & running as frictionless as possible, so I:
- Made it open source (choosing IBM’s OSI-approved Common Public License) and downloadable from Sourgeforge
- Had it use the “ubiquitous” Northwind database
I knew from the start that such a db would have impaired my ability to design an effective Domain Model, but I didn’t care ‘cause that was code that I was expected to show (and comment), and not targeted to the casual downloader.
Let’s just have an example: in order to allow me to explain how an O/RM works and avoid early adopters (remember, we are talking about year 2004/2005) fear for “O/RMs black magic”, I defined both a IUnitOfWork interface and my own query object, and then implemented both delegating the real work to NHibernate. I even implemented proxies for a couple of entities in order to show how O/RMs manage concurrency. Frankly, I did not pay much attention to my implementation of UoW/query object/proxies, because that implementation wasn’t neither expected to go live in a “production” system nor looked at as an advice to encapsulate an O/RM. That “poor man’s” O/RM, let me stress about that, was only meant to allow me to talk about how an O/RMs works without having to resort to NHibernate source, which IMHO would have been overkill. And when
DLINQ Linq 2 SQL came to us, I renamed the IUnitOfWork interface to IDataContext in order to better adhere to .NET’s emerging jargon: again, I was only trying to have a “companion demo” which fitted my own presenting needs so, when the “pioneering era of O/RM” relating to the .NET community ended (which, IMHO, happened with Microsoft releasing L2SQL and then EF) I considered my “introduce O/RMs by explaining the inner workings” strategy obsolete, made a branch for those still interested in having a look to that code and had NSK switched to the LINQ side of the Force.
And then came the book (to which, BTW, both me and Dino refer to as “the brick” <g>): we needed a companion demo, and ultimately chose to use NSK so I had to fit into the codebase a bunch of samples covering nearly all the book’s topics, such as:
- The book talks about IoC and unit testing, so I ended implementing custom factories for both ASP.NET MVC (which at the time was in the “v1 beta” timeframe) and WCF in order to inject dependencies and/or mock objects
- the book talks about validation and we wanted to show the capabilities of Enterprise Library’s Validation Application Block (which I still think is pretty gorgeous), so I did put in demos using both the custom attributes and the xml rulesets to validate the domain model
Again, the codebase was intended to be looked at while being guided by the book and not as a fully fledged application (please note that NSK still does not sport a release) or as an example of how to implement a Domain Model. If you look to NSK this way, you will find a lot of thing you would do very differently in a “real” application. Just to make an example: you have a look at the CalculateTotalIncome() method of the Customer class and find the following, pretty sub-optimal, code:
1: public virtual decimal CalculateTotalIncome()
5: decimal income = this.Orders.Sum(o => o.CalculatePrice());
6: return income;
In a “real world” application, should the evaluation of the total income be a mere sum, I’d have the O/RM generating a proper query. But, for the sake of the project, I only wanted both a mockable customer repository and the above shown method in order to set up a unit testing demo for the following service:
1: public virtual decimal CalculateSuggestedDiscountRate(string customerId)
3: Contract.Requires<ArgumentNullException>(customerId != null, "customerId");
4: Contract.Requires<ArgumentException>(!string.IsNullOrWhiteSpace(customerId), "customerId");
6: Customer customer = customerRepository.FindById(customerId);
7: decimal income = customer.CalculateTotalIncome();
8: decimal discount = 0;
9: if (income > 5000)
11: //Suggests a 6% discount if income>5000USD
12: discount = 0.06M;
16: //Suggests a 1% discount for every 1000USD of income
17: discount = income / 100000;
19: return discount;
This way, I could write down the following test:
2: public void Test_Calculation_Of_Suggested_Discount_Rate_For_Customers_With_Total_Income_Of_Less_Than_5000_Dollars()
4: decimal generatedIncome = 3500;
5: string customerId = "FAKE1";
6: var custMockBuilder = new Mock<Customer>();
7: custMockBuilder.Setup(c => c.CalculateTotalIncome()).Returns(generatedIncome);
8: var repoMockBuilder = new Mock<ICustomerRepository>();
9: repoMockBuilder.Setup(r => r.FindById(customerId)).Returns(custMockBuilder.Object);
11: MarketingServices svc = new MarketingServices(repoMockBuilder.Object);
12: Assert.AreEqual<decimal>(0.035M, svc.CalculateSuggestedDiscountRate(customerId));
To cut a long story short: the reader should look neither at the CalculateTotalIncome nor at the CalculateSuggestedDiscountRate service per se, but at the unit test. Think about it as a MSTest + Moq demo, and maybe you’ll get the picture I wanted to give to the reader. Being the code targeted at someone who has attended a class/talk or read the book, I thought there was no way to have someone misunderstanding the scope of the project.
The same goes for the domain model at large: if you take a look at it, you’ll notice that aggregates encapsulation is pretty low; I just managed to:
- define an aggregate root abstraction (the IAggregateRoot interface), and built an eco-system aware of it (i.e. the repositories which uses IAggregateRoot explicit implementation and code contracts to enforce domain logic)
- have the aggregate roots implement factories in order to prevent bad instantiation to happen (builder pattern anyone?)
- encapsulate some navigation properties having the domain model “users” forced to use domain logic (i.e. the, AddProduct method of the Order entity which is the only way to add a product to the order… or avoiding that, from a domain logic perspective)
- added a bunch of domain services (i.e.: GetRelatedProducts, CalculateSuggestedDiscountRate, …) in order to show the differences lying in implementing domain logic within the model and/or by means of services
Again, that was enough for my own needings; demo after demo, technology after technology (code contracts, entity framework POCO mapping, jquery, MVVM) NSK grew up and nearly became the “one size fits all” demo I needed in my talks. Up to late 2010/early 2011, I only managed to update NSK in order to remain useful for my own needings.
All of a sudden, though, “developing” NSK wasn’t fun anymore so I settled down and asked myself what I wanted to do with it; my answer was: “make it a real application under the form of an Amazon-like e-commerce web site”. That would have justified the complexity DDD kicks in and also (hopefully) make the project a foundation for solutions we build at Managed Designs. I opted to go for the CQRS way and started focusing of the front-end: so I quickly implemented a read model and started implementing a couple of user stories only to define a structure for the project (architecture, file system, NuGet-based pre build actions, …), only to discover that such a project is too much of an effort for a single person which is going to develop it in his spare time, so I contacted a bunch of friends in order to ask for their support. Then we stopped committing code and started writing down the user stories that will lead our effort from now on.
That’s why the read model and the domain model appear so similar, being the former a mere database reverse engineering and the latter the model that fitted my own “demoing” needings, but we’ll remove this model (and other code, such as the repositories) as soon as we’ll have the new ones, which will emerge from the user stories. Remember that I *still* need demoes for my talks, so I won’t be able to remove “demoable” code until when I have a replacement for it. The nice part is that we think that the new model will be composed by “real” aggregates and that we’ll switch from SQL server to a NoSQL database, so the “R” and “C” parts are going to be pretty different.
At this very moment, being the “code writing” on a hiatus, the only code I would recommend a casual downloader to look at is the stack that shows the recommended projects onto the home page, which picks the products following the following strategy: “Given all products->Choose the ones we are selling (which, of course, aren’t all the products we have in the db)->Then select only the available ones->Let’s pick up the projection we need within this view”. That happens picking them (the products) by means of an expression tree that is composed while goin’ up the application stack: that’s an idiom we at Managed Designs nicknamed LET (which stands for Layered Expression Trees) and we think that it’s a pretty powerful idiomatic way to express logic in a DDD context. I’ll talk about it at the next local ALT.net event, and dedicate soon a blog post to it.
To sum it up: if you’re looking for a sample application, you’d better search for a project sporting a release version (which is something NSK still doesn’t) or, at least, wait for we to implement some more user stories in order to allow the whole design to consolidate. In the meantime, the project can still be looked at in order to take advantage of some “pills” you could be interested in for your projects, such as:
- JQueryUI integration with ASP.NET MVC (i.e.: the DateTime partial view implemented for both WebFormsEngine and Razor engine)
- MVC and WCF custom factories
- NuGet-based pre build actions in order to easen you first “compile&run” (for those using the recently released v1.6 of NuGet, I’d recommend to have a look at the “package restore” feature)
- Code Contracts aware IRepository interface (don’t focus on actual designs: the real meat lies in having IAggregateRoot + code contracts enforcing your validation even when application code “forgets” to do domain object validation)
- Rss and Atom custom ActionResults for ASP.NET MVC, taking advantage of framework’s built-in serializers
That’s all code you can use (and refactor to satisfy your own needings) due to the license chosen. Enjoy NSK!
P.S.: I know, project’s description on Codeplex sucks bad. Mea culpa: I’ll fix it ASAP.
posted @ martedì 10 gennaio 2012 12.17