Friday, September 10, 2010

Souce Code and other materials from Grokking ORMs talk

Here are the slides and source code from my talk at Central PA.NET Code Camp 2010 called Grokking Object-Relational Mappers. The zip file is at https://public.me.com/jwigger and is called Grokking_ORMs_9_10_2010.zip
Here is a few links covered in the talk.
  • Julie Lerman's book, THE book on EF - Programming Entity Framework

  • Frans Bouma, developer of LLBLGen has a lot of interesting, highly opinionated posts on his blog. This post explains his position on why LLBLGen works well with Entity Framework. I will post more on this topic but I do really like the LLBLGen designer and code generator used in combination with EF. Caveat Lector: I received a free developer license of LLBLGen to work on this presentation.

  • NHibernate's Home is here at nhforge.org

  • Upcoming NHibernate 3 Cookbook by Jason Dentler and his Hanselminutes podcast episode

  • Jeremy Miller's MSDN article on persistence ignorance and the unit of work pattern.


  • An explanation of the Select N+1 problem that relates to lazy loading objects.

Code Contracts Support within .NET Framework BCL

Code Contracts were one of the Holy Grails in Computer Science when I received my bachelor’s degree in 1997. Yes, there was research aplenty including my professor Dr. Tim Wahls’ work with the Larch and later Java Modeling Language (JML) approaches to Design By Contracts. However, it was far removed from mainstream programming. Microsoft is poised to change that with Code Contracts.


Code Contracts allow formal specifications to be applied to code. These consist of preconditions, post-conditions, and object invariants. The idea is that code can have its intent made clearer for callers by specifying characteristics of valid use and code that calls code with contracts available can be more reliable by guaranteeing that the contracts aren’t broken. Compile-time checking allows abuse of contracts to be caught very early in the development cycle. An excellent chapter by Jon Skeet from C# in Depth (second edition) covering contracts is available here.


Code Contracts are still a development labs product but Microsoft has already modified some BCL code to support contracts. An earlier draft of Skeet’s chapter illustrates the progress is making. An example showing a case beyond what Code Contracts were NOT aware of is now caught by .NET 4 and the static contract checker! The system random number generator Next function takes two arguments , a lower bound and upper bound, and produces a pseudorandom number >= lower bound and < upper bound. Looking at the BCL source available through Microsoft’s symbol server shows a contract that stipulates that the lower bound can’t be larger than the upper bound.


 int randomNum;  
Random randomGenerator = new Random();
randomNum = randomGenerator.Next(7, 1);
//caught as an exception violation

If we have a function with a precondition that an input number is a valid output of a six-sided die, then the static contract checker uses the contracts built-in to the BCL to support its inference. The static check has found that the output of the Next function will always produce legal input.


 Random randomGenerator = new Random();  
randomNum = randomGenerator.Next(1, 7);

Sunday, August 15, 2010

Cardinal Rule of OO design: Internal Immutability

One of my bedrock OO programming practices is a use of internal immutability. I don’t know if there is an expression that describes this but that is what I call it. By this I mean calls to a procedure or function of a class from within another procedure or function of the same object shouldn’t change the state of any data members of a class. This is often referred to as avoiding side effects. Isn’t it fundamentally essentially that an object consists of both state and behavior? (As an aside, I am omitting the third characteristic of an object, identity.) State that is exposed to another object is allowable, and indeed essential for OO programming.


This practice is etched in mind through prolonged exposure to pain. I began my programming career by supporting the implementation of a subsystem developed by an experienced Fortran developer required to write his first C++ program. The essential flaw to this design was that each column of each database table used represented a data member in a SINGLETON class. What happened was that the state would get overwritten and lost in processing events. Development had started out very promisingly but slowed down by the time I joined the team. I assisted by testing the development code baseline. As I identified test case failures, the developer, who had both a phenomenal work ethic (12 hours a day, 7 days a week) and a keen ability in logic, would painstakingly correct the code. Once corrected, test cases would frequently fail again over time. Once implementation was undertaken, despite the fact that the system had no error-handling logic, it needed babysitting round the clock. I spent my evening onsite for this application querying and updating Oracle records to provide that fault handling. This is an extreme case but was helpful to develop OO religion.


This is a long-time practice of mine but not one that I could formally articulate until I recently read Growing Object-Oriented Software Guided By Tests, written by Steve Freeman and Nat Pryce. This book has a lot of insights into OO design that stand apart from its focus on TDD. Let me quote their wonderful explanation.


“
As well as distinguishing between value and object types (page 13), we
find that we tend towards different programming styles at different
levels in the code. Loosely speaking, we use the message-passing style
we’ve just described between objects, but we tend to use a more
functional style within an object, building up behavior from methods and
values that have no side effects. Features without side effects mean
that we can assemble our code from smaller components, minimizing the
amount of risky shared state. Writing large-scale functional programs is
a topic for a different book, but we find that a little immutability
within the implementation of a class leads to much safer code and that,
if we do a good job, the code reads well too.”

Friday, June 25, 2010

Pradeep's Presentation on Web Client Software Factory

Lately, all of the buzz within ASP.NET has been for ASP.NET MVC. Microsoft’s Patterns and Practice group’s Web Client Software Factory has been around a couple of years. It allows the Model View Presenter (with Passive View) pattern to be applied while still taking advantage of WebForms. I think that the WCSF fits a niche for developments shops with an investment in WebForms can utilize while still offering some benefits of a much more testable and clean development structure. Its recipe-based structure allows for guidance to encourage a consistent approach across the application. Fritz Onion has a nice article providing an overview of the product. WCSF continues to be supported for VS 2010.


In May, I saw an excellent presentation by Pradeep Panthulu on WCSF at a Central PA.NET users group meeting. He has been an architect on a large project that uses WCSF. If I recall correctly, there were at least 40 people on the project. For such a large project, Pradeep found the guidance-based approach of WCSF vital to keep development consistent across the application. Pradeep also showed his architectural expertise by demonstrating the ability to answer questions not directly related to his presentation.


Pradeep found two way data binding to be difficult to accomplish with WCSF. He has ultimately had some success in this area and his blog is a must read for dealing with this scenario. You can read about his modifications to the Object Container Data Source here.


Pradeep also took the time to replace the dependency injection technique supplied by WCSF. Out of the box, WCSF for VS 2008 utilized ObjectBuilder. He replaced it with the newer P&P solution. He found using Unity for DI to not be a performance bottleneck, but application startup was slow. Another problem he encountered was that the team's project would often crash within the visual studio editor when under design view.

Wednesday, June 23, 2010

dealing with EF error

I have been spending a lot of time lately comparing NHibernate with Entity Framework using POCOs. I have been hesitant to blog about potential flaws in the EF because there hasn’t been a lot of writing out there on the subject. One experience I have had shows the holes in what is essentially a 1.0 for POCO support. The mapping error handling in EF must be improved.
If you make a mistake in EF where your class doesn’t map correctly to the model, you are likely to see this error “Mapping and metadata information could not be found for EntityType 'YourNamespace.YourClass'. When not using POCOs with EF, the properties in the class that map to the model are automatically generated. However, with POCOs you are on your own. For troubleshooting I did find it helpful to temporarily turn code generation of classes on and then compare my properties with those generated by the EF templates. It still is error handling that sucks, and it should be improved by Microsoft’s EF team. Ideally, the missing or mistyped property should be spelled out. In fact, when using EF with EntityClasses I received at one point (after mucking around in the model .edmx xml file) this error “The type 'Employee'('EntityType') of the member 'manager' in the conceptual type 'HelloEfModel.Employee' doesn't match with the type 'collection[HelloNHibernate.Employee(Nullable=True,DefaultValue=)]'('CollectionType') of the member 'manager' on the object side type 'HelloNHibernate.Employee'.” That is exactly the kind of error I want to see!

Saturday, May 15, 2010

Introducing SpecFlow

Philly .NET Code Camp 2010 was particularly timely, being in conjunction with the Visual Studio 2010 launch. There were 10 different tracks, with numerous well-known speakers and many exciting new .NET features. Despite all of that, one of the more low-profile talks, by Tony Nguyen, on Behavior Driven Development, proved to be the most exciting to me. This talk on BDD and the relatively new product SpecFlow draws heavily on concepts pioneered in the Ruby world through the Cucumber BDD framework.


I had been unconvinced about the full value of BDD prior to this. I could see potential benefits as part of the development process. However, I was skeptical that users, even highly motivated users that are part of an agile process, would be interest in seeing test results. With SpecFlow, instead of just seeing test results as output, quality assurance or end users can write out requirements.


The approach SpecFlow takes is requirements first. The requirements are written in the natural language Gherkin. Conventions are then use to determine the names of tests that should be written. Instead of being test-first, it is requirement first. Running the test suite will confirm or deny the existence of individual test cases and whether they return the proper result. Requirements writers can write cases in notepad and developers can run test suites integrated into Visual Studio. I haven’t provided any details of the Gherkin language but Tony’s presentation, available here, is one good place to start.


There are some immediate questions that are still worth considering before jumping in using SpecFlow. One important question to consider is that given SpecFlow is a fairly new open source project, will it continue to be actively maintained? Another big question is, will there be end-user buy-in into writing requirements in this fashion? Tony has had some success with end users but reports, after less than a year of development with BDD on his most recent project, less than 100% adoption. Organizational culture and management support will affect adoption greatly. Finally, BDD emphasizes integration style tests. How should unit testing be combined, if at all, with BDD tests? In Tony’s case, there test cases are most done in SpecFlow but unit test cases have been written too by some team members.

Monday, May 3, 2010

Turbo-charge your .NET application – upgrade to .NET 4.0

Even if you aren’t planning to take advantage of any of the new features in the .NET 4.0 Framework, performance alone can justify the upgrade. I recently spent a “Day of Performance” with John Robbins at the April 2010, Wintellect Devscovery conference. He estimates that applications should see a 5-10% increase in performance. This is due to improvements in garbage collection and within the Common Language Runtime (CLR).


Prior to .NET 4.0, garbage collection took over execution within your application. This meant that while garbage collection was running, your code wouldn’t be. In .NET 4.0, garbage collection can now occur in a background thread. Of course, it is always wise to address performance by cutting down on the number of garbage collections that are necessary.


Two performance boosts stand out in the .Net CLR: reflection and StringBuilder appending. Although already fast, Robbins’ performance metrics show that StringBuilder appending is three times as fast. Reflection binding and invoking are also three times as fast. Considering how slow reflection is compared to normal method invocation, this increase is huge. Even if you aren’t directly performing reflection or using a StringBuilder, the NET FCL code uses these classes as building blocks. I have run Robbins’ test suite and encountered the same results on my own PC. I have not directly included the test suite results or test code due to intellectual property concerns.