Model View Presenters : Presenter to View Communication

Jan 26, 08:12 AM

Table of Contents:

  • Introduction
  • Presenter to View Communication
  • View to Presenter Communication
  • Composite Views
  • Presenter / Application communication
  • ...

Presenter to View Communication

There are two styles utilised for populating the View with data from the Presenter and Model that I have used. The only difference between them is how tightly coupled you mind your View being to the Model. For the example of this, we will have the following as our Model:

public class Person
{
    public int ID { get; private set; }
    public int Age { get; set; }
    public String FirstName { get; set; }
    public String LastName { get; set; }
    Public Genders Gender { get; set; }
}

Method 1: Using the Model

Now our View code:

public interface IEmployeesView
{
    void ClearList();
    void PopulateList(IEnumerable<Person> people);
}

And finally the Presenter:

public class IEmployeesPresenter
{
    public void Display()
    {
        _view.ClearList();
        _view.PopulateList(_model.AllEmployees);
    }
}

This method of population produces a link between the Model and the View; the Person object used as a parameter in PopulateList.

The advantage of this is that the concrete implementation of the IEmployeesView can decide on what to display in its list of people, picking from any or all of the properties on the Person.

There are two disadvantages of this method. The first is that there is nothing stopping the View from calling methods on the Person, which makes it easy for lazy code to slip in. The second is that if the model were to change from a List<Person> to a List<Dog> for instance, not only would the Model and the Presenter need to change, but so the View would too.

Method 2: Using Generic Types

The other method population relies on using Tuple<...>, KeyValuePair<,> and custom classes and structs:

Now our View code:

public interface IEmployeesView
{
    void ClearList();
    void PopulateList(IEnumerable<Tuple<int, String> names);
}

And finally the Presenter:

public class IEmployeesPresenter
{
    public void Display()
    {
        var names = _model.AllEmployees.Select(x => new Tuple<int, String>(x.ID, x.FirstName + " " + x.LastName));

        _view.ClearList();
        _view.PopulateList(names);
    }
}

The advantages of this method of population is that the Model is free to change without needing to update the View, and the View has no decisions to make on what to display. It also prevents the View from calling any extra methods on the Person, as it does not have a reference to it.

The down sides to this method, are that you loose strong typing, and discoverability - It is quite obvious what a Person is but what a Tuple<int, String> is less obvious.

Andy

Code, Design, .net

Comments...

---

Model View Presenter : Introduction

Jan 26, 08:11 AM

What is MVP?

I first came across MVP in Jeremy Miller's Build Your Own Cab series, and have been using and improving how I work with this style ever since. Model View Presenters tend to come in one of two forms: Passive View, and Supervising Controller. I am a fan of the Passive View variety, primarily for the testing aspect, but also as I find it provides me with the best level of separation.

The code ends up structured like this:

MVP

The View contains only code that enables control population and feedback. This means the odd For loop or similar to fill a grid from a property, or feedback object construction, along the lines of new SelectedRowData {ID = (int)row.Tag, Name = row[0].Value}. However, it would not contain any decision logic.

The Presenter contains code to transform Model data to something the View can display, and vice-verse. It also contains any view logic, such as if a CheckBox is selected, then a MenuItem becomes disabled.

The Model is the data to be displayed. This can either be an abstraction that encompasses several entities and business logic, or can be some entities themselves.

What I aim to cover in this series

Andy

Design, .net

Comments...

---

Working with XmlTextWriter

Oct 25, 11:05 AM

I was working on some code today that needs a lot of data writing into an XML document. The documents structure is not repetitive - it is loads of one time data, so templating the document is possible, but not the best route to go.

To that end, it uses an XmlTextWriter. The problem I have with it is the way you must write sub-elements. If you just need a single value wrapped in a tag, you are catered for already:

writer.WriteElementString("name", current.Name);

However, if you want to embed a composite set of elements, you are left with this lovely chunk:

writer.WriteStartElement("composite")

writer.WriteElementString("firstName", current.FirstName);
writer.WriteElementString("lastName", current.LastName);

writer.WriteEndElement();

And if you have a long document, with many composite elements, good luck remembering which element is being ended by WriteEndElement() (even if you functionalise it, you still run into the issue.)

