Monday, April 20, 2009

PRISM: Your guide to a well-structured UI layer in WPF/SilverLight

I’ve had the opportunity to work with Composite Application Guidance for WPF and SilverLight (codenamed “PRISM”) for a couple of months now, and I’m really impressed with what the Patterns & Practices team has shipped this time. The forefather of Prism is in many senses the CAB framework (Composite UI Application Block) and even though I never worked with the CAB Framework myself, I’ve heard that it is a quite large and not that easy to grasp. Prism on the other hand, is quite light weight and the documentation is very concise and well written.

imageThe feedback from CAB has also been that it’s too intrusive; it’s an all or nothing application block and it’s hard to take advantage of the UI composition patterns in existing applications. CAB is from what I have found, meant to be built upon – not with (remember, I haven’t worked with CAB myself, so if you’d like to correct me, please feel free to do so in the comments below). With Prism P&P has taken quite another approach; you’re free to use (or not use) any part of the Composite Application Library in Prism. And you can switch out whatever part that doesn’t suite your needs. For instance, a core principle in Prism is to use an IoC container to make the application highly testable and loosely coupled. And since P&P has developed an IoC container themselves, namely the Microsoft Unity, the examples and the reference application in Prism uses Unity. But if you’d rather use Windsor, StructureMap, Ninject, Autofac, or any other IoC you’re definitely free to do so.

The big difference here’s that where CAB is an application block, Prism is an application guidance. And it guides you towards building applications that are testable, maintainable, multi-targeted and modularized. I’ll dive into these concepts in more details, so let’s start with;

Testability

Everybody tests their code and there are two ways to do it;

a) Manually; set some breakpoints, fire up the app, input some data and push some buttons, let the debugger hit the breakpoints, inspect some variables, and check that everything works as expected (or more often; try to find out why it doesn’t work as expected)

b) Automated; use a testing framework like NUnit, xUnit, or MSTest, write some tests, and then let the machines do the tedious work of verifying that you didn’t break anything you didn’t mean to

If you enjoy your time with the debugger, I won’t try to convince you that automation is good. But I consider myself a pretty lazy programmer and whenever I see an opportunity to automate boring, repetitive tasks, I always try to do so. I prefer to code, not debug, and therefore I automate my testing. Therefore I write unit, integration and UI tests that can be run by an unattended build machine whenever I check in some code changes. I’m a coder, not a debugger.

imageBut writing unit tests can be hard if you haven’t architected you’re classes and methods in a way that opens up for testing. If you instantiate objects inside your classes or in other ways are tightly coupled to other classes, mocking out those classes that are not in the scope of the current unit test will be hard. It’s not impossible, it’s just hard. One of the areas that are notoriously hard to unit test is the “code behind” of graphical components. Because when you instantiate a GUI component, it makes you dependent on a GUI thread when you run the test. On a build machine that’s going to run your tests without any interactive user logged in, this is just not the case; there’s no GUI thread available. And besides; it is bloody annoying and time consuming to have those forms and windows pop up whenever you run your test suite.

Opening your class for dependency injection and using an IoC container to manage the wiring of dependent objects is a well-proven and easy way to solve this problem. Prism explains and shows you how to write your application using an IoC container for the hot-wiring. And as I’ve already mentioned; if you prefer any other IoC Container, it’s totally up to you. But if you choose to not use Unity, you’ll have to be prepared to write some wiring code when initializing your application. Prism comes with the wiring code in form of a class called UnityBootstrapper. And there’s no surprise to the naming here; this class takes care of booting up your application with the Unity IoC container. So if you want to use any other container, you’ll need to rewrite the UnityBootstrapper to suite your choice. Or if you’re lucky; use the source code from someone who’s already done it (like the Castle Windsor adapter and bootstrapper that you can find in the Composite WPF Contrib project over at CodePlex).

 

All right! I think that’s enough for one post. I promised to write about maintainability, multi-targeting and modularity as well, so these will be the subjects for my next post.

Thursday, March 19, 2009

MSDN Live: Slides & Demo Code from “WPF Done Right!”

Me and my colleague Pål Fossmo was invited to give a talk on the Composite Application Guidance (codenamed Prism) on the MSDN Live March 2009 tour. It was great fun, but man we spent many hours preparing for this event! Given the fact that there were 2 of us given the talk, one could assume that this meant just half the work. But, no. So many hours of discussing what to include, how to do the talk, who does what, synchronizing the talk, rehearsal… 

Pål talking about IoC ContainersAnd we thought we had it all figured out as we started out in Stavanger on March 5th. But the feedback from the session suggested that maybe we ought to change the talk a bit. The score wasn’t as good as we’d hoped and we knew we could do better. So we spent the weekend adjusting the talk for Bergen on March 10th. The tip from MSDN General Rune G was clear; more code equals higher score. So we added some quality time in Visual Studio to the talk and the score went up. I must admit that I was perhaps the one that resisted to take “live coding” into the talk in the first place, but seeing the score from Stavanger and Bergen made it pretty clear that this was a bad call. The reason for my resistance was perhaps the fear of ‘something’ going wrong during live coding; staying in PowerPoint is safe, jumping around in Visual Studio is a lot more risky. So many things can go wrong and to stand in front of the crowd with an app that crash and burn is just not much fun. Believe me; I’ve tried it. The demo-God was nice to us though, and I think we got away with some nice demos on how to get started with Prism.

Download slides & codeThe Slides

