The Degrees of Unit Testing

Three Degrees of Unit Testing

I apologize for the length of this. I’m very passionate about this topic, and there is so much to say. The three styles of testing really are different, and explaining them does take some room!

Any amount of unit testing, done almost any way, adds value to a code base. Regardless of how and when the tests were written, as long as they are reliable and quick, and prove the code does what we think it does, I’m in favor of them. But that is not to say there are not degrees of goodness within the scope of unit testing, especially around when the tests are conceived.

My point in this post is to show how the benefits of unit testing increase the closer you get to letting the tests drive both the implementation and design of the code as it is written. For those of you who have never heard of Test Driven Development (TDD) or have never really tried it, I’m hoping this opens some eyes.

The Basics – Tests After Coding

For most people, this is what comes to mind when thinking about writing unit tests – I write my code, then I write tests for it. This activity, by definition, occurs after code has be written and is an extra task. Let’s look at an example:

// Calculator class
public String calculate(String calculation) throws Exception {
  calculation = calculation.trim();
  String[] pieces = calculation.split(" ");

  int first = Integer.parseInt(pieces[0]);
  int second = Integer.parseInt(pieces[2]);
  String operand = pieces[1].trim();

  switch(operand) {
    case "+" : return Integer.toString(first + second);
    case "-" : return Integer.toString(first - second);
    case "*" : return Integer.toString(first * second);
    case "/" : return Integer.toString(first / second);

  throw new Exception("No calculation found");

// Calculator tests
public void testCalculations() throws Exception {
  Calculator c = new Calculator();

  assertEquals("3", c.calculate("1 + 2"));
  assertEquals("1", c.calculate("2 - 1"));
  assertEquals("8", c.calculate("2 * 4"));
  assertEquals("2", c.calculate("8 / 4"));

  try {
  } catch(Exception e) {

Here we see a simple case of an isolated method, where testing after the code is written is easy. No dependencies, simple inputs and outputs, no problem. As the implementation gets more complicated, though, and dependencies creep in, and code gets longer, testing this code becomes much harder. Here, for example, is a simple Point of Sale system that uses an inventory system to retrieve information a barcode just scanned and a display to show the information retrieved. Here is that code along with a test I wrote. (note I had to fake out some of the complexity to make my point. I’ve seen each and every behavior mentioned in lots of production code, however!)

Display and Inventory classes

public class Display {
  public static Display getInstance() { return new Display(); }

  private Display() {}

  public void showError(String errorMessage) { DisplayService.showError(errorMessage); }
  public void displayItem(Item item) { DisplayService.displayItem(item); }

public class DisplayConfig {}

public class DisplayService {
  private static Item lastItem;

  public static void showError(String errorMessage) {}
  public static void displayItem(Item item) {
  // do the real stuff for displaying an item and save
  // the item so we can test this method
  lastItem = item;

  public static void configure(DisplayConfig config) {
    // configuration code

  // WARNING - testing only!!!
  public static Item getLastItem() { return lastItem; }
public class Inventory {
  public static Inventory getInstance() { return new Inventory(); }
  private Inventory() {}

  public Item getItem(String barcode) { return InventoryService.getItem(barcode); }

public class InventoryConfig {}

public class InventoryService {
  public static Item getItem(String barcode) {
    try {
    } catch (InterruptedException e) {}

    Item item = new Item();

    return item;

  public static void configure(InventoryConfig config) {
  // configuration stuff


public class Item {
  private String name;
  private String price;

  public String getName() { return name; }
  public void setName(String name) { = name;}
  public String getPrice() { return price; }
  public void setPrice(String price) { this.price = price; }


public class POS {
  public void doSale(String barcode) {
    if(barcode == null) {
      Display.getInstance().showError("Invalid barcode scanned");



public class POSTests {
  public void myTest() {
    DisplayConfig dConfig = new DisplayConfig();
    // 10 lines ofsetup code hidden

    InventoryConfig iConfig = new InventoryConfig();
    // 15 lines of setup code hidden

    POS pos = new POS();

    Item item = DisplayService.getLastItem();
    assertEquals("foo", item.getName());
    assertEquals("1.99", item.getPrice());

Now, testing becomes harder because the code was likely not written with testability in mind. The design doesn’t easily support testing small pieces, and there frequently aren’t hooks into the written code to allow it to be tested. So, instead of fixing the design to make things more testable, fewer tests are written and hacks are put into place to allow for testing. On top of that, the dependencies in the code require a lot more setup to let us test our little piece, and they also tend to make tests take longer to run and run less reliably.

However, this is the kind of testing most developers do, as it is what we’ve learned over our careers. It provides partial test coverage, usually of the happy-path cases, which is an improvement over not having tests at all. But since testing is done after the functionality is completed, it is viewed as an “extra activity”, which means it is the first thing dropped when time run short.

Test First Programming

In this style of development, a significant amount of up-front thought and design go into an implementation. Once the design is decided upon, the code is then written by creating a test before code, and repeating that until the implementation is complete.

This is completely identical, in terms of outcomes, to the Test After case, when the problem is very simple. But when the problem gets larger, with dependencies and more complicated coding, you tend to get more code and path coverage due to writing less code to satisfy each test. You also begin to use the tests as feedback into the quality of the design — as tests become harder to write as the code becomes more tightly coupled, which leads to design improvements along the way. The codebase grows as the tests grow, so you get coverage of happy path and error conditions as well. That’s a bonus for this kind of testing.

To start, this is a UML diagram I might have come up with as thinking about solving the same problem from above. The difference in who I might think about this is that making the design testable becomes a first-class design decision. So, instead of using singletons or static classes, I rely entirely on interfaces and the Dependency Inversion Principal to keep things loosely coupled.

Test First Design UML

To implement this, we might start with the concrete implementation of the real Display and Inventory classes, according to the contracts defined in their interfaces. Among the design choices we would make would be to avoid Singletons and static classes, because both make testing more difficult. As our first step for the Inventory class, for instance, we’d make a list of test cases we’d like to implement:

Inventory Test List

  • Will return an item when passed a valid barcode
  • Throws an exception when no item found for a valid barcode
  • Throws an exception when passed a null barcode
  • Throws an exception for an invalid barcode
  • Throws an exception of all information not available to construct an Item

That would be my first pass at a test list, knowing I might find more as I go. One interesting thing that did come up as I was building this is that I realized BarCode is an abstraction that probably needs to be written and have its own tests (validation on construction for the most part). Next step is to write our first test to implement the design we created above:


public void AppropriateItemRetrievedWhenGivenCorrectBarcode() {
  InventoryRepository repository = new InventoryRepository(connection);
  Item expectedItem = new Item("Coke", "$1.99");

  Item item = repository.getItem("validBarcode");

  assertEquals(expectedItem, item);

Before we write any application code, we write our test. This serves as an exploration of the interface and as documentation of how our class will work. In this case, I am using the Repository pattern to encapsulate database operations. I add a test object, use my repository to retrieve it, and make sure it is the same object. From just writing this test, I found I missed the addItem() method in my InventoryRepository and found my Item class needs an equality operator. Easy things to add!

After writing this test, we’d confirm our system won’t compile yet, since we haven’t written any application code yet (hence the TestFirst name). We’d write empty shells of all appropriate classes, adding just enough to make the test compile and fail for the correct reason of not having the appropriate code written yet.

Lastly, I’d repeat these tests for the rest of the InventoryRepository class and then PhysicalDisplay class, followed by the PointOfSale class, working from the bottom up. At this point, I’d expect to have three main application classes written, along with the POD class of Item, and tests for the three main classes. Each class would be thoroughly tested, as we designed our system to be testable and implemented each class one test at a time.

The downside with Test First is that you tend to stick to close to the original design as you’re incrementally writing tests. This means the learning and investigation in the construction process was still very front-loaded.

Test Driven Development

Now, I know I’ve been doing a great job of hiding my preference here, but I’m going to go ahead now and admit to it. I’m a TDD fan. I’ve been doing it since 1999 or so, it is the primary way I write any non-trivial code, and there is nothing better that I’ve found in my 30+ years in the software industry.

The thought process behind TDD is that every move you make while writing code is an experiment, an experiment of how you can satisfy an example through a small amount of code. And after each experiment completes successfully, you spend a few minutes ensuring the code remains simple, readable, and changeable, to support your next experiment. There’s really not any more to it.

What follows is a portion of a larger example of this, done in steps, because TDD is done in small steps. The complete example is available on github. In addition to the tests/experiments and code, there are also complete and explicit checkin comments for each step of the way.

The first thing to notice here is we’re not taking time up front to come up with a design. Part of the Test Driven approach is that you start with your first experiment, write code, and iterate to the minimal design that supports your code. While some believe this is an indication TDD is against design, it’s more true that TDD is a tool to allow design to evolve constantly rather than being concentrated up front.

To build our system, we’ll work outside-in, meaning we’ll look at our system as a whole and write our first experiment to implement a sliver of behavior from the entry-point of our application, then dig in and implement the internals one piece at a time.

Point of Sale Experiment List

  • Given a barcode, display the corresponding name and price
  • Given a different barcode, display the corresponding name and price
  • Given a null barcode, show the appropriate error
  • Given an invalid barcode, show the appropriate error

Thinking about shape of this problem, we need our PointOfSale class and someplace to display the output. This Display class is important, because it is how we’re going to tell our experiment is successful. Everything else will come from thinking about the design as we go.

PointOfSale tests

public class PointOfSaleTests {
  public void correctNameAndPriceShownWhenBarcodeScanned() { 
    Display display = new Display();
    PointOfSale pos = new PointOfSale(display);


    assertEquals("Coke", display.getDisplayedName());
    assertEquals("$1.99", display.getDisplayedPrice());

As we create the shells of our classes and start to implement the code to make this experiment a success, we’ll discover our Display class has a showItem(String name, String price) method our PointOfSale class calls, and also some testing-only methods to get the item details provided through showItem(). This drives out an interface over the Display class that holds just the application method, while the TestDouble we create will have the methods to get the item back for us to confirm. This sounds complicated, but let me show you the code for it.

PointOfSale implementation

public class PointOfSale {
  private DisplayIF display;

  public PointOfSale(DisplayIF display) { this.display = display; }
  public void doSale(String validBarCode) { display.showItem("Coke", "$1.99"); }

public interface DisplayIF {
  void showItem(String name, String price);

// This is a TestDouble, a class written only to allow your design to be tested
public class Display implements DisplayIF {
  private String displayedName;
  private String displayedPrice;

// Method called by application code, to be extracted to interface
  public void showItem(String name, String price) {
    displayedName = name;
    displayedPrice = price;

// Testing-only methods
public String getDisplayedName() { return displayedName; }
public String getDisplayedPrice() { return displayedPrice; }

Again, there is a lot more detail in GitHub, and there is even a lot more detail you can learn from someone who already knows how this technique works.

As you do this, as you create small experiments and implement the minimal code to satisfy them, your system will grow. Do this a hundred times, and you have a small system. Repeat it a thousand, and you have a larger one. And you can keep going, because this scales as large as you like. Since you keep things clean and simple after each experiment finishes, your code is always understandable and easy to change.

It’s just that simple.


At the end of the day, code with tests is better than code without tests. Testing after you write the code is likely to cover the happy paths and some of the error cases, but doesn’t do anything to improve the design. Writing tests before you write code lets you cover more of the error cases, but again generally doesn’t help you with the design. Going all the way to TDD, however, gets you clean code, nearly total test coverage, and a design and is simple and easy to maintain.

TDD is considered controversial by many. I’m really not sure why.

Agile 2016 – Requesting Help for Submissions

Agile2016 Submissions : Asking for Help

Submitting a session proposal for a major conference can be a daunting task, especially if it is your first time. You’re putting your thoughts and ideas out there, knowing that a team of experts will read your words and eventually come to a decision about whether your submission is selected for the final program.

Everyone on each track team knows exactly how you feel, because we’ve all done it, too. Fortunately for us, we were able to ask for feedback from experts and peers while we crafted our sessions. In many cases, that feedback was instrumental in creating a successful submission.

In keeping with the Agile principle of rapid feedback, we’d like you to know that you can get that very same kind of feedback on your submissions, too. All you have to do is ask!

Asking for Help

On the form where you create your proposal, you’ll find three large, colorful buttons used to submit your changes. These buttons represent the stages through which your submission can pass. These stages are important, because they define how the track team will treat your proposal.

In the Draft stage, you can incrementally create and improve their submission for as long as they want. You’re basically alone during this time, although you can still receive public comments on your content.

The Ask For Help stage is where you can ask members of your track team to review and give feedback on your content. The track team members are experts in the subject matter of their tracks and in knowing what it takes to create a great submission. They will answer questions, offer advice, and do anything you need to help make your submission as perfect as possible. One note – no feedback is offered until you Ask for Help!!!

Please use this help early and often in creating your submission. You have an entire team of people per track who are ready and willing to help you create a great session. All you have to do is ask them!

The final stage, Ready for Evaluation, is for sessions the author views as complete, well structured, and ready to be evaluated for inclusion in the final program. No help will be offered in this stage. Track team members may ask clarifying questions as they evaluate all submissions, but the assumption is that you’re ready for that evaluation.

Final Thoughts

Thanks for reading this far. Everyone involved with the program side of the conference truly wants our submitters to succeed. Help is there for each of you – all you have to do is ask.

For more information

Additional guidance and advice is available on the Agile 2016 Conference site. This will tell you about deadlines and expectations, and also show an example of a well-crafted submission.

Introduction to the Theory of Constraints


I’m obviously a big fan of the Agile methods and Lean/Kanban, as evidenced by how the teams on which I work, consult, or participate use aspects of each for their chosen processes. One of the underlying philosophies of both Agile and Lean/Kanban is the Theory of Constraints (ToC). The Theory of Constraints was developed by Eliyahu Goldratt in the early 1980s to describe how workflows can be understood and improved by focusing on the bottlenecks that constrain the flow of value through the system being measured.

Goldratt explained his reasoning in three novels, The Goal, Critical Chain, and It’s Not Luck. In each of these, different aspects of the ToC are described through mildly entertaining characters and story lines. The first book, The Goal, describes the ToC itself and the Process of Ongoing Improvements (POOGI). Critical Chain talks about Critical Chain Management, a style of thinking that takes the concept of a critical path for a project and expands it to support multiple projects. And finally, It’s Not Luck introduces Goldratt’s Thinking Processes, which are orderly patterns of thinking that help you understand the current situation, define the intended future state, and chart a path from to that future. All great reads, highly recommended.

The Theory of Constraints

His most important point, however, is the ToC and advice about how to apply it. In a nutshell, the ToC boils down to understanding how value flows through your production system, learning where the bottlenecks are, and iterating over improving the efficiency and effectiveness of processing at the bottlenecks. He gives the outline of a process to follow in this improvement, called the 5 Focusing Steps:

  1. Identify the constraint in your system,
  2. Exploit the constraint by making sure that this particular part of your workflow is busy and productive all the time,
  3. Subordinate everything to the constraint by reducing production eveywhere else in your system to avoid having work pile up, waiting to be processed,
  4. Elevate the constraint by improving its ability to process the value by adding capacity, changing the nature of the work, hiring, and so on,
  5. Return to the first step to find the new constraint in the system.

This process never stops, as there is always exactly one bottleneck in a system, and you can always discuss ways to eliminate it.

In The Goal, Goldratt writes a pretty approachable example of the Theory of Constraints in practice when he describes a Boy Scout march the protagonist, Alex, leads with his son. His job is to take the whole troop on a trip through the woods to a camping site before nightfall. The boys start marching through the woods, and for various reasons they aren’t making the kind of progress that he hoped for. One boy in particular, Herbie, is moving a lot more slowly than the rest, and he is both slowing down everyone behind him and allowing everyone in front of him to spread out so far that they can’t keep track of each other.

Through some careful thinking, Alex understands that Herbie is the limiting factor, or constraint, in how fast the team can march. So he exploits how fast Herbie can march by putting him at the front of the line of boys, so that he can always keep moving, and and subordinates the progress of every other boy by telling each to keep a 10 foot margin behind the boy in front. Now everyone is marching at the same rate, and the length of the column is fixed for the most part. Since the speed is now constrained by how fast Herbie can march, he elevates that speed by offloading the junk in Herbie’s pack to the other boys, which lets Herbie and the whole troop march faster. They arrive at their destination, all are happy, and Alex learns a valuable lesson he can take back to work the next day.

It’s a better story in the book, but you get the idea. The ToC is actually a pretty simple theory, but it has amazing applicability to so many situations. Read the books and judge for yourself.

Why Should You Care?

The whole reason why I’m writing about this is that I believe the Theory of Constraints can be used to explain and justify the processes and practices that are part of the individual Agile methods. In future blog posts, I want to take a typical team and talk about how you can optimize the progress made by that team through applying the ToC to the constraints of that team.

I plan on writing posts about the importance of good and important stories, the criticality of acceptance tests to avoiding unnecessary work, and then discuss the Extreme Programming engineering practices of Pair Programming, Refactoring, Test Driven Development, and Continuous Integration/Deployment.

Thanks for reading this far, and I’m looking forward to writing the rest of this series over time.


Additional Reading

A Life Changing Event

After almost 8 years at Asynchrony, I resigned my position as VP of Engineering on Thursday to take a new position working with some of my old friends. The times at Asynchrony were some of the best times in my career, and I feel privileged to have worked with so many bright, driven, passionate people. The reason for this move has nothing to do with Asynchrony – I consider them to be one of the good guys in the industry. They get Agile there, they get Lean/Kanban, and they get delivering quality software. I will miss them, I will  miss the challenges, and I will miss calling myself an Asynchronite.

But, old chapters close in our lives, and new chapters open, and this is one of those times.

I have accepted a position with Tier3, working alongside my old Patterns and Practices friends, Jim Newkirk, Scott Densmore, Tim Shakarian, Brad Wilson, Ade Miller (I think there are one or two more that I’m leaving out, but I only heard the whole list once. Apologies if I left someone off), as well as other teammates I’m very eager to meet. In my new role, I will be Product Owner, community leader, and one of the public faces of Tier3’s Platform as a Service family of offerings. And I even get to write some code!

I have a ton to learn, about the space, the product, the team and people, and that’s probably just touching the surface. I’ve been consulting, mentoring, and training for half of my career, and I’m excited about moving back into the product world. I get to work with world class engineers and an exciting company to create, to quote Ron Jeffries’ words from oh, so long ago, Something Magnificent.

new Chapter().Next().Open();

— bab

Re-energizing a Standup Meeting with Kanban

Problem: Standup meetings are more like status meetings than a collaboration meeting for the team.


  • The whole standup meeting is run by the Scrum Master, with no one doing or saying anything until called upon.
  • People on the team report their status back to the Scrum Master or team lead. No one or few people speak to the rest of the team, and interaction between people is pretty rare.
  • Its difficult for people to gain an integrated picture of team status and progress across all the user stories. Individuals report around a circle, describing their progress against individual tasks on user stories, but no one is reporting on or focusing on the progress of the stories themselves.

In summary, all the data reported in the standup meeting is focused on reporting task status back to the Scrum Master, little collaborative conversation occurs, and no complete picture of progress in delivering user stories is to be found.

Solution: Change the standup meeting to focus on collaboration and the flow of value through the team. Change the level of conversation from talking about tasks, which represent effort, to talking about the user stories promised for the current iteration. Doing this promotes cross-team member discussion about the work and how they can complete it. This takes the Scrum Master out of the middle of the conversations and lets the team talk about what matters to them.

Method: The way I help teams focus more on the flow of user stories and value is to make the stories more visible parts of the standup. The Scrum Task Board is fine for showing the flow of tasks through their workflow, but user stories have other elements to their workflow, such as any sort of code reviews or business focused reviews. After getting the team in the habit of talking about tasks and their states, just to get them used to talking about their work, I like to introduce a Kanban board.

Kanban boards are used to represent both the course user stories take from the time a team starts working on them through the time that a team delivers that story, and the current status of all of the stories in play for that sprint. Having this visual representation of the work has a drastic effect on the standup and the team. They stop looking at me, the Scrum Master, and they start looking at the board. They start talking about the stories, where they are, what issues they need help with, discussions about when they’ll be finished with their current phase of work and ready to be moved forward… In other words, they begin collaborating. Its magical 🙂

For those of you who have never seen a Kanban board, this is what one looks like:


This board models the workflow defined by the team. In this case, stories committed to the sprint begin in the Sprint Backlog column, and then move through Story Review, Development, Testing, Review, and then finally Done. During a sprint, small cards that represent each user story move across the board from left to right representing the work done to each item. Here is a board populated with work:


Here we see user stories in varies stages of completion. Having this board as the focus of the standup allows the team to talk about the progress of user stories, and not get overly concerned with low level details that confuse the big picture.

Conclusion: On the team that I’ve been coaching for the past couple of months, introducing a Kanban board was the key to changing the standup meeting from being an exercise in status reporting to a productive, useful collaborative event. We learned how to focus on issues and the flow of value throughout our sprint, and to ignore the noise of personal status. Unanimously throughout the team, we agree that our new standups are much more productive in helping us deliver on our promises each sprint.

“You get what you measure” versus “What you measure, you can manage” – The Agile Metrics Dichotomy

(I just reinstalled Windows Live Writer and reconnected it to my blog, and it pulled down some drafts I wrote years ago. So, I have no idea when I actually wrote this, what the context was that was in my head, but it seems like a decent article. So I’m posting it :))

I’ve long been a fan of the “You get what you measure” school of metrics doubters, especially in agile projects. Its really easy to decide to measure something, have the people being measured act in a totally predictable and rational way, and screw up a team beyond belief. For example, if I measure how productive individual programmers are, then its to the advantage of individuals to focus on their own work and spend less (or no!) time helping others. Completely kills teamwork 🙁

On the other hand, in our environment, where we are responsible for delivering projects to clients on time, on budget, etc, we have a responsibility and an obligation to know what is happening in each of our project teams. Management needs to know if we’re going to make our deadlines, customers need to know what is coming, project leaders need to be able to manage and set expectations, we need to satisfy contractual obligations, etc.

The challenge is to come up with a set of metrics and an unobtrusive way to gather data that allows metrics to be reported to interested stakeholders, and yet does not disrupt the team.

This is my challenge. And what follows are the basic metrics I’ve been using as a way of meeting that challenge. These metrics are balanced between measuring things that meaningfully describe what’s happening inside teams, and creating the right environment and behaviors that will help the team reach its goals rather than incent poor behavior.

How Fast Are We Going?

The gold standard of progress on an agile team is its velocity. This can be measured in story points per week for teams following a more “traditional” agile process like Scrum or XP, or it be measured in cycle time for those teams that have evolved to a Lean or Kanban approach. The team I’m coaching now is somewhere in the middle, closer to Scrumban.

So our standard metric is points per week. We measure weekly, and our measurements are reasonably accurate, varying between 25 and 30 points a week. We have the occasional week when we’re significantly below this, and some weeks where we way overachieve. Our historical velocity chart looks like this:

At first, our velocity varied a lot, mostly because we were still learning the codebase (this project has a large legacy codebase that we are adding functionality to). As of late, though, we’ve become a lot more consistent in what we finish each week. Not perfect, but a lot better.

But What About Quality?

Measuring velocity is not enough, as teams can find ways to go faster when pressed to do so. This is a great example of measuring something that is going to create the wrong behavior. If a team is rated on how fast they go, they are going to go as fast as they need to. They’ll either cut corners and quality will slip, or they’ll inflate the estimates to make the numbers start to look better without actually accomplishing anything more.

What I’ve found is that the best way to avoid incenting the team to cut corners is to keep an eye on quality, too. So, in addition to tracking  velocity, I also track defect counts. These charts look like this:


This shows our weekly quality over time since the beginning of our project. We started off pretty high, put in some good effort to get our quality back under control, and have done a decent job of keeping it under control most of the time.

Looking at the Bigger Picture

What I do is to use these two metrics together to help me understand what’s happening on the team and to ask questions about what may be causing ebbs and flows in velocity or quality. We did a good job of keeping the defect count pretty low during February and March, but the count crept back up, pretty quickly, to 20 or so active defects by the beginning of April. It was towards the end of this relatively quiet period that the time began to feel pressure to deliver more functionality more quickly. They did what they thought was best and focused more on getting stories “finished” without spending quite a much time on making sure everything worked. They worked to what was being measured.

Up steps Project Manager Man (that’s me, for those of you following along at home), and I was able to point out what was happening with quality and, with their help, relate that back to the feeling of pressure they were feeling. Together, we came up with the idea that velocity and quality have to improve together or teams create false progress. I helped the team manage this mini-issue on their own by pointing it out to them through metrics.

The Final Velocity/Quality Metric

As a way to keep an eye on the general trend of where the work is going on the team, I also track time spent working on Acceptance Tests versus time spent fixing defects (defects include stories that are kicked back from QA or the Product Owners prior to acceptance) versus time spent developing. My feeling is that if we can maximize development effort and minimize defect remediation time, then the team is operating as effectively as it can, given its circumstances.

The Most Important Point About Metrics

Metrics should never be used to judge a team or used to form conclusions about what is happening. They should be treated as a signpost along the way, an indicator of things that are not easily observed in real time but can be measured to point out trends. They should always serve as the starting point for a conversation, the beginnings of understanding an issue. If a manager or executive begins to use metrics as a way to judge a team, the metrics will be gamed and played from that point on. They will become useless, because they will be a reflection of what reality the manager wants to see, rather than what is truly happening.

In each and every one of these cases, I have used the metrics to confirm what I thought I was seeing, as the starting point of a conversation with the team about what they saw happening, and a way to measure the impact of issues on the team. After speaking with the team, the metrics are also useful to judge whether the changes chosen by the team to improve are effective.

Metrics are no substitute for being on the ground with your team, in their team room, pairing with devs and testers, working with product owners, feeling the vibe in the room. Remember, its people over process, right? 🙂

— bab

Looks like I’m speaking at SQE East in Boston, November 12th, 2013!

My good friend Mitch Lacey had to take a step back from a speaking engagement, and he asked me to cover for him to give a half day tutorial on Getting Started With Agile: An Experiential Workshop at the Better Software Conference in November. I’m very excited about doing this talk, both because of the opportunity to speak at this venue and to this audience, and because this kind of talk is so much fun to give.

This session is described as experiential because this talk about Agile and Scrum is planned and execute using Agile and Scrum, With the audience as the stakeholders and me as their “team”, we go through an initial story-gathering process, writing user stories for questions, estimate the questions, put them into a backlog, track metrics, replan and refine, and so on, all while answering the questions posed by the audience.

Doing this talk requires a bit of knowledge and a LOT of courage on the speaker’s part, as the questions can cover literally anything involved with the subject. I’m very glad Mitch has the confidence in me to be able to stand in for him, as his are some very big shoes to fill. Mitch, I’ll do my best not to let you down 🙂

— bab

New blog home

Hey, sorry for the inconvenience. We lost our hosting at our previous site (Thanks, Peter, for doing it for over 5 years!), so I’m reloading all content here, setting up a nice theme, etc. It might take a while, but it’ll eventually get done.

Thanks for your patience…

— bab

Test Driving a WPF App – Part 3: Switching to new window

This is the third part in what I hope to be a four-part series about creating a WPF application using TDD to drive the functionality and MVVM to keep everything testable as we go. The idea is to use view models to split away functionality from the view and have it available for testing while not losing any capabilities along the way. If you haven’t read the first two parts,  you may want to do that.

In this part, we’ll see what it takes to have a user gesture, in our case, either a double-click on a row in our ListView or clicking a button, take us to a different page in our application.We’ll write the code to get you to the other window in this post and leave the corresponding code to get back for readers as an exercise, should they want to confirm they understand how this all works. So, here we go.

The end result

At the conclusion of this process, we’re going to be able to start from the opening page, showing players and their numbers:


and navigate to this second page:


About this time, I’m feeling pretty good about my screen design abilities as well, as these pages are beautiful! (One thing I’ve learned about myself over the years is that I have very little taste when it comes to designing UIs :))

Step 1 – Writing the command logic to command the pages to switch

As before, when we’re adding new behavior based on a user gesture, we start by writing the ICommand class. We do this because it fleshes out both the details of that class, but also because it drives us down the road of creating the interface that the command class is going to use. This interface is going to be eventually implemented by the view model class, the TeamStatControlViewModel in our case. We don’t “officially” know that at this point, though, so we work through this interface, which represents one of the growing number of roles our view model fulfills. Fo more information on this style of development, read this paper by Steve Freeman.

Let’s begin by writing our first test for the command class. This is the test that invokes the behavior that the role we’re collaborating with makes available to us. In keeping with my experiment of creating lots of little fixtures, each of which represents a complete, but individual, behavior of my system, I’ve created a fixture called InterPageNavigationFixtures. My idea is that this fixture will hold all tests that document how navigating between pages works. Our first test:

   1: [Fact]

   2: public void SwitchToPlayerViewStartedWhenViewPlayerCommandExecutes()

   3: {

   4:     var viewPlayerSwitcher = new Mock<IViewPlayerModeSwitcher>();

   5:     ViewPlayerModeSwitchCommand cmd = new ViewPlayerModeSwitchCommand(viewPlayerSwitcher.Object);


   7:     cmd.Execute(null);


   9:     viewPlayerSwitcher.Verify(s => s.SwitchToPlayerViewMode());

  10: }

Like the other test we created for a command, we define the interface that represents the role we’re going to use, IViewPlayerModeSwitcher, and then our command class. The rest of the test ensures that the correct behavior happens when we invoke the command’s Execute method.

To make this test compile, we have to create some things, including the interface, the command, and some very minimal method signatures in both.

In the ViewModels project, we add the interface:

   1: namespace ViewModels

   2: {

   3:     public interface IViewPlayerModeSwitcher

   4:     {

   5:         void SwitchToPlayerViewMode();

   6:     }

   7: }

as well as the skeleton of the command:

   1: namespace ViewModels

   2: {

   3:     public class ViewPlayerModeSwitchCommand

   4:     {

   5:         public ViewPlayerModeSwitchCommand(IViewPlayerModeSwitcher modeSwitcher)

   6:         {

   7:         }


   9:         public void Execute(object parameter)

  10:         {

  11:         }

  12:     }

  13: }

Run test, test fails, implement minimal behavior to make test pass:

   1: public class ViewPlayerModeSwitchCommand

   2: {

   3:     private readonly IViewPlayerModeSwitcher modeSwitcher;


   5:     public ViewPlayerModeSwitchCommand(IViewPlayerModeSwitcher modeSwitcher)

   6:     {

   7:         this.modeSwitcher = modeSwitcher;

   8:     }


  10:     public void Execute(object parameter)

  11:     {

  12:         modeSwitcher.SwitchToPlayerViewMode();

  13:     }

  14: }

At this point, the test passes, and we can invoke the switching behavior that will be implemented in our view model shortly.

The last thing I was to do here before moving on is to expose the command through the view model so the view can bind to it. A simple test, much like others we’ve seen before:

   1: [Fact]

   2: public void ViewModelExposesSwitchToPlayerViewModeCommandAsICommand()

   3: {

   4:     TeamStatControlViewModel viewModel = new TeamStatControlViewModel(null, null, null);


   6:     Assert.IsAssignableFrom<ViewPlayerModeSwitchCommand>(viewModel.PlayerViewMode);

   7: }


and we implement this by simply adding an auto-property to our view model called PlayerViewMode.

Part 2 – Making the view model change application modes

In this next, the view model will begin to switch modes in the application between the Player Summary mode and View Player mode. I’m intentionally calling these modes here because I don’t want the view model to know about windows and views and other UI-ish specifics. As far as it is concerned, the application has two modes in which it can work, and someone else is going to be able to translate from the information about modes and transitions to swapping out views and controls. This is purely an example of separating concerns, where the view model only cares about the modes of the application and another class, more than likely in the same assembly as the view logic, will know how to act upon modes switching.

Starting down this road, we’ll write a test that drives out the interface for how we’ll tell something outside of the view model that a mode is changing. We’ll be talking to a role I chose to call the ModeController, commanding it through its PlayerViewMode. Here is the test:

   1: [Fact]

   2: public void ModeControllerCommandedToSwitchToPlayerViewByViewModel()

   3: {

   4:     var modeController = new Mock<IModeController>();

   5:     TeamStatControlViewModel viewModel = new TeamStatControlViewModel(null, modeController.Object, null);


   7:     viewModel.SwitchToPlayerViewMode();


   9:     modeController.Verify(nc => nc.PlayerViewMode(It.IsAny<Player>()));

  10: }

Since the TeamStatControlViewModel needs access to the mode controller, we had to modify its constructor to take an argument of that type. We call the method we’re trying to drive through the tests, SwitchToPlayerViewMode, and then comes our assertion. Our assertion is a bit interesting here – maybe I’m thinking too far ahead, but I’m considering how the view that is going to eventually be rendered is going to work. Its going to need to know about the player that was selected, so it can show it. In fact, that player is probably going to become its DataContext. To give the new view, which will be rendered by someone else at some other time, access to the player, I’m passing it along here. I’m not writing the code that will actually cause it to be passed yet, as you can see by the It.IsAny<Player> argument in the Verify statement, but I’m declaring that an object of that type is going to be passed to it when the system runs for real. Let’s implement this small step:

First, the IModeController, which sits in the ViewModel sassembly:

   1: namespace ViewModels

   2: {

   3:     public interface IModeController

   4:     {

   5:         void PlayerViewMode(Player player);

   6:     }

   7: }

and then the minimal code in the view model:

   1: public class TeamStatControlViewModel: IApplicationExitAdapter, IViewPlayerModeSwitcher

   2: {

   3:     private readonly IApplicationController applicationController;

   4:     private readonly IModeController modeController;

   5:     private readonly IPlayerRepository playerRepository;


   7:     public TeamStatControlViewModel(

   8:         IApplicationController applicationController, 

   9:         IModeController modeController, 

  10:         IPlayerRepository playerRepository)

  11:     {

  12:         this.applicationController = applicationController;

  13:         this.modeController = modeController;

  14:         this.playerRepository = playerRepository;

  15:         ApplicationExit = new ApplicationExitCommand(this);

  16:         PlayerViewMode = new ViewPlayerModeSwitchCommand(this);

  17:     }


  19:     public void SwitchToPlayerViewMode()

  20:     {

  21:         modeController.PlayerViewMode(new Player());

  22:     }

  23: }

Please not that I’m only showing the interesting bits here, and removing code that didn’t change from the last time we looked at this class. The bits that did change are an additional parameter to the constructor of this class and the addition of the SwitchToPlayerMode method. Since that method came from the IViewPlayerModeSwitcher, I also went ahead and implemented the interface here. (Note – Since this isn’t a lesson in TDD, I skipped the step of how I used the AddMethodParameter refactoring to slowly add the new constructor and move away from the old one. I didn’t do this in one big step, I did it in small steps, using the tests to guide me to what to change next.)

The next step is to get the player that is selected in the ListView and pass that along in the call, instead of passing an empty player. Here is the test used to drive that:

   1: [Fact]

   2: public void SamePlayerPassedToModeControllerAsSetInViewModel()

   3: {

   4:     var modeController = new Mock<IModeController>();

   5:     TeamStatControlViewModel viewModel = new TeamStatControlViewModel(null, modeController.Object, null);

   6:     Player player = new Player();

   7:     viewModel.SelectedPlayer = player;


   9:     viewModel.SwitchToPlayerViewMode();


  11:     modeController.Verify(nc => nc.PlayerViewMode(player));

  12: }

There are only small differences between this test and the one before it. The main one is that I’m defining a new property on the view model, SelectedPlayer. A ListView sets this property every time the selected item changes in its view, and this property will allow our view model to be informed about which player is selected at any time. Now we can pass along that player in the PlayerViewMode call, and all is well. Here are the minor changes in TeamStatControlViewModel:

   1: public Player SelectedPlayer { get; set; }


   3: public void SwitchToPlayerViewMode()

   4: {

   5:     modeController.PlayerViewMode(SelectedPlayer);

   6: }

Part 3 – Hooking up what we have

Despite the fact that I write a lot of tests for my code, I still like to see it work every now and then! This would be one of those times. We’re at the point now where we should be able to wire up everything we have and get to the point where the mode controller would be able to swap out controls, were we to have implemented that last piece of functionality. Let’s hook up what we got and see what works.

Let’s start by making a couple of quick changes in the XAML. We’ll add a SelectedItem attribute and binding in the ListView and we’ll hook up the ViewPlayer button to the command:

   1: <ListView IsSynchronizedWithCurrentItem="True" Grid.Row="1" VerticalAlignment="Stretch" 

   2:     SelectedItem="{Binding SelectedPlayer}" ItemsSource="{Binding Players}">

   1: <Button Command="{Binding PlayerViewMode}" Grid.Column="0" Content="View Player Stats" 

   2:         HorizontalAlignment="Right" Style="{StaticResource NormalButton}"/>

That should be enough to have the user gestures be sent to our view model.

The view model itself is complete, but we need to make some class implement the IModeController. Again, I think the best place, at least for now, is the App class, so we’ll put that interface there – I do suspect that we’ll eventually pull that out of the App class and make it its own class, so that we can test it, but we haven’t had that need yet. Someday, maybe…

That leaves some very minor changes in App.xaml.cs. We add the interface to the class definition, implement the PlayerViewMode method, and tell the container that App implements the IModeController interface (line 8), which allows it to pass an object of that type to the view model’s constructor.


   1: public partial class App : Application, IApplicationController, IModeController

   2: {

   3:     private readonly IUnityContainer container = new UnityContainer();


   5:     private void Application_Startup(object sender, StartupEventArgs e)

   6:     {

   7:         container.RegisterInstance<IApplicationController>(this);

   8:         container.RegisterInstance<IModeController>(this);


  10:         container.RegisterType<IPlayerRepository, PlayerRepository>(new ContainerControlledLifetimeManager());

  11:         container.RegisterType<TeamStatControlViewModel>(new ContainerControlledLifetimeManager());

  12:         container.RegisterType<TeamStatControl>(new ContainerControlledLifetimeManager());


  14:         container.RegisterType<MainWindow>(new ContainerControlledLifetimeManager());


  16:         Current.MainWindow = container.Resolve<MainWindow>();

  17:         Current.MainWindow.Content = container.Resolve<TeamStatControl>();

  18:         Current.MainWindow.Show();

  19:     }


  21:     public void ExitApplication()

  22:     {

  23:         Current.Shutdown();

  24:     }


  26:     public void PlayerViewMode(Player player)

  27:     {

  28:         ;

  29:     }

  30: }

At this point, we’re good to try it out, so start up the application, click on a name, press View Player, and… OK, still nothing happens because we don’t have another window yet. I tested this by putting a breakpoint on line 28 and debugging it to see that I made it to here, which I did, and that the correct player was being sent here. I know my tests told me that this should work, but in the immortal words of Ronald Reagan, “Trust, but verify”.

Part 4 – Showing the other view

We’re in the home stretch now. Let’s show the other view. First, let’s just assume that I created another view. You can see it way back at the top – its the second window you see, with a big name and number in it. Once you’re at this point, all you need to do to enable the app to switch between the main view and this view is to implement the App.PlayerViewMode method correctly. I couldn’t find a way to test this, since I’m manipulating the UI directly, so I just wrote the code:

   1: public void PlayerViewMode(Player player)

   2: {

   3:     Current.MainWindow.Content = null;


   5:     Current.MainWindow.Content = container.Resolve<PlayerDetailControl>();

   6:     ((PlayerDetailControl) Current.MainWindow.Content).DataContext = player;

   7: }

A couple things to note here. First, I didn’t register the type, PlayerDetailControl, with the container. The Unity container will do its best to create any object that hasn’t been registered with it by calling whatever constructor it can find that matches up with arguments it knows how to build. In our case, the class has a default constructor, so it knew how to build it. Since we didn’t register it, Unity will just create a new instance of the control for me every time I ask for it. I can then assign the player to be its DataContext, and we’re done. That turned out to be very easy 🙂

At this point, we should be able to select a player, click on the View Player button, and the other view should appear. Success! But we’re not quite finished yet… sorry! Two more points to make

Part 5 – Double clicking and CanExecute for the command

Before we finish, I want to cover two other things. The first is how to enable double click behavior for the ListView. There isn’t a simple way to attach a command behavior to the ListView in the version of WPF I’m using. I know that AttachedBehaviors are part of the new WPF version that’s in development now, but I don’t have that, so you’re stuck with this explanation 🙂

Since there wasn’t a way to attach a command to the double-click event, I had to put code into the code-behind page, which is the first time I’ve had to do that yet! I wired up an event handler to the double-click event through a small change in the XAML for the ListView:

   1: <ListView IsSynchronizedWithCurrentItem="True" Grid.Row="1" VerticalAlignment="Stretch" 

   2:     MouseDoubleClick="ListView_MouseDoubleClick"  SelectedItem="{Binding SelectedPlayer}" ItemsSource="{Binding Players}">

and added a trivial handler in the TeamStatControl.xaml.cs file:

   1: private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)

   2: {

   3:     TeamStatControlViewModel viewModel = (TeamStatControlViewModel) DataContext;

   4:     viewModel.PlayerViewMode.Execute(null);

   5: }

All this method does is to call the Execute method of the same command that the button runs. Trivial code. So now we can double-click on a player in the list and the right thing happens.

But what happens if no player is selected (OK, I couldn’t figure out a way to make this happen for the real list view, but it seemed like an interesting example and thought experiment!). We need to implement the CanExecute behavior for the ViewPlayerModeSwitchCommand. As usual, we do this through tests.

In our first test, we confirm that the command cannot execute if no player is selected:

   1: [Fact]

   2: public void ViewModelFunctionalityIsNotOnlyAvailableWhenNoPlayerIsSelected()

   3: {

   4:     TeamStatControlViewModel viewModel = new TeamStatControlViewModel(null, null, null);

   5:     ICommand playerViewModeCommand = viewModel.PlayerViewMode;


   7:     Assert.False(playerViewModeCommand.CanExecute(null));

   8: }

and we implement CanExecute as simply as we can to make the test pass:

   1: public bool CanExecute(object parameter)

   2: {

   3:     return false;

   4: }

Our  next test is a little more interesting, as it requires that the CanExecute returns true if a player is selected:

   1: [Fact]

   2: public void ViewModelFunctionalityIsAvailableWhenPlayerIsSelected()

   3: {

   4:     TeamStatControlViewModel viewModel = new TeamStatControlViewModel(null, null, null);

   5:     ICommand playerViewModeCommand = viewModel.PlayerViewMode;

   6:     viewModel.SelectedPlayer = new Player();


   8:     Assert.True(playerViewModeCommand.CanExecute(null));

   9: }

The only real modification here is that we use the SelectedPlayer method of the view model to set the player that would be selected through the real view. We expect that the command class is able to query this SelectedPlayer property through its reference to the view model using the IViewPlayerModeSwitcher interface. Well, that’s what we’d expect, anyhow…

   1: public bool CanExecute(object parameter)

   2: {

   3:     return modeSwitcher.SelectedPlayer != null;

   4: }

The SelectedPlayer property isn’t available through that interface, so as our final step along this long and tortuous path, we add it to the interface, our implementation code compiles, our tests all run, and we celebrate by going home early for the day.


I hope people are finding this case study to be useful. I found a lot of different resources on the web about doing bits and pieces of your WPF/MVVM application test-first, but I still had a lot of unanswered questions. First and foremost on that list was how to do simple navigation like I’m doing. By putting together most of a whole application, I hope its more clear to readers how the different pieces fit together.

I do plan on doing one more step along the way, probably posted tomorrow morning (8/25/2009). I want to show how to handle pop-up windows, including windows dialog boxes as well as custom WPF windows. I had to deal with this on my own project, and it took a bit of thinking to figure out how to do it in a testable way.

Until tomorrow!

— bab

Test driving a WPF App – Part 2: Adding some data

This is part two of the blog series about creating a WPF application using TDD to drive the functionality and MVVM to split that functionality away from the view into something more testable. You may want to read part one if you haven’t already.

In this part, we’ll see what it takes to display data on the front page about each player on the softball team. We’re not going to display all their stats, since we don’t need to for the example, but it would be very easy to extend this to do so. (N.B. I have a more full version of this that I’ll post that includes a database backend with more data in it than what I’m going to show here. The data backend is irrelevant to the layer being discussed here, so I’m going to ignore those details.)

The end result

At the end of this process, what we’re going to have is a list of players and their numbers. We could easily extend it to total stats for each of them, but that’s outside the point of the example, and is left as an exercise for the reader (I hated when college textbooks said that!).


So anyhow, you can see the 4 players listed and their numbers. This data came from the data repository that I created behind the view, in a class called PlayerRepository. I’m not going to go into the details of how this repository class was created, as the database layer is outside the scope of this article, so we’ll just assume that we created it when it was needed, and I won’t include discussion or tests for it. The important part of us to think about is how the data got into the view model and how it got from there onto the view. And that begins our (short) story.

Step 1 – Get data to the view

In order to get data to the view, the view model needs to expose an ObservableCollection that the view can bind to. I decided to create a property called Players on the TeamStatControlViewModel, driving it through tests. I created a test fixture in the ViewModelFixtures assembly called TeamStatControlPlayersDataBindingFixture, and I put my test into there (as an aside, I’m trying a different style of fixtures here, where I’m naming fixtures after behaviors or features and putting all the tests for those features in that fixture. I’m intentionally trying to break out of the app class <-> fixture class model and create tests around the behaviors of the system, regardless of where those behaviors may lie. Let me know if you like it, please.)

   1: [Fact]

   2: public void ViewModelExposesObservableCollectionOfPlayers()

   3: {

   4:     TeamStatControlViewModel viewModel = new TeamStatControlViewModel(null);


   6:     Assert.IsType<ObservableCollection<Player>>(viewModel.Players);

   7: }

We have to add the Players property to the view model and create an empty Player class in our Model assembly to get this test to compile. Once it runs and fails, we implement the property in the view model to return an empty ObservableCollection<Player> collection. Run again, and the test passes.
   1: public ObservableCollection<Player> Players

   2: {

   3:     get { return new ObservableCollection<Player>(); }

   4: }

Step 2 – Get the data to the view model

Now that we have the data available to be shown on the view, we need to provide that data to the view model. We do this by giving the view model access to the PlayerRepository we spoke of earlier and letting it query the repository for the data as needed. Again, very simple. Here is the test in that same test fixture:

   1: [Fact]

   2: public void DataIsPulledFromModelWhenRetrievingPlayersFromViewModel()

   3: {

   4:     var playerRepository = new Mock<IPlayerRepository>();

   5:     TeamStatControlViewModel viewModel = new TeamStatControlViewModel(null, playerRepository.Object);

   6:     playerRepository.Setup(pr => pr.GetAllPlayers()).Returns(new List<Player>());


   8:     ObservableCollection<Player> players = viewModel.Players;


  10:     playerRepository.Verify(pr => pr.GetAllPlayers());

  11: }

The test start driving to define the behavior our system is going to need. We already know that the view model is going to need a reference to the repository, so we add the repository to the constructor arguments for the view model on line 5. (I like working backwards in a situation like this to discover the objects needed. I’ll write the constructor signature first and use that to drive object creation on previous lines, like you see here.) This forces us to create a mock version of the repository, which we do in line 4 by discovering an IPlayerRepository interface, details to be fleshed out. On line 6, we set up the behavior that we want the view model to invoke on the repository, which is the GetAllPlayers method, which for our purposes needs to return an empty collection of the appropriate type. Finally, we invoke the Players property and verify that the repository’s GetAllPlayers method is indeed called.

In getting this to compile, we create the IPlayerRepository interface and modify the signature of TeamStatControlViewModel to take the new IPlayerRepository parameter. Run test, test fails, and we finally implement:

   1: public interface IPlayerRepository

   2:     {

   3:         IList<Player> GetAllPlayers();

   4:     }


   1: public class TeamStatControlViewModel: IApplicationExitAdapter

   2: {

   3:     private readonly IApplicationController applicationController;

   4:     private readonly IPlayerRepository playerRepository;


   6:     public TeamStatControlViewModel(IApplicationController applicationController, IPlayerRepository playerRepository)

   7:     {

   8:         this.applicationController = applicationController;

   9:         this.playerRepository = playerRepository;

  10:         ApplicationExit = new ApplicationExitCommand(this);

  11:     }


  13:     public void ExitApplication()

  14:     {

  15:         applicationController.ExitApplication();

  16:     }


  18:     public ICommand ApplicationExit { get; set; }


  20:     public ObservableCollection<Player> Players

  21:     {

  22:         get { return new ObservableCollection<Player>(playerRepository.GetAllPlayers()); }

  23:     }

  24: }

At this point, we have data coming from the repository and available to the view. All that’s left is to hook up to the view.

Step 3 – Hooking up to the real view

I’m going to cheat a bit and not define a DataTemplate for this and just directly bind to the two columns I’m going to define, Name and Number. I have a ListView in the middle of my window, as you can see in the screencapture at the top if this post. I define a couple GridViewColumns in it and bind them to Name and Number:

   1: <ListView IsSynchronizedWithCurrentItem="True" Grid.Row="1" VerticalAlignment="Stretch" ItemsSource="{Binding Players}">

   2:     <ListView.View>

   3:         <GridView>

   4:             <GridViewColumn Header="Player" DisplayMemberBinding="{Binding Name}"/>

   5:             <GridViewColumn Header="Number" DisplayMemberBinding="{Binding Number}" />

   6:         </GridView>

   7:     </ListView.View>

   8: </ListView>

Obviously I wouldn’t do this on a real project, I’d use a DataTemplate. But for now, this will do. The ItemSource is set to the Players property, and the two columns are set to the fields I want to show.

We don’t have a real instance of our IPlayerRepository yet, so lets build a really simple one. In real life, this would be a repository over the top of a database, but we don’t need to go that far for now. Let’s just create the simplest repository we can for now:

   1: public class PlayerRepository : IPlayerRepository

   2:     {

   3:         public IList<Player> GetAllPlayers()

   4:         {

   5:             return new List<Player>

   6:                        {

   7:                            new Player

   8:                                {

   9:                                    Name = "Linsey",

  10:                                    Number = "42"

  11:                                },

  12:                            new Player

  13:                                {

  14:                                    Name = "Michelle",

  15:                                    Number = "31"

  16:                                },

  17:                            new Player

  18:                                {

  19:                                    Name = "Susan",

  20:                                    Number = "17"

  21:                                },

  22:                            new Player

  23:                                {

  24:                                    Name = "Joan",

  25:                                    Number = "26"

  26:                                }

  27:                        };

  28:         }

  29:     }

One thing we’re still doing is exposing the Player class to the view. This is not necessarily the best practice that has evolved, since the Player class is defined in the Model layer. The danger is that we may end up needing to add INotifyPropertyChanged behavior to the Player class, which would pollute our domain model with view-specific code. If that were to happen, it would force us to refactor the view model to return an observable collection of something else, like an ObservableCollection<PlayerViewModel>, so that we would have a place to put our view-specific code. We don’t need to yet, so we’re not going to bother. This is a potential refactoring to come, though.

And our final change is to add the PlayerRepository type into our Application_Startup method, so that Unity knows how to build the repository and pass it into the TeamStatControlViewModel:

   1: private void Application_Startup(object sender, StartupEventArgs e)

   2: {

   3:     container.RegisterInstance<IApplicationController>(this);


   5:     container.RegisterType<IPlayerRepository, PlayerRepository>(new ContainerControlledLifetimeManager());

   6:     container.RegisterType<TeamStatControlViewModel>(new ContainerControlledLifetimeManager());

   7:     container.RegisterType<TeamStatControl>(new ContainerControlledLifetimeManager());


   9:     container.RegisterType<MainWindow>(new ContainerControlledLifetimeManager());


  11:     Current.MainWindow = container.Resolve<MainWindow>();

  12:     Current.MainWindow.Content = container.Resolve<TeamStatControl>();

  13:     Current.MainWindow.Show();

  14: }

Compile and run, and all should work.


This was a fairly easy step to take. We exposed a property on our view model to let our view see the data we want to publish. Our view model has a repository injected into it to let it get the data as needed. That was really all there was to it. Two tests, and we got to where we needed to be.

The next step along the way will involve navigating from the front page to a player detail page. Stay tuned for the next installment, coming right up!

— bab