The solution I came up with for this was a class and an extension method:

internal class WriteElement : IDisposable
{
    private XmlTextWriter _writer;

    internal WriteElement(XmlTextWriter writer, String element)
    {
        _writer = writer;
        _writer.WriteStartElement(element);
    }

    public void Dispose()
    {
         _writer.WriteEndElement();
         _writer = null;
    }
}

static class XmlTextWriterExtensions
{
    public static IDisposable WriteComposite(this XmlTextWriter self, String element)
    {
        return new WriteElement(self, element);
    }
}

This enables me to write composite elements like this:

using (writer.WriteComposite("composite"))
{
    writer.WriteElementString("firstName", current.FirstName);
    writer.WriteElementString("lastName", current.LastName);           
}

With the two benefits of knowing when my composite elements are ending, and I also gain indentation of my elements, which allows me to see where the composites are a lot easier.

Andy

Code, .net

Comments...

---

Noticing Changes

Oct 22, 11:48 AM

I work on a piece of software that has been around for about 6 years now, which looks something like this:

Control

The textboxes are validating that their contents, some as decimal, and some as integer. All the textboxes consider no-value to be invalid.

I made a slight change to the control, which was to add a new row. Since adding that row, many users have sent in requests to have the validation changed on the textboxes, so that no-value is considered to be zero.

Now while I have no problem in making the change, I do however wonder what caused all the requests. Is it because users noticed the control was changed, so a developer is paying attention somewhere, so maybe they can fix a problem? Had they just not noticed that no-value is invalid, and now it has changed slightly, they have?

Another thing is that while it is a very minor change, it must have been causing user friction for the last 6 years or so, and no one has mentioned it? Maybe they just didn't think it was changeable, or that it just wasn't that bothersome compared to some other issue they had?

Andy

Design

Comments...

---

The work ethic

Sep 26, 05:47 PM

Over the past few weeks I have found my concentration sapped at work. I am uninterested in the project I am assigned to, and am not looking forward to the one that is coming after it either (although it is more appealing than the current.)

Part of the reason for the current project I think has to do with the subject matter - It involves some financial rules that need to be implemented, and finance is really not my strong point. I have a formula, and various numbers to plug into it, but I don’t really understand what it’s doing.

The other side of the reason for not enjoying it is simple; I would much rather be fixing code, making things easier, faster and better for fellow programmers. When it comes down to it, I get much more enjoyment from tidying the code we have in our common controls project. I would rather be making our exception handling better by giving it finer detail, and enabling it in the projects it cannot run in. I would rather be consolidating code that is repeated all over the place.

We have a lot of code in our system that needs fixing - when bugs crop up in it, it takes ages to fix as you have no idea what is going on. While I think my team leader sees the benefits in making these improvements, I don’t think it is easy to justify to higher management the importance of this. They tend to see programming/software as like building a house - once it's finished, very little needs doing to keep it in shape. The reality is that software development is a lot more like gardening - once it's all planted, you need to keep weeding it, else it will get overrun.

The next contributing factor is "Get it done" vs. "Get it done right". People in the team go for the first. This is down to several things, the first being personal preference, in that the thought is "we can fix it later". However, later never comes, as something else comes up. The other main force behind it is management set deadlines. I am not involved in deadline picking, but most seem to be picked too short, and so there is no time for getting it done right.

When trying to combat this effect, I ended up doing what I hate doing - staying late. I did the "Get it done" during the day, and the "right" part in the evening. This in my mind is down to me covering up someone else’s mistake - they can’t pick deadlines right, so I have to put extra work in, or I produce bad code that I will be fixing in a few weeks time. I am defiantly not saying that I can pick estimates better than management, but at the same time, a little flexibility would go a long way. Oh and communicating this to developers and making sure that they know getting it done right is important. If we don’t do it right the first time, we will have to fix it later, and that is far less cost effective.

The other problem with this is burn-out. I just can’t do this for long; I am not designed for it. Week on, Week off was suggested on a blog I read a few weeks back, but I think the reality for me is Week on, Month off. Why should I have to do this anyway?

I don’t really have a summary for this, but it needed putting down to get it out of my system. Now on to some interesting coding.

Andy

Rant

Comments... [1]

---

« Older