We spent about half of the talk in PowerPoint and rest was demo. The slides focus on the what and why of Prism, while the how was in Visual Studio. Since one of the key concepts of Prism is the use of an IoC/D I-container, we decided to spend about 8-10 minutes explaining the concepts of Dependency Injection and Inversion of Control using some example code in PowerPoint. Rune Grothaug will publish a screen-recording of the session we did in Oslo, and I guess will be available in a couple of days (I’ll update this article with a link to the recording when it’s available). If you want to take a look on the slides, you can download them here (for you non-Norwegian speaking out there; sorry, the slides are (mostly) in Norwegian, but if you’d like a copy in English just let me know and I’ll translate and upload it).  

Download slides & codeThe Code

The goal of the demo was to show off some of the key concepts in Prism; modules, regions, views and communication. As we started to prepare for this talk, we quickly found the need of a very lightweight and small app that we could demo. The reference application that comes with Prism is really good, and I highly recommend everyone to take a walk around the code from the Patterns & Practices team. It’s nicely done and I think most of us can learn a lot just be reading this code. But alas the reference app is nice and well done; we still wanted something smaller and more fit to our purpose, so we decided to roll our own little composite application. And since Pål is a big fan of Twitter, he built a nice little Twitter client using the concepts from Prism. The demo app, called ‘Kvittre’, consists of a shell with 4 regions and in the main app we had 3 modules; one for the login view, one for posting tweets, and one for listing tweets from those you follow.

For the live demo we wanted to show how to build a module, and since TinyUrl is a popular service to shorten down url’s in tweets we decided to build a module that could take an url, ask the TinyUrl service for a shortened version, and then insert the tiny url into the message. And to demo that you could build a module separate from the ‘main solution’, we coded the module in a separate solution. To test-run the module we added a ‘host application’ project that contained a bootstrapper and a region to host the view from the module. When the module was tested and looked okay, we deployed it back to Kvittre. Kvittre was set up with a DirectoryModuleCatalog that would load any module in a given catalog. Since the 4th region in the Kvittre shell was set up to host the TinyUrl module, the module was loaded and displayed in Kvittre. Then we used an EventAggregator for communicating between modules and wrapped it up by demoing some unit testing of the Login method in Download slides & codethe Presenter class of the LoginView. If you want to check out the code, it’s all wrapped up and ready for download right here.

Tuesday, February 24, 2009

“Legacy Code is Code Without Tests”

I wish I’d come up with that phrase first, but it was Michal Feathers who stated this in his “Working effectively with legacy code”. It’s a great statement, and it pretty much sums up what testing is all about; if you’re not covered by tests, it is hard to refactor and change the code and at the same time know that you didn’t break anything. And if you have code that is resistant to change or that makes you nervous every time you touch it, then you have code that won’t be changed. You have legacy code. And you can try to wrap it, hide it, and forget it, but someday it will blow up. And someday you’ll have to go in there and make it work. But you won’t have any safety net. You’ll have to change something you do not know the reach of, and you’ll have to do it blindfolded and pray that your changes aren’t going to break something somewhere else. But I promise you; it will.

image And man I can tell you; it is good to be a consultant with skills in a technology where the software industry hasn’t had time to produce that much legacy code yet! That alone should be a good enough reason for you to invest some of your time into learning new skills. Skills that make you more valuable in the projects that produce new code, instead of maintaining legacy code that someone else hacked together years ago. It’s those green field projects that are fun!

And because there’s not that much WPF-based apps out there yet, there can still be time to save some poor souls from aiming at that same old pit of failure. The pit of strongly coupled, untestable, monolithic monsters. There’s hope and I believe in the goodness of coders. I believe that we want to make solid code. I believe that we want to produce code that is maintainable and changeable. And I believe that we, the residents of the software community, can make the leap into software craftsmanship. It’s just a matter of making those right choices. And I believe that loose couplings, testability and modularity are definitely the right choices in most cases. These are the key principles that will make you a better person (or at least a better developer).

Loose couplings and testability are tightly coupled (touché!). If you’re doing test-driven development, or behavior-driven development, or any other development practice that use tests to drive the design, you will end up with code that is loosely coupled. And if you’re building an app with loose couplings between modules and classes, you’ll end up with code that lends itself to testing very well. And testable, loosely coupled systems will be easier to maintain and change than a tightly coupled system with no tests to verify your code.

Modularity is another beast though. Modularity is about splitting the application in to pieces that multiple teams can work on in parallel - without getting in the way of each other. Modularity is about scalability and maintainability. Adding new functionality without ending up with a logarithmicimage time/functionality curve is an important factor in software development (maybe not for you and me, but for those white collars* that are deciding whether to fund or close down your project, predictability is extremely important). And modularity is about mastering complexity. How do you master too complex challenges? You break it down in to smaller, more manageable parts. And in software terms those parts are modules.

So if you take these 3 ingredients – loose couplings, testability, and modularity – and you shake it together with WPF (shake, not stir), you’ll have a fantastic opportunity to do WPF right. You’ll end up with code, not legacy code.

imageIf you’re in Stavanger on the 5th of March, Bergen on the 10th, Trondheim on the 12th or in Oslo on the 19th of March, you can hear me and my colleague Pål Fossmo give a talk on this topic at the MSDN Live event.

 

 

* Which btw just managed to bankrupt Iceland and is about to break the back of some of the strongest economies in the world… how the he** did they do that?!