CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Unlearn

“You must unlearn what you have learned.”

Yoda to Luke Skywalker Empire Strikes Back 1981

I have become convinced that we are entering a new dawn of software development and we must take time to unlearn that which we know. Over the last 2 months I have been researching building business applications using Silverlight 2.0. In case you don’t know Silverlight 2.0 is a tool used to build Rich Internet Applications (RIA’s) Silverlight 1.1 (released in 2007) gave us a small glimpse of the future of RIA development.  This glimpse proved that Silverlight 1.1 was wholly lacking for business developers (it didn’t even have a button). Silverlight Version 2.0 (released at Mix 08 in Las Vegas, NV) is a different story. Silverlight 2.0 has all of the features a business developer might need. The control set includes: textboxes, buttons, watermark textboxes and, drum roll please, a DataGrid component.

During my research I began experimenting with the DataGrid. I started (in XAML) adding columns to the DataGrid’s columns collection, setting data binding attributes, column widths and header properties. I then turned to the code portion of my research and DataGrid’s ItemSource property to a list of objects. I ran the application and lo-and-behold it worked (not the first time of course but eventually).  After getting my simple grid demo working I wanted to implement a simple, but common use case. I wanted to allow the user to sort the data by clicking on the column.  Here’s how it went:

1. Look for DataGrid properties called something like “AllowSort”
2. Look for header properties that would turn this feature on.
3. Look into the documentation for the DataGrid (samples, online, etc)
4. Download and open the source code for the DataGrid (yup you read that right its available to developers)

I struck out on all accounts. It looked like I would be waiting for a new rev for this feature. I did take one more step though. I turned to my trusty search engine Google and typed in “silverilght 2.0 datagrid sort”. And look what I found: Matt Berseth (http://mattberseth.com/blog/) had already figured this out in a very creative and enlightening way. Matt’s unique solution was to put a HyperlinkButton control into the DataGrid’s Header Content property. The Header object’s Content Property is defined as Object. The normal use case for this property is to specify a string as your header. But this is Silverlight and when a property says it’s an object it’s an object. This means you can replace the header content with a Hyperlink rather than a textbox. This is where my epiphany occurred:

My typical path took me to the control itself. I searched for properties, events and even considered for a moment hacking up a hit test set of code to do this. It hadn’t occurred to me to composite some controls together to do what I wanted.  This is where I told myself I must unlearn what I know.  I must think of new and interesting ways to combine these controls to do new and interesting things.

This epiphany raised its head again over the last 2 weeks. Over the last 6 months we have started the trek down the Agile Development path. This path has included installing and researching agile development applications including:  Nant, Nunit and Subversion.  We are using Nant and Nunit to automate our testing, and in the last two weeks we moved a large quantity of our source code into a Subversion repository. It’s this last application that has provided me with another epiphany.  Source code control in Subversion is “just different” than in Visual SourceSafe (our previous source code provider).  Visual SourceSafe is a pessimistic version control system (you lock files when you check them out) Subversion is just the opposite. All files are worked on in shared mode. Meaning two developers can work on the same file at the same time. It’s up to the developer to merge changes into the development branch of code when conflicts occur. Along with a different philosophy Subversion uses different terms: In Subversion Checkout means get a fresh set of code from the repository, Import means send source code to the repository. Commit means send your changes to the repository. Visual SourceSafe had different meanings for all of these terms.

When I started using Subversion I found it difficult until I told myself what Yoda said: “You must unlearn what you have learned.” I closed the book on Visual SourceSafe and opened a new one on Subversion. I consulted the documentation to see what the Subversion philosophy is and what the terms in Subversion really mean. When I “forgot” what I knew about source code control from the VSS POV things began to become clear and the process of migrating much simpler.

In today’s development world new technologies require new thinking. You need to unlearn what you already know. To find comfort in the unlearning process, take shelter in the words of Jedi Master Obi-Wan Kenobi to Luke Skywalker: “Luke… Let go. Trust the force”. 

crossposted from blog.dashpoint.com

Nhibernate and medium trust

Being sick of all the hassles it took to keep my own server up and running I've moved it to a public hoster. Which does offer asp.net hosting but like many others code is only given medium trust. My site was using nHibernate. That does have serious problems under this trust level. I've been investigating and experimenting to get it up and running. Alas without success. Nevertheless a summary of what I've done. As most web references on this subject are either vague or not specific enough this can help get a better overview. Or perhaps somebody can point me to something I have overlooked.

Medium trust restricts the permissions given to your code. When googling a lot of the links mention the error message That assembly does not allow partially trusted callers. You can get it  when you sign the assemblies of your site. It depends on your hoster. You used to get that when hibernate tries to load a signed assembly with your domain objects. This can be fixed by setting the AllowPartiallyTrustedCallersAttribute on the loading assembly. This has been fixed on the recent production build of nHibernate; a lot of the posts still around deal with a previous version of nHibernate and are a dead end.

The main problem with medium trust is that it inhibits reflection. nHibernate depends heavily on reflection. For lazy load to work nHibernate generates proxies to the domain objects. These proxies are built by reflecting on the domain objects. You can configure nHibernate to work without lazy loading. I gave this path a full try and tried everything I could find on the web and could think of myself.

This is what I did to the configuration

  • Apply the requirepermission="false" in the web.config section of nHibernate
  • Set the hibernate.use_reflection_optimizer in the web.config to false
  • Set the hibernate.bytecode.provider in the web.config to null.

This is what I did in the mapping files

  • Set the lazy attribute of all classes to "false"
  • Set the lazy attribute of all collections to "false"
  • Remove the proxy attribute of all classes

In the domain classes I even made all public members non-virtual. In a normal scenario nHibernate will now completely trip over this, complaining it cannot create a proxy.

On my local machine the site still worked. But on the medium trust host it immediately crashed again on a security exception. The stack trace pointed to the initialization of the reflection optimizer. Huh ? This is where I gave up.

There is an approach on the web which promises a working lazy load even in medium trust. It is supposed to work by replacing the proxyfactory by one which provides pre generated proxies instead of generating them on the fly via reflection. Alas providing you own proxyfactory takes nHibernate 2.0. Which is still in alpha phase. From a maintainability point of view beyond consideration.

Googling around getting nHibernate to work under medium trust is considered important but still takes a lot of effort, also in 2.0. I really hope it is going to work but for me it's back to basics for this project. Not all work has to be done again, the domain model is clear, all I have to do is rewrite the implementation of the repositories. To the UI it's not important how I gets the data as long as it gets them.

The main reason for needing persistence on my site is an index on a selection of my publications. Reading through the results it sometimes does make my toes curl. A lot of the work is pretty old by now and my techniques have really grown over the years. Time for a good update of the contents of the underlying db.

Rhino.Mocks Performance Issue Fixed

Just wanted to quickly note that I tracked down the performance issue in Rhino.Mocks and patched it. I also updated the original post with the new numbers. Enjoy!

Heard Mike Cohn speak at AgileAustin user group

Today I had the pleasure of hearing Mike Cohn speak at an AgileAustin meeting. Below are some of my raw notes. I have not edited them. Just a brain dump of some of the presentation.

- agile is all about continuous improvement
- we cannot predict how an organization will respond to change.
- We cannot plot an agile transition on a ghant chart.
- When we break things apart to a small level, we sometimes lose sight of the whole
- The steps necessary to become good at X cannot be enumerated and have them be correct for more than a single organization
-

Different mental model: CAS, Complex Adaptive System
- many agents acting in parallel
- Control is highly dispersed and decentralized
- Overall system behavior is the result of a huge number of decisions made constantly by many agents

Our organizations need to be networks, not a hierarchy

Success:
Newtonian: Success = closing the gab with the desired state and actual state

CAS view: Success = achieving a good fit with the environment

Agility is different for every company. We need to find how it fits with the environment.

Vision should come from someone influential in the organization.
- Local actions will be taken based on interpretation of the vision. Overall we can't predict local actions based on the communicated vision.

CAS (agile) model of change:
- Behavior is unpredictable and uncontrollable
- Direction is determined through emergence and by many people
- Every effect is also a cause
- Relationships are empowering
- Responsiveness to the environment is the measure of value
- Decisions are based on patterns and tensions
- Leaders are facilitators and supporters

Traditional model of change
- Behavior is predictable and controllable
- Direction is determined by a few leaders
- Every effect has a cause
- Relationships are directive
- Efficiency and reliability are measure of value
- Decisions are based on facts and data
- Leaders are experts and authorities

ADAPT acronym
- Awareness: Before an organization can change, the organization needs to be aware of the need to change. We have to be aware that what we are doing is not working as good as we would like it to work.
- Desire to change
- Ability to work in an agile manner
- Promote early successes to build momentum and get others to follow
- Transfer the impact of agile throughout the organization so that it sticks.

Your API Fails, Who is at Fault?

I decided to stay on the Design by Contract side for just a little bit.  Recently, Raymond Chen posted "If you pass invalid parameters, then all bets are off" in which he goes into parameter validation and basic defensive programming.  Many of the conversations had on the blog take me back to my C++ and early Java days of checking for null pointers, buffer lengths, etc.  This brings me back to some recent conversations I've had about how to make it explicit about what I expect.  Typical defensive behavior looks something like this:

public static void Foreach<T>(this IEnumerable<T> items, Action<T> action)
{
    if (action == null)
        throw new ArgumentNullException("action");

    foreach (var item in items)
        action(item);
}

After all, how many times have you not had any idea what the preconditions are for a given method due to lack of documentation or non-intuitive method naming?  it gets worse when they don't provide much documentation, XML comments or otherwise.  At that point, it's time to break out .NET Reflector and dig deep.  Believe me, I've done it quite a bit lately.

The Erlang Way

The Erlang crowd takes an interesting approach to the issue that I've really been intrigued by.  Joe Armstrong calls this approach "Let it crash" in which you only code to the sunny day scenario, and if the call to it does not conform to the spec, just let it crash.  You can read more about that on the Erlang mailing list here.

Some paragraphs stuck out in my mind.

Check inputs where they are "untrusted"
    - at a human interface
    - a foreign language program

What this basically states is the only time you should do such checks is at the bounds when you have possible untrusted input, such as bounds overflows, unexpected nulls and such.  He goes on to say about letting it crash:

specifications always  say what to  do if everything works  - but never what  to do if the  input conditions are not met - the usual answer is something sensible - but what you're the programmer - In C etc. you  have to write *something* if you detect an error -  in Erlang it's  easy - don't  even bother to write  code that checks for errors - "just let it crash".

So, what Joe advocates is not checking at all, and if they don't conform to the spec, just let it crash, no need for null checks, etc.  But, how would you recover from such a thing?  Joe goes on to say:

Then  write a  *independent* process  that observes  the  crashes (a linked process) -  the independent process should try  to correct the error, if it can't correct  the error it should crash (same principle) - each monitor  should try a  simpler error recovery strategy  - until finally the  error is  fixed (this is  the principle behind  the error recovery tree behaviour).

It's an interesting approach, but proves to a valuable one for parallel processing systems.  As I dig further into more functional programming languages, I'm finding such constructs useful.

Design by Contract Again and DDD

Defensive programming is a key part of Design by Contract.  But, in a way it differs.  With defensive programming, the callee is responsible for determining whether the parameters are valid and if not, throws an exception or otherwise handles it.   DbC with the help of the language helps the caller better understand how to cope with the exception if it can.

Bertrand Meyer wrote a bit about this in the Eiffel documentation here.  But, let's go back to basics. DbC asserts that the contracts (what we expect, what we guarantee, what we maintain) are such a crucial piece of the software, that it's part of the design process.  What that means is that we should write these contract assertions FIRST. 

What do these contract assertions contain?  It normally contains the following:
  • Acceptable/Unacceptable input values and the related meaning
  • Return values and their meaning
  • Exception conditions and why
  • Preconditions (may be weakened by subclasses)
  • Postconditions (may be strengthened by subclasses)
  • Invariants (may be strengthened by subclasses)

So, in effect, I'm still doing TDD/BDD, but an important part of this is identifying my preconditions, postconditions and invariants.  These ideas mesh pretty well with my understanding of BDD and we should be testing those behaviors in our specs.  Some people saw in my previous posts that they were afraid I was de-emphasizing TDD/BDD and that couldn't be further from the truth.  I'm just using another tool in the toolkit to express my intent for my classes, methods, etc.  I'll explain further in a bit down below.

Also, my heavy use of Domain Driven Design patterns help as well.  I mentioned those previously when I talked about Side Effects being Code Smells.  With the combination of intention revealing interfaces which express to the caller what I am intending to do, and my use of assertions not only in the code but also in the documentation as well.  This usually includes using the <exception> XML tag in my code comments.  Something like this is usually pretty effective:

/// <exception cref="T:System.ArgumentNullException"><paramref name="action"/> is null.</exception>

If you haven't read Eric's book, I suggest you take my advice and Peter's advice and do so.

Making It Explicit

Once again, the use of Spec# to enforce these as part of the method signature to me makes sense.  To be able to put the burden back on the client to conform to the contract or else they cannot continue.  And to have static checking to enforce that is pretty powerful as well. 

But, what are we testing here?  Remember that DbC and Spec# can ensure your preconditions, your postconditions and your invariants hold, but they cannot determine whether your code is correct and conforms to the specs.  That's why I think that BDD plays a pretty good role with my use of Spec#. 

DbC and Spec# can also play a role in enforcing things that are harder with BDD, such as enforcing invariants.  BDD does great things by emphasizing behaviors which I'm really on board with.  But, what I mean by being harder is that your invariants may be only private member variables which you are not going to expose to the outside world.  If you are not going to expose them, it makes it harder for your specs to control such behavior.  DbC and Spec# can fill that role.  Let's look at the example of an ArrayList written in Spec#.

public class ArrayList
{
    invariant 0 <= _size && _size <= _items.Length;
    invariant forall { int i in (_size : _items.Length); _itemsIdea == null };  // all unused slots are null

    [NotDelayed]
    public ArrayList (int capacity)
      requires 0 <= capacity otherwise ArgumentOutOfRangeException;
      ensures _size/*Count*/ == 0;
      ensures _items.Length/*Capacity*/ == capacity;
    {
      _items = new object[capacity];
      base();
    }

    public virtual void Clear ()
      ensures Count == 0;
    {
      expose (this) {
        Array.Clear(_items, 0, _size); // Don't need to doc this but we clear the elements so that the gc can reclaim the references.
        assume forall{int i in (0: _size); _itemsIdea == null};  // postcondition of Array.Clear
        _size = 0;
      }
    }

// Rest of code omitted

What I've been able to do is set the inner array to the new capacity, but also ensure that when I do that, my count doesn't go up, but only my capacity.  When I call the Clear method, I need to make sure the inner array is peer consistent by the way of all slots not in the array must be null as well as resetting the size.  We use the expose block to expose to the runtime to have the verifier analyze the code.  By the end of the expose block, we should be peer consistent, else we have issues.  How would we test some of these scenarios in BDD?  Since they are not exposed to the outside world, it's pretty difficult.  What it would be doing is leaving me with black box artifacts that are harder to prove.  Instead, if I were to expose them, it would then break encapsulation which is not necessarily something I want to do.  Instead, Spec# gives me the opportunity to enforce this through the DbC constructs afforded in the language. 

The Dangers of Checked Exceptions

But with this, comes a cost of course.  I recently spoke with a colleague about Spec# and the instant thoughts of checked exceptions in Java came to mind.  Earlier in my career, I was a Java guy who had to deal with those who put large try/catch blocks around methods with checked exceptions and were guilty of just catching and swallowing or catching and rethrowing RuntimeExceptions.  Worse yet, I saw this as a way of breaking encapsulation by throwing exceptions that I didn't think the outside world needed to know about.  I was kind of glad that this feature wasn't brought to C# due to the fact I saw rampant abuse for little benefit.  What people forgot about during the early days of Java that exceptions are meant to be exceptional and not control flow.

How I see Spec# being different is that since we have a static verification tool through the use of Boogie to verify whether those exceptional conditions are valid.  The green squigglies give warnings about possible null values or arguments in ranges, etc.  This gives me further insight into what I can control and what I cannot.  Resharper also has some of those nice features as well, but I've found Boogie to be a bit more helpful with more advanced static verification.

Conclusion

Explicit DbC constructs give us a pretty powerful tool in terms of expressing our domain and our behaviors of our components.  Unfortunately, in C# there are no real valuable implementations that enforce DbC constructs to both the caller and the callee.  And hence Spec# is an important project to come out of Microsoft Research.

Scott Hanselman just posted his interview with the Spec# team on his blog, so if you haven't heard it yet, go ahead and download it now.  It's a great show and it's important that if you find Spec# to be useful, that you press Microsoft to give it to us as a full feature.

WPF, from this to that..Wow!

A few weeks ago, our reference implementation for Prism looked like this.

image

Early on we decided that we needed the RI to have a better look in feel so that it delivered a more real world WPF experience. We hired a design firm to create XAML proofs based on our implementation. The process on their end was two fold. First there we a graphic designer who created non XAML proofs. Then a XAML developer converted those proofs to XAML.

Once we got the proofs, Adam Calderon from Interknowlogy (on our team) team took two weeks, and merged the new XAML into our existing codebase. In the migration, there were a few aspects of the proofs that we decided not to apply because we wouldn't push on the scenarios we need to. However, the changes we did apply, did not require much code rework to the application itself.

This is what came out of that effort, and what was in our last drop.

image

I must admit, I was previously skeptical of the whole designer-developer interaction and what was really possible. I am definitely now a true believer! Great job WPF team!

Mock Framework Benchmarks

UPDATE: I tracked down the issue and committed a patch to Rhino.Mocks. Rhino.Mocks is now much more competetive performance wise, our CI build time nearly halved, and about 4 minutes out of 7 of our test time has disappeared. New numbers below.

I've complained before that Mocking is Slow but I never really dove further into it. Today I decided to actually compare Rhino.Mocks to other mock frameworks on a pure performance basis to see if it was a global problem. I timed 2000 unit tests across 100 classes with 20 tests each. The results were a bit surprising:

Framework TD.NET Time nunit-console Time
Rhino.Mocks old trunk 57.36s 28.82s
Rhino.Mocks new trunk 22.94s 7.59s
Moq trunk 18.30s 5.91s
TypeMock 4.2.3 Reflective Mocks 15.36s 9.35s
TypeMock 4.2.3 Natural Mocks 16.92s 9.56s

That's right, according to these tests, Rhino.Mocks is at least 3 times slower than the other frameworks when under heavy load in TD.NET and five times slower in the console according to these tests. It's also interesting to note that TypeMock is faster than Moq in TD.NET, but slower in the console runner.

While running the Rhino.Mocks tests it is very clear that there is a degrading performance issue. All the other frameworks executed tests with a near constant speed per test, but Rhino.Mocks slowed down noticeably about half way through.

Please feel free to try it yourself, grab the project here. You should be able to just run the 4 strategy .bat files (run-rhino, run-moq, run-tmock-reflective, run-tmock-natural). Let me know if you find anything interesting.

More Posts Next page »



What's New

Who Is Online