0% found this document useful (0 votes)
61 views54 pages

Presentation Patterns

Uploaded by

Dwj Nguyen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views54 pages

Presentation Patterns

Uploaded by

Dwj Nguyen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Notification
An object that collects together information about errors and other information in the
domain layer and communicates it to the presentation.

Martin Fowler

09 August 2004

This is part of the Further Enterprise Application Architecture


development writing that I was doing in the mid 2000’s. Sadly too
many other things have claimed my attention since, so I haven’t had
time to work on them further, nor do I see much time in the
foreseeable future. As such this material is very much in draft form
and I won’t be doing any corrections or updates until I’m able to find
time to work on it again.

A common application scenario is that of a presentation capturing data from the user
and passing submitting that data to the domain for validation. The domain needs to
make a number of checks and if any them fail, to let the presentation know about it.
However Separated Presentation does not allow the domain to communicate directly
with the presentation.

A Notification is an object that the domain uses to collect information about errors during
the validation. When an error appears the Notification is sent back to the presentation
so the presentation can display further information about the errors.

How it Works
In its simplest form, a notification can just be a collection of strings which are error
messages that the domain generates while it's doing its work. With each validation that
the domain layer makes, each failure results in an error added to the notification.
However it makes sense to give the notification a more explicit interface than this. A
notification object will typically have methods for adding errors that use error codes
rather than strings, and convenience methods to tell if the notification has any errors
present.

If you are using a Data Transfer Object (DTO), it makes sense to add the notification to
the DTO in a Layer Supertype. This allows all interactions to use the notification cleanly.

If your domain logic is relatively simple, such as using Transaction Scripts, then the
logic can have a direct reference to the Notification. This makes it easy to refer to it
while adding errors. Referring to the Notification can be more problematic in more
layered systems using a Domain Model because such domain models often don't have
visibility into such things as incoming DTOs. In this case case it's necessary place a
Notification into some kind of session object that domain objects can easily reach.

Error codes need to be present on classes that are shared between presentation and
domain. Using error codes provides a more explicit statement of the expected errors
and makes it easier for the presentation to present the errors in a more interactive way
than just printing out error messages. With a simple domain layer it's often enough to
embed these codes within a data transfer object (if you're using one) or a set of error
codes for the specific interaction. With a domain model the error codes need to be
designed around the vocabulary of the domain model itself.

While errors are usually the most needed aspect for a Notification, it's also useful for the
Notification to pass back any other information that the domain wishes to convey to its
caller. These might include warnings (problems that aren't serious enough to stop the
interaction) and informational messages to display to the user. These need to be
separated on the Notification so that the presentation can easily tell if any errors are
present.

If you are using Notification in a system where the presentation and domain logic are in
different processes, you need to ensure that the Notification only contains information
that can be safely transported across the wire, typically this means you cannot embed
references to domain objects in such Notification.

When the presentation receives a response from the validation, it needs to check the
Notification to determine if there are errors. If so it can pull information out of the
Notification to display these errors to the user. If there are errors one option is for the
domain to raise an exception so that the presentation can use exception handling to
handle the errors. On the whole I feel that validation errors are sufficiently common that
it isn't worthwhile to use exception handling mechanisms for these cases, but that's not
an overwhelming preference.

When to Use It
You should use Notification whenever validation is done by a layer of code that cannot
have a direct dependency to the module that initiates the validation. This is very
common in a layered architecture is Separated Presentation.

The most obvious alternative to using Notification is for the domain to use exception
handling to indicate errors. Such an approach has the domain throw an exception if a
validation check fails. The problem with this is that it only indicates the first validation
error. It's usually more helpful to show every validation error, particular if validation
requires a round trip to a remote domain layer.

Another alternative is for the domain layer to raise an event for validation errors. This
allows multiple errors to be flagged. However it's not so good for remote domain layers
since each event would result in a network call.

Example: Error Checking a Window (C#)


Example: Error Checking a Window (C#)

In Figure 1 I have a simplistic form to submit to judge an insurance claim. I have three
bits of data to submit: the policy number (a string), the type of claim (text from a pick
list), and the date of the incident (a DateTime).

If my data is simplistic, just wait for my validity checks:

Check that none of the three bits of data are missing (null or blank for the strings.
Check that the policy number is present in the data store.
Check that the date of the incident is later than the inception date of the policy.

We want to give as much information back to the user as possible, so if we can


reasonably detect multiple errors we should.

I'll start the discussion with the domain layer. The basic interface to the domain logic is
in a Service Layer.

class ClaimService...
public void RegisterClaim (RegisterClaimDTO claim) {
RegisterClaim cmd = new RegisterClaim(claim);
[Link]();
}

This method just creates and runs a command object to do the actual work. Wrapping
command objects behind a method call service layer can help simplify a server API and
make it easier to build a Remote Facade.

I use a Data Transfer Object, to transfer the data over. The RegisterClaimDTO contains
the main data.

RegisterClaimDTO : DataTransferObject
private string _policyID;
private string _Type;
private DateTime _incidentDate = BLANK_DATE;

public string PolicyId {


get { return _policyID; }
set { _policyID = value; }
}
public string Type {
get { return _Type; }
set { _Type = value; }
}
public DateTime IncidentDate {
get { return _incidentDate; }
set { _incidentDate = value; }
}

DataTransferObject is a Layer Supertype for all the DTOs. This contains general code
to create and access a Notification to go with the interaction.

class DataTransferObject...
private Notification _notification = new Notification();
public Notification Notification {
get { return _notification; }
set { _notification = value; }
}

The notification class is what we'll use to capture the errors in the domain layer.
Essentially it's a collection of errors, each one of which is a simple wrapper around a
string.

class Notification...
private IList _errors = new ArrayList();

public IList Errors {


get { return _errors; }
set { _errors = value; }
}
public bool HasErrors {
get {return 0 != [Link];}
}

class [Link]
private string message;
public Error(string message) {
[Link] = message;
}

The command's run method is very simple.

class class RegisterClaim : ServerCommand...


public RegisterClaim(RegisterClaimDTO claim) : base(claim) {}
public void Run() {
Validate();
if (![Link])
RegisterClaimInBackendSystems();
}

Again the Layer Supertype provides some general functionality to store the DTO and
access the notification.

class ServerCommand...
public ServerCommand(DataTransferObject data){
this._data = data;
}
protected DataTransferObject _data;
protected DataTransferObject _data;
protected Notification notification {
get {return _data.Notification;}
}

The validate method carries out the validations that I talked about above. Essentially all
it does is run a series of conditional checks, adding errors into the notification if anything
fails.

class RegisterClaim...
private void Validate() {
failIfNullOrBlank([Link], RegisterClaimDTO.MISSING_POLICY_NUMBER);
failIfNullOrBlank([Link], RegisterClaimDTO.MISSING_INCIDENT_TYPE);
fail ([Link] == RegisterClaimDTO.BLANK_DATE, RegisterClaimDTO.MISSING_INCIDENT_DATE);
if (isNullOrBlank([Link])) return;
Policy policy = FindPolicy([Link]);
if (policy == null) {
[Link](RegisterClaimDTO.UNKNOWN_POLICY_NUMBER);
}
else {
fail (([Link]([Link]) < 0),
RegisterClaimDTO.DATE_BEFORE_POLICY_START);
}
}

The most complex thing about much of this is that certain validation checks only make
sense if others haven't failed - which leads to conditional logic in the validate method.
With more realistic size methods it's important to break them out into smaller chunks.

Common generic bits of validation can (and should) be extracted and put in the Layer
Supertype.

protected bool isNullOrBlank(String s) {


return (s == null || s == "");
}
protected void failIfNullOrBlank (string s, [Link] error) {
fail (isNullOrBlank(s), error);
}
protected void fail(bool condition, [Link] error) {
if (condition) [Link](error);
}

The very simplest form of error for the Notification would be just to use strings as error
messages. I prefer at least a minimal wrapping, defining a simple error class and
defining a fixed list of errors for the interaction in the DTO.

class RegisterClaimDTO...
public static [Link] MISSING_POLICY_NUMBER = new [Link]("Policy number is missi
public static [Link] UNKNOWN_POLICY_NUMBER = new [Link]("This policy number is
public static [Link] MISSING_INCIDENT_TYPE = new [Link]("Incident type is missi
public static [Link] MISSING_INCIDENT_DATE = new [Link]("Incident Date is missi
public static [Link] DATE_BEFORE_POLICY_START
= new [Link]("Incident Date is before we started doing this business");
If you are communicating across tiers you may need to add an ID field to the error to
allow comparisons to work properly when errors are being serialized across the wire.

That pretty much is all the interesting behavior in the domain layer. For the presentation
I'll use an Autonomous View. The behavior we're interested in occurs when the submit
button is pressed.

class FrmRegisterClaim...
RegisterClaimDTO claim;
public void Submit() {
saveToClaim();
[Link](claim);
if ([Link]) {
[Link] = "Not registered, see errors";
indicateErrors();
}
else [Link] = "Registration Succeeded";
}
private void saveToClaim() {
claim = new RegisterClaimDTO();
[Link] = [Link];
[Link] = [Link];
[Link] = (string) [Link];
}

The method pulls information out of the controls to fill the DTO and sends the data to
the domain layer. If the returning DTO contais errors, then we need to display them.

class FrmRegisterClaim...
private void indicateErrors() {
checkError(RegisterClaimDTO.MISSING_POLICY_NUMBER, txtPolicyNumber);
checkError(RegisterClaimDTO.MISSING_INCIDENT_TYPE, cmbType);
checkError(RegisterClaimDTO.DATE_BEFORE_POLICY_START, pkIncidentDate);
checkError(RegisterClaimDTO.MISSING_INCIDENT_DATE, pkIncidentDate);
checkError(RegisterClaimDTO.DATE_BEFORE_POLICY_START, pkIncidentDate);
}
private void checkError ([Link] error, Control control) {
if ([Link](error))
showError(control, [Link]());
}

Here I'm using the errors defined in the DTO and mapping them to fields in the form, so
the right field shows the right errors.

To actually display the errors, I use the standard error provider that comes with .NET.
This displays an error icon next to fields in trouble, and a tooltip to reveal the error
message that's the cause of the problem.

class FrmRegisterClaim...
private ErrorProvider errorProvider = new ErrorProvider();
void showError (Control arg, string message) {
[Link](arg, message);
}

I clear the error information if anything in the fields change.


class FrmRegisterClaim...
void clearError (Control arg) {
[Link](arg, null);
}
private void txtPolicyNumber_TextChanged(object sender, EventArgs e) {
clearError((Control)sender);
}
private void cmbType_TextChanged(object sender, EventArgs e) {
clearError((Control)sender);
}
private void pkIncidentDate_ValueChanged(object sender, EventArgs e) {
clearError((Control)sender);
}


© Martin Fowler | Privacy Policy | Disclosures

Supervising Controller
Factor the UI into a view and controller where the view handles simple mapping to the
underlying model and the the controller handles input response and complex view logic.

Martin Fowler

19 June 2006

This is part of the Further Enterprise Application Architecture


development writing that I was doing in the mid 2000’s. Sadly too
many other things have claimed my attention since, so I haven’t had
time to work on them further, nor do I see much time in the
foreseeable future. As such this material is very much in draft form
and I won’t be doing any corrections or updates until I’m able to find
time to work on it again.

Many UI frameworks provide the ability to easily map between the view and model,
often using some kind of Data Binding. These approaches are very effective in allowing
you to declaratively set up a relationship between elements in the view and model.
Usually, however, there are more complex relationships which require you to have more
complex view logic. This logic can be hard to manage, and in particular hard to test,
while embedded in the view.

Supervising Controller uses a controller both to handle input response but also to
manipulate the view to handle more complex view logic. It leaves simple view behavior
to the declarative system, intervening only when effects are needed that are beyond
what can be achieved declaratively.

How it Works
Supervising Controller decomposes presentation functionality into two parts: a controller
(often called presenter) and view. The domain data that needs to be displayed is
separate, and following rough MVC terminology I'll refer to it as a model, although it
need not be a Domain Model. The basic division of responsibilities echoes the Model-
View-Presenter architecture in its Dolphin form, as described by Bower and McGlashan.

A Supervising Controller has two primary responsibilities: input response and partial
view/model synchronization.

For input response the controller operates in the presenter style. The user gestures are
handled initially by the screen widgets, however all they do in response is to hand these
events off to the presenter, which handles all further logic.

For view/model synchronization the controller defers as much of this as reasonable to


the view. The view typically uses some form of Data Binding to populate much of the
information for its fields. Where Data Binding isn't up to more complex interactions then
the controller steps in.

Figure 1: Class diagram for the assessment example.

Figure 2: Sequence diagram showing the response for putting in a low actual value.

In the assessment window, the initial text change is handled by the text field widget in
the view. This widget is observed by the controller, so when the text changes the
widgets emits an event which results in the controller's actualFieldChanged method
being called. This method then handles the full response to the event. It first updates
the reading model object's actual value. The window observes the reading object so the
change to the reading's value triggers a refresh. It's pretty easy to map the actual and
variance text fields' text to the appropriate properties of the reading, so that updates
those values. For the purposes of our example changing the color is a bit more involved.
The reading object can, and should, determine which category the reading should fit
into. A sophisticated widget might be able to bind its text color to a category like this, but
we'll assume we don't have such a clever young thing. In this case controller takes over
setting the variance field's text color directly.

As the example shows, the essence of a good Supervising Controller is to do as little as


possible. Let the view handle as much as possible and only step in when there's more
possible. Let the view handle as much as possible and only step in when there's more
complex logic involved.

One of the prime reasons to use Supervising Controller is for testability. Assuming the
view is hard to test, by moving any complex logic into the controller, we put the logic in a
place that's easier to test. In order to run tests on the controller, however, we do need
some form of view, so a Test Double is often in order. With the double in place, we don't
have any need for UI framework objects in order to test the more awkward parts of the
UI behavior.

This testability issue affects another decision - whether the controller should access the
view and its widgets directly, or through an intermediary. With an intermediary we build
a Gateway for the the controller. The gateway defines an interface for the controller to
manipulate. One implementation then adapts the window's interface while the other
provides a stub for testing (you could also use a mock). This is the same approach that
you need for Passive View.

Figure 3: Using an intermediary between the controller and the window.

The discussion so far suggests using Flow Synchronization with Supervising Controller,
but this need not be the case. It is possible to use Observer Synchronization, but it
needs to be modified so that it's the controllers that observe the model rather than the
views.

When to Use It
There are two main reasons to look into using a Supervising Controller: to separate out
the complexity of an Autonomous View, and to improve testability.

The separation advantage is that it pulls all the behavioral complexity away from the
basic window itself, making it easier to understand. This advantage is offset by the fact
that the controller is still closely coupled to its screen, needing a pretty intimate
knowledge of the details of the screen. In which case there is a real question mark over
whether it's worth the effort of making it a separate object.

The testability reason is the more compelling one. Many people I've talked to have
found using some form of controller has made a big difference to making a UI that is
properly testable.

If testability is your driver then the driving issue is how much behavior to leave in the
If testability is your driver then the driving issue is how much behavior to leave in the
view. Passive View is a very similar pattern to Supervising Controller, but with the
difference that Passive View puts all the view update behavior in the controller, including
simple cases. This results in extra programming, but does mean that all the presentation
behavior is testable. The choice between the two depends on what kind of Data Binding
support you have and whether you're happy to leave that untested by controller tests.

A third alternative is Presentation Model. This again pulls most behavior away from the
view, but leaves it to the view to synchronize all its updates. There isn't a great deal of
the difference in test coverage between Presentation Model and Supervising Controller
- much of the choice (as with Passive View) depends on personal judgments.


© Martin Fowler | Privacy Policy | Disclosures

Passive View
A screen and components with all application specific behavior extracted into a
controller so that the widgets have their state controlled entirely by controller.

Martin Fowler

18 July 2006

This is part of the Further Enterprise Application Architecture


development writing that I was doing in the mid 2000’s. Sadly too
many other things have claimed my attention since, so I haven’t had
time to work on them further, nor do I see much time in the
foreseeable future. As such this material is very much in draft form
and I won’t be doing any corrections or updates until I’m able to find
time to work on it again.

A perennial problem with building rich client systems is the complication of testing them.
Most rich client frameworks were not built with automated testing in mind. Controlling
these frameworks programaticly is often very difficult.

A Passive View handles this by reducing the behavior of the UI components to the
absolute minimum by using a controller that not just handles responses to user events,
but also does all the updating of the view. This allows testing to be focused on the
controller with little risk of problems in the view.

How it Works
This pattern is yet another variation on model-view-controller and model-view-presenter.
As with these the UI is split between a view that handles display and a controller that
responds to user gestures. The significant change with Passive View is that the view is
made completely passive and is no longer responsible for updating itself from the
model. As a result all of the view logic is in the controller. As a result, there is no
dependencies in either direction between the view and the model.
Figure 1: Unlike most MVC-style configurations, Passive View results in no dependencies between view and
model.

Looking at our regular assessment window example, again we see a view/controller


split, but this time the controller does all the work in figuring out how the view should
display the model. The text field widget receives the user gesture but immediately
hands off to the controller, in the classic MVP movement. The controller then updates
the model, and then handles the reloading of the view from the model. This load actions
involves pulling all the data needed from the model, and using it to update the widgets.
This example shows a coarse-grained synchronization, where any change results in a
complete reload.

Figure 2: When the actual text is edited, all the UI response is handled by the controller.

Figure 3: Classes for the assessment example.

The primary driver for Passive View is testing, as a result it's often valuable to use of
Test Double for the view so that the controller can be tested without needing any
interaction with the UI framework. This needs a intermediate Gateway to be setup as in
Figure 4. This is the same technique that you would use for Supervising Controller. As
with Supervising Controller I've shown a stub here, but this is also a good opportunity to
use a mock.
Figure 4: Setting up the view as a Gateway so that it's easy to substitute the window with a Test Double

When to Use It
The driving reason to use Passive View is to enhance testability. With the view reduced
to a dumb slave of the controller, you run little risk by not testing the view. The controller
can run and be tested outside of the UI environment - indeed if you use a Test Double
for the view you don't need to even have the UI classes available to you.

Passive View isn't the only way make the view sufficiently humble to help in testing.
Presentation Model and Supervising Controller are both reasonable alternatives. The
strength that Passive View has over these two is that both of the alternatives require the
view to do some of the synchronization work, which results in more untestable behavior
than Passive View. Whether this difference is significant or not is a judgment call.

Another advantage that Passive View is a very explicit mechanism. There's very little
reliance on Observer mechanisms or declarative mappings. This makes it much easier
to read the code to see what is happening - particularly useful if you're trying to debug
when things go wrong.


© Martin Fowler | Privacy Policy | Disclosures

Presentation Model
Represent the state and behavior of the presentation independently of the GUI controls
used in the interface

Also Known as: Application Model

Martin Fowler

19 July 2004

This is part of the Further Enterprise Application Architecture


development writing that I was doing in the mid 2000’s. Sadly too
many other things have claimed my attention since, so I haven’t had
time to work on them further, nor do I see much time in the
foreseeable future. As such this material is very much in draft form
and I won’t be doing any corrections or updates until I’m able to find
time to work on it again.

GUIs consist of widgets that contain the state of the GUI screen. Leaving the state of
the GUI in widgets makes it harder to get at this state, since that involves manipulating
widget APIs, and also encourages putting presentation behavior in the view class.

Presentation Model pulls the state and behavior of the view out into a model class that
is part of the presentation. The Presentation Model coordinates with the domain layer
and provides an interface to the view that minimizes decision making in the view. The
view either stores all its state in the Presentation Model or synchronizes its state with
Presentation Model frequently
Presentation Model may interact with several domain objects, but Presentation Model is
not a GUI friendly facade to a specific domain object. Instead it is easier to consider
Presentation Model as an abstract of the view that is not dependent on a specific GUI
framework. While several views can utilize the same Presentation Model, each view
should require only one Presentation Model. In the case of composition a Presentation
Model may contain one or many child Presentation Model instances, but each child
control will also have only one Presentation Model.

Presentation Model is known to users of Visual Works Smalltalk as Application Model

How it Works
The essence of a Presentation Model is of a fully self-contained class that represents all
the data and behavior of the UI window, but without any of the controls used to render
that UI on the screen. A view then simply projects the state of the presentation model
onto the glass.

To do this the Presentation Model will have data fields for all the dynamic information of
the view. This won't just include the contents of controls, but also things like whether or
not they are enabled. In general the Presentation Model does not need to hold all of this
control state (which would be lot) but any state that may change during the interaction of
the user. So if a field is always enabled, there won't be extra data for its state in the
Presentation Model.

Since the Presentation Model contains data that the view needs to display the controls
you need to synchronize the Presentation Model with the view. This synchronization
usually needs to be tighter than synchronization with the domain - screen
synchronization is not sufficient, you'll need field or key synchronization.

To illustrate things a bit better, I'll use the aspect of the running example where the
composer field is only enabled if the classical check box is checked.

Figure 1: Classes showing structure relevant to clicking the classical check box
Figure 2: How objects react to clicking the classical check box.

When someone clicks the classical check box the check box changes its state and then
calls the appropriate event handler in the view. This event handler saves the state of
the view to Presentation Model and then updates itself from the Presentation Model (I'm
assuming a coarse-grained synchronization here.) The Presentation Model contains the
logic that says that the composer field is only enabled if the check box is checked, so
the when the view updates itself from the Presentation Model, the composer field
control changes its enablement state. I've indicated on the diagram that the
Presentation Model would typically have a property specifically to mark whether the
composer field should be enabled. This will, of course, just return the value of the
isClassical property in this case - but the separate property is important because that
property encapsulates how the Presentation Model determines whether the composer
field is enabled - clearly indicating that that decision is the responsibility of the
Presentation Model.

This small example is illustrates the essence of the idea of the Presentation Model - all
the decisions needed for presentation display are made by the Presentation Model
leaving the view to be utterly simple.

Probably the most annoying part of Presentation Model is the synchronization between
Presentation Model and view. It's simple code to write, but I always like to minimize this
kind of boring repetitive code. Ideally some kind of framework could handle this, which
I'm hoping will happen some day with technologies like .NET's data binding.

A particular decision you have to make with synchronization in Presentation Model is


which class should contain the synchronization code. Often, this decision is largely
based on the desired level of test coverage and the chosen implementation of
Presentation Model. If you put the synchronization in the view, it won't get picked up by
tests on the Presentation Model. If you put it in the Presentation Model you add a
dependency to the view in the Presentation Model which means more coupling and
stubbing. You could add a mapper between them, but adds yet more classes to
coordinate. When making the decision of which implementation to use it is important to
remember that although faults do occur in synchronization code, they are usually easy
to spot and fix (unless you use fine-grained synchronization).

An important implementation detail of Presentation Model is whether the View should


reference the Presentation Model or the Presentation Model should reference the View.
Both implementations provide pros and cons.

A Presentation Model that references a view generally maintains the synchronization


code in the Presentation Model. The resulting view is very dumb. The view contains
setters for any state that is dynamic and raises events in response to user actions. The
views implement interfaces allowing for easy stubbing when testing the Presentation
Model. The Presentation Model will observe the view and respond to events by
changing any appropriate state and reloading the entire view. As a result the
synchronization code can be easily tested without needing the actual UI class.

A Presentation Model that is referenced by a view generally maintains the


synchronization code in the view. Because the synchronization code is generally easy to
synchronization code in the view. Because the synchronization code is generally easy to
write and easy to spot errors it is recommended that the testing occur on the
Presentation Model and not the View. If you are compelled to write tests for the view
this should be a clue that the view contains code that should belong in the Presentation
Model. If you prefer to test the synchronization, a Presentation Model that references a
view implementation is recommended.

When to Use It
Presentation Model is a pattern that pulls presentation behavior from a view. As such it's
an alternative to to Supervising Controller and Passive View. It's useful for allowing you
to test without the UI, support for some form of multiple view and a separation of
concerns which may make it easier to develop the user interface.

Compared to Passive View and Supervising Controller, Presentation Model allows you
to write logic that is completely independent of the views used for display. You also do
not need to rely on the view to store state. The downside is that you need a
synchronization mechanism between the presentation model and the view. This
synchronization can be very simple, but it is required. Separated Presentation requires
much less synchronization and Passive View doesn't need any at all.

Example: Running Example (View References PM)


(C#)
Here's a version of the running example, developed in C# with Presentation Model.

Figure 3: The album window.

I'll start discussing the basic layout from the domain model outwards. Since the domain
isn't the focus of this example, it's very uninteresting. It's essentially just a data set with
a single table holding the data for an album. Here's the code for setting up a few test
albums. I'm using a strongly typed data set.

public static DsAlbum AlbumDataSet() {


DsAlbum result = new DsAlbum();
[Link](1, "HQ", "Roy Harper", false, null);
[Link](2, "The Rough Dancer and Cyclical Night", "Astor Piazzola", false, null);
[Link](3, "The Black Light", "Calexico", false, null);
[Link](4, "Symphony No.5", "CBSO", true, "Sibelius" );
[Link]();
return result;
}

The Presentation Model wraps this data set and provides properties to get at the data.
There's a single instance of the Presentation Model for the whole table, corresponding
to the single instance of the window. The Presentation Model has fields for the data set
and also keeps track of which album is currently selected.

class PmodAlbum...
public PmodAlbum(DsAlbum albums) {
this._data = albums;
_selectedAlbumNumber = 0;
}
private DsAlbum _data;
private int _selectedAlbumNumber;

PmodAlbum provides properties to get at the data in the data set. Essentially I provide a
property for each bit of information that the form needs to display. For those values
which are just pulled directly out of the data set, this property is pretty simple.

class PmodAlbum...
public String Title {
get {return [Link];}
set {[Link] = value;}
}
public String Artist {
get {return [Link];}
set {[Link] = value;}
}
public bool IsClassical {
get {return [Link];}
set {[Link] = value;}
}
public String Composer {
get {
return ([Link]()) ? "" : [Link];
}
set {
if (IsClassical) [Link] = value;
}
}
public [Link] SelectedAlbum {
get {return [Link][SelectedAlbumNumber];}
}

The title of the window is based on the album title. I provide this through another
property.

class PmodAlbum...
public String FormTitle
{
get {return "Album: " + Title;}
}

I have a property to see if the composer field should be enabled.

class PmodAlbum...
public bool IsComposerFieldEnabled {
get {return IsClassical;}
}
}

This is just a call to the public IsClassical property. You may wonder why the form
doesn't just call this directly - but this is the essence of the encapsulation that the
Presentation Model provides. PmodAlbum decides what the logic is for enabling that
field, the fact that it's simply based on a property is known to the Presentation Model but
not to the view.

The apply and cancel buttons should only be enabled if the data has changed. I can
provide this by checking the state of that row of the dataset, since data sets record this
information.

class PmodAlbum...
public bool IsApplyEnabled {
get {return HasRowChanged;}
}
public bool IsCancelEnabled {
get {return HasRowChanged;}
}
public bool HasRowChanged {
get {return [Link] == [Link];}
}

The list box in the view shows a list of the album titles. PmodAlbum provides this list.

class PmodAlbum...
public String[] AlbumList {
get {
String[] result = new String[[Link]];
for (int i = 0; i < [Link]; i++)
result[i] = [Link][i].Title;
return result;
}
}

So that covers the interface that PmodAlbum presents to the view. Next I'll look at how I
do the synchronization between the view and the Presentation Model. I've put the
synchronization methods in the view and am using coarse-grained synchronization.
First I have a method to push the state of the view into the Presentation Model.

class FrmAlbum...
private void SaveToPmod() {
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
}

This method is very simple, just assigning the mutable parts of the view to the
Presentation Model. The load method is a touch more complicated.

class FrmAlbum...
private void LoadFromPmod() {
if (NotLoadingView) {
_isLoadingView = true;
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
[Link] = [Link];
_isLoadingView = false;
}
}
private bool _isLoadingView = false;
private bool NotLoadingView {
get {return !_isLoadingView;}
}

private void SyncWithPmod() {


if (NotLoadingView) {
SaveToPmod();
LoadFromPmod();
}
}

The complication here is avoiding a infinite recursion since synchronizing causes fields
on the form to update which triggers synchronization.... I guard against that with a flag.

With these synchronization methods in place, the next step is just to call the right bit of
synchronization in event handlers for the controls. Most of the time this easy, just call
SyncWithPmod when data changes.

class FrmAlbum...
private void txtTitle_TextChanged(object sender, [Link] e){
SyncWithPmod();
}

Some cases are more involved. When the user clicks on a new item in the list we need
to navigate to a new album and show its data.

class FrmAlbum...
private void lstAlbums_SelectedIndexChanged(object sender, [Link] e){
if (NotLoadingView) {
[Link] = [Link];
LoadFromPmod();
}
}

class PmodAlbum...
public int SelectedAlbumNumber {
get {return _selectedAlbumNumber;}
set {
if (_selectedAlbumNumber != value) {
Cancel();
_selectedAlbumNumber = value;
}
}
}
}

Notice that this method abandons any changes if you click on the list. I've done this
awful bit of usability to keep the example simple, the form should really at least pop up a
confirmation box to avoid losing the changes.

The apply and cancel buttons delegate what to do to the Presentation Model.

class FrmAlbum...
private void btnApply_Click(object sender, [Link] e) {
[Link]();
LoadFromPmod();
}
private void btnCancel_Click(object sender, [Link] e){
[Link]();
LoadFromPmod();
}

class PmodAlbum...
public void Apply () {
[Link]();
}
public void Cancel() {
[Link]();
}

So although I can move most of the behavior to the Presentation Model, the view still
retains some intelligence. For the testing aspect of Presentation Model to work better, it
would be nice to move more. Certainly you can move more into the Presentation Model
by moving the synchronization logic there, at the expense of having the Presentation
Model know more about the view.

Example: Data Binding Table Example (C#)


As I first looked at Presentation Model in the .NET framework, it seemed that data
binding provided excellent technology to make Presentation Model work simply. So far
limitations in the current version of data binding holds it back from places that I'm sure it
will eventually go. One area where data binding can work very well is with read-only
data, so here is an example that shows this as well as how tables can fit in with a
Presentation Model design.

Figure 4: A list of albums with the rock ones highlighted.


Figure 4: A list of albums with the rock ones highlighted.

This is just a list of albums. The extra behavior is that each rock album should have it's
row colored in cornsilk.

I'm using a slightly different data set to the other example. Here is the code for some
test data.

public static AlbumList AlbumGridDataSet()


{
AlbumList result = new AlbumList();
[Link](1, "HQ", "Roy Harper", "Rock");
[Link](2, "Lemonade and Buns", "Kila", "Celtic");
[Link](3, "Stormcock", "Roy Harper", "Rock");
[Link](4, "Zero Hour", "Astor Piazzola", "Tango");
[Link](5, "The Rough Dancer and Cyclical Night", "Astor Piazzola", "Tango");
[Link](6, "The Black Light", "Calexico", "Rock");
[Link](7, "Spoke", "Calexico", "Rock");
[Link](8, "Electrica", "Daniela Mercury", "Brazil");
[Link](9, "Feijao com Arroz", "Daniela Mercury", "Brazil");
[Link](10, "Sol da Libertade", "Daniela Mercury", "Brazil");
[Link](result);
return result;
}

The presentation model in this case reveals its internal data set as a property. This
allows the form to data bind directly to the cells in the data set.

private AlbumList _dsAlbums;


internal AlbumList DsAlbums {
get {return _dsAlbums;}
}

To support the highlighting, the presentation model provides an additional method that
indexes into the table.

internal Color RowColor(int row) {


return (Albums[row].[Link]("Rock")) ? [Link] : [Link];
}
private [Link] Albums {
get {return [Link];}
}

This method is similar to the ones in a simple example, the difference being that
methods on table data need cell coordinates to pick out parts of the table. In this case
all we need is a row number, but in general we may need row and column numbers.

From here on I can use the standard data binding facilities that come with visual studio.
I can bind table cells easily to data in the data set, and also to data on the Presentation
Model.

Getting the color to work is a little bit more involved. This is straying a little bit away from
the main thrust of the example, but the whole thing gets its complication because there's
no way to have row by row highlighting on the standard WinForms table control. In
general the answer to this need is to buy a third party control, but I'm too cheap to do
this. So for the curious here's what I did (the idea was mostly ripped off from
this. So for the curious here's what I did (the idea was mostly ripped off from
[Link] I'm going to assume you're familiar with
the guts of WinForms from now on.

Essentially I made a subclass of DataGridTextBoxColumn which adds the color


highlighting behavior. You link up the new behavior by passing in a delegate that
handles the behavior.

class ColorableDataGridTextBoxColumn...
public ColorableDataGridTextBoxColumn (ColorGetter getcolorRowCol, DataGridTextBoxColumn original)
{
_delGetColor = getcolorRowCol;
copyFrom(original);
}
public delegate Color ColorGetter(int row);
private ColorGetter _delGetColor;

The constructor takes the original DataGridTextBoxColumn as well as the delegate.


What I'd really like to do here is to use the decorator pattern to wrap the original but the
original, like so many classes in WinForms, is all sealed up. So instead I copy over all
the properties of the original into my subclass. This won't work is there are vital
properties that can't be copied because you can't read or write to them. It seems to work
here for now.

class ColorableDataGridTextBoxColumn...
void copyFrom (DataGridTextBoxColumn original) {
PropertyInfo[] props = [Link]().GetProperties();
foreach (PropertyInfo p in props) {
if ([Link] && [Link])
[Link](this, [Link](original, null), null) ;
}
}

Fortunately the paint method is virtual (otherwise I would need a whole new data grid.) I
can use it to insert the appropriate background color using the delegate.

class ColorableDataGridTextBoxColumn...
protected override void Paint([Link] g, [Link] bounds,
[Link] source, int rowNum,
[Link] backBrush, [Link] foreBrush,
bool alignToRight)
{
[Link](g, bounds, source, rowNum, new SolidBrush(_delGetColor(rowNum)), foreBrush, alignToRight);
}

To put this new table in place, I replace the columns of the data table in the page load
after the controls have been built on the form.

class FrmAlbums...
private void FrmAlbums_Load(object sender, [Link] e){
bindData();
replaceColumnStyles();
}
private void replaceColumnStyles() {
[Link](dgsAlbums,
[Link](dgsAlbums,
new [Link]([Link]));
}

class ColorableDataGridTextBoxColumn...
public static void ReplaceColumnStyles(DataGridTableStyle grid, ColorGetter del) {
for (int i = 0; i < [Link]; i++) {
DataGridTextBoxColumn old = (DataGridTextBoxColumn) [Link][0];
[Link](0);
[Link](new ColorableDataGridTextBoxColumn(del, old));
}
}

It works, but I'll admit it's a lot more messy than I would like. If I were doing this for real,
I'd want to look into a third party control. However I've seen this done in a production
system and it worked just fine.


© Martin Fowler | Privacy Policy | Disclosures

Event Aggregator
Channel events from multiple objects into a single object to simplify registration for
clients.

Martin Fowler

29 September 2004

This is part of the Further Enterprise Application Architecture


development writing that I was doing in the mid 2000’s. Sadly too
many other things have claimed my attention since, so I haven’t had
time to work on them further, nor do I see much time in the
foreseeable future. As such this material is very much in draft form
and I won’t be doing any corrections or updates until I’m able to find
time to work on it again.

A system with lots of objects can lead to complexities when a client wants to subscribe
to events. The client has to find and register for each object individually, if each object
has multiple events then each event requires a separate subscription.

An Event Aggregator acts as a single source of events for many objects. It registers for
all the events of the many objects allowing clients to register with just the aggregator.
all the events of the many objects allowing clients to register with just the aggregator.

How it Works
An Event Aggregator is a simple element of indirection. In its simplest form you have it
register with all the source objects you are interested in, and have all target objects
register with the Event Aggregator. The Event Aggregator responds to any event from a
source object by propagating that event to the target objects.

The simplest Event Aggregator aggregates events from multiple objects into itself,
passing that same event onto its observers. An Event Aggregator can also generalize
the event, converting events that are specific to a source object into a more generic
event. That way the observers of the aggregators don't need to register for as many
individual event types. This simplifies the registration process for observers, at the cost
of being notified of events that may not have any material effect on the observer.

Since an Event Aggregator is based around observer, it's important to take into account
all of the danger areas with observer.

When to Use It
Event Aggregator is a good choice when you have lots of objects that are potential
event sources. Rather than have the observer deal with registering with them all, you
can centralize the registration logic to the Event Aggregator. As well as simplifying
registration, a Event Aggregator also simplifies the memory management issues in
using observers.

Further Reading
You can think of an Event Aggregator as a particular form of Facade that focuses only
on observer relationships.

Example: Watching Our Consultants (C#)


When someone joins ThoughtWorks, they get immediately issued with a mobile phone.
The old joke was that this was because Roy (the CEO) wanted to be able to call you
any time day or night. So here I'm imagining a simple applications which tells Roy the
location of all his consultants and whether they are available to be called on the phone.

Figure 1: Consultant class

To capture this we have consultant objects as in Figure 1. When consultants move


around we capture this by messages about these movements indicating which
consultant moved and where they are now.

When these messages are received by the system they are passed to a consultant
object to process them and update the consultant's status. Updating the current location
is rather obvious, updating the availability has some mild computation - essentially each
consultant has a home and can choose whether they are available while at home. (It's
assumed that when on the road they are always subject to Roy's telephonic whims.)
assumed that when on the road they are always subject to Roy's telephonic whims.)

class Consultant...
public bool IsAvailable {
get {return IsAvailableAt(_current_location);}
}
private bool IsAvailableAt(string location) {
return (location == Home) ? _availableAtHome : true;
}

So when the consultant handles the movement message it has to worry about two
things that may change - the current location and the availability. It signals a separate
event for each.

class Consultant...
public void HandleMovement(MsgMovement movement) {
if (_current_location != [Link]) {
if (LocationChanged != null) LocationChanged(this, [Link]);
if (IsAvailableAt([Link]) != IsAvailable) {
if (AvailabilityChanged != null) AvailabilityChanged(this, [Link]);
}
_current_location = [Link];
}
}

The screen for this application might choose to register for these events for all the
consultants, but here I'll use an Event Aggregator. The Event Aggregator monitors an
consultant by registering for all its events.

class EventAggregator...
public void Listen (Consultant subject) {
[Link] += new [Link](HandleConsultantLocationChanged);
[Link] += new [Link](HandleConsultantAvailabilityChan
}

When it receives an event it signals two events, a specific one for the type of change
and a general one just indicating a change has occurred. This allows clients to register
to the granularity they wish.

class EventAggregator...
private void HandleConsultantLocationChanged (Consultant consultant, EventArgs args) {
if (ConsultantLocationChanged != null) ConsultantLocationChanged(consultant, args);
if (ConsultantChanged != null) ConsultantChanged(consultant, args);
}
private void HandleConsultantAvailabilityChanged (Consultant consultant, EventArgs args) {
if (ConsultantAvailabilityChanged != null) ConsultantAvailabilityChanged(consultant, args);
if (ConsultantChanged != null) ConsultantChanged(consultant, args);
}
public event [Link] ConsultantChanged;
public event [Link] ConsultantLocationChanged;
public event [Link] ConsultantAvailabilityChanged;

Most of the time, I'd suggest using just a single coarse-grained event. However this
gives a good example of how you can react to the incoming events by providing a
variety of different reactions depending on the needs of your clients. This also allows the
Event Aggregator to act as an Adapter as well as a facade.


© Martin Fowler | Privacy Policy | Disclosures

Window Driver
Provide a programmatic api to drive and interrogate a UI window.

Martin Fowler

26 August 2004

This is part of the Further Enterprise Application Architecture


development writing that I was doing in the mid 2000’s. Sadly too
many other things have claimed my attention since, so I haven’t had
time to work on them further, nor do I see much time in the
foreseeable future. As such this material is very much in draft form
and I won’t be doing any corrections or updates until I’m able to find
time to work on it again.

A user interface window acts as an important gateway to a system. Despite the fact that
it runs on a computer, it often isn't really very computer friendly - in particular it's often
difficult to program it to carry out tasks automatically. This is particularly a problem for
testing where automated tests do a great deal to simplify the whole development
process.

Window Driver is an programmatic API for a UI window. A Window Driver should allow
programs to control all dynamic aspects of a window, invoking any action and retrieving
any information that's available to a human user.

How it Works
The basic rule of thumb for a Window Driver is that it should allow a software client to
do anything and see anything that a human can. It should also provide an interface
that's easy to program to and hides the underlying widgetry in the window. So to access
a text field you should have accessor methods that take and return a string, check
boxes should use booleans, and buttons should be represented by action oriented
method names. The Window Driver should encapsulate the mechanics required to
actually manipulate the data in the gui control itself. A good rule of thumb is to imagine
changing the concrete control - in which case the Window Driver interface shouldn't
change.
The names in the interface of the Window Driver should reflect the visible UI, so name
elements after their labels on the screen.

Rich client windows usually organize their controls into a complicated hierarchical
structure. This is particularly the case when you use flow based layouts as opposed to
absolute coordinate layouts. The Window Driver should hide the layout design as much
as possible from the interface. That way changes to the internal layout shouldn't cause
clients to change. An exception to this may be multipart windows using techniques like
tabs or sidebar selectors. In this case the sheer number of controls make it worthwhile
to split up the programmatic api into separate Window Driver classes.

One of the more tricky aspects of a Window Driver with modern UIs is dealing with
mutliple threads. Usually once a window is launched it runs on a different thread to the
driving program. This can cause nasty threading bugs to breed that makes the Window
Driver unreliable. There are a couple of ways to deal with this. One is to use a library
that will put requests onto the UI thread. Another is to not actually launch the window so
that it never actually goes into the UI thread.

The interface of a Window Driver can expose either the widgets themselves, or expose
methods that make the changes you're interested in making on the widgets. So if you
want to expose a text field in swing, you can either do it by a single method JTextField
getArtistField(); or with methods for the different aspects of a field String
getArtistField(), void setArtistField(String text), bool
getArtistFieldEnabled(). Returning the field itself is simpler, but does mean that the
client of the Window Driver is dependent upon the windowing system and programmers
using the Window Driver need to be familiar with how the windowing system works. It
also means that windowing system has to fire events on changes to the widgets that are
done by calling methods on them directly. On the whole I prefer to return the widgets
unless there is a good reason not to.

When to Use It
The most common use for a Window Driver is for testing, particularly when using an
Autonomous View. The Window Driver isolates the tests from the details of the
implementation of view, simplifying writing the tests and isolating them from changes in
organization of the view.

Window Driver can also be used to provide a scripting interface on top of the
application. However in most cases it's better to write such an interface on a lower layer
in the system. One case where this may be difficult is when you have an application with
lots of behavior embedded into the view and it's too difficult to move this behavior into a
lower layer. I'd still prefer to move the behavior if I could.

Window Driver may not be needed if you work hard to provide a really thin view.
Patterns such as Supervising Controller, Passive View and Presentation Model aim to
make a Window Driver unneccessary.

Example: The Swing Album Example (Java)


Here's the Window Driver I used for the album running example. One of my
requirements was that I could write a single set of tests which would test multiple
implementations of the this window using different patterns. This isn't going to be a
common requirement, but it helps show how the Window Driver can provide some
implementation independence.

I begin by defining the common interface for the Window Driver

public interface AlbumWindowDriver {


JList getAlbumList();
JTextField getTitleField();
JPanel getMainPane();
JPanel getAlbumDataPane();
JPanel getApplyPanel();
JScrollPane getAlbumListPane();
JTextField getComposerField();
JCheckBox getClassicalCheckBox();
JSplitPane getSplitPane();
JButton getApplyButton();
JButton getCancelButton();
JTextField getArtistField();
JFrame getWindow();
}

As you can see this just exposes the various widgets for manipulation. I then implement
this interface directly in the various view implementations that I have.

In my case I'm driving the tests using Jemmy. The testcase class uses Jemmy's
operators to wrap the controls exposed by the Window Driver.

private JTextFieldOperator title;


private JTextFieldOperator artist;
private JListOperator list;
private JFrameOperator window;
private JCheckBoxOperator isClassical;
private JTextFieldOperator composer;
private JButtonOperator applyButton, cancelButton;
private Album[] albums = (Album[]) [Link]().toArray(new Album[[Link]().size()]);

protected void setUp() throws Exception {


AlbumWindowDriver frame = doCreateFrame();
window = new JFrameOperator([Link]());
title = new JTextFieldOperator([Link]());
list = new JListOperator([Link]());
artist = new JTextFieldOperator([Link]());
isClassical = new JCheckBoxOperator([Link]());
composer = new JTextFieldOperator([Link]());
applyButton = new JButtonOperator([Link]());
cancelButton = new JButtonOperator([Link]());
}
protected abstract AlbumWindowDriver doCreateFrame();

I'm using Jemmy's operators to handle the threading issues. Jemmy also provides
capability to allow you to find controls in a form's hierarchy, but I don't need that as the
Window Driver gets me directly to the controls I need.

The abstract method doCreateFrame() is there so I can use a subclass to setup the
actual view implementation I'm using. Unless you have this odd requirement you can
just instantiate the view inline.

With the various variables setup, I can now write tests that directly manipulate the
With the various variables setup, I can now write tests that directly manipulate the
controls.

public void testCheckClassicalBoxEnablesComposerField() {


[Link](4);
assertEquals("Zero Hour", [Link]());
[Link]();
assertTrue([Link]());
assertTrue("composer field not enabled", [Link]());
[Link]();
[Link](0);
[Link](4);
assertTrue("composer field not enabled after switch", [Link]());
}


© Martin Fowler | Privacy Policy | Disclosures

Flow Synchronization
Synchronize screens with an underlying model based on the flow of the user interaction
between the screens.

Martin Fowler

15 November 2004

This is part of the Further Enterprise Application Architecture


development writing that I was doing in the mid 2000’s. Sadly too
many other things have claimed my attention since, so I haven’t had
time to work on them further, nor do I see much time in the
foreseeable future. As such this material is very much in draft form
and I won’t be doing any corrections or updates until I’m able to find
time to work on it again.

Applications often contain multiple screens that display the same data. If the data is
edited in one screen, then the other screens must be updated to reflect the changes.

Flow Synchronization does this by having the screen code explicitly re-synchronize at
the appropriate point in the work flow of the screen.

How it Works
Flow Synchronization is a very simple approach to explain. Essentially each time you do
something that changes state that's shared across multiple screens, you tell each
screen to update itself. The problem is that this means, in general, that every screen is
somewhat coupled to the other the other screens in the application. If you have a lot of
screens that are working in a very open-ended way, this can be nasty - which is
Observer Synchronization is such a strong alternative.

Flow Synchronization thus better with simple navigation styles.

One common style is a root and child style. Here you have a root window that is open
for the whole application. When you want more detailed information you open a child
window, which is often modal. In this situation it's easy to use Flow Synchronization, all
you need to do is to update the root whenever you close a child. If you do this in the
root screen the child doesn't need to be aware of the root.
root screen the child doesn't need to be aware of the root.

If the child is non-modal, this can get become more difficult. It's straightforward if you
follow the approach of only updating the data (and thus the root) when the child is
closed. If you want updates while the child window is still open then you are moving
towards the territory of Observer Synchronization. It's also problematic if data is shared
between the children.

Another simple style is a wizard style where you have a sequence of screens in order.
With a wizard each screen is modal and movement from one screen to another involved
closing the old screen and opening another. So in this situation Flow Synchronization is
easy to do: update the data on closing a screen and load the fresh data when opening
the next screen. You can have a wizard sequence of modal children with a root screen
where closing the last child updates the root.

When to Use It
Flow Synchronization is an alternative to Observer Synchronization for synchronizing
screens with domain data. It is, in many ways a more explicit and straightforward way of
doing things. Instead of implicit Observer relationships which can be hard to see and
debug, you have explict synchronization calls clearly laid out in the code.

The problem with Flow Synchronization is that things can get very messy once you have
an unconstrained amount of screens that may share data. Any change on any screen
needs to trigger other screens to update. Doing this through explicit calls to other
screens makes screens very interdependent. This is where Observer Synchronization is
so much easier.

Despite its limitations, Flow Synchronization does have its place. It works well providing
the navigational flow of the user interface is simple and only one or two screen are
active at the same time. Examples of such situations are sequences of screens (such
as wizards) and a root screen with modal children. Observer Synchronization will also
work with these cases but you may find the more explicit approach preferable. Web user
interfaces are effectively a sequence of screens and thus work effectively with Flow
Synchronization, this is an example where the protocol of the client/server connection
makes Observer Synchronization very difficult to do.

Example: Root and Child Restaurent List (Java)


With example I hava couple of simple screens. The root is a list of restaurents. To edit
the list you click on the restaurent entry to edit the details. If you change the name, then
the list needs to update itself, both in the contents of the name and also to preserve
alphabetical order.

The restaurent class is so boring I won't repeat it here. There are just string fields
corresponding to the fields on the UI and the attendent getters and setters. Not much of
a class, but it's not the focus of this discussion so I can permit its sad, pathetic
existance.

The form that edits the restaurent details is also rather simple. I have a single flobal
update listener that I attach to each field, so any change in a field causes a global
refresh of the underlying domain object and the form - this is coarse-grained
synchronization.
class RestaurentForm…
public class FieldListener extends GlobalListener {
void update() {
save();
load();
}
}
private void load() {
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
private void save() {
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}

The restaurent list needs to be updated at two points, on initial creation of the form and
whenever a child window closes. I put the code to update the list in a method.

class RestaurentListForm...
void load() {
sortModel();
[Link](getRestaurentNames());
}

private String[] getRestaurentNames() {


String[] result = new String[[Link]()];
int i = 0;
for (Restaurent r : model) result[i++] = [Link]();
return result;
}

private void sortModel() {


[Link](model, new Comparator<Restaurent>() {
public int compare(Restaurent r1, Restaurent r2) {
return [Link]().compareTo([Link]());
}
});
}

I then call it from the constructor of the form and from an action listener attached to the
edit button.

class RestaurentListForm...
public RestaurentListForm(List<Restaurent> model) {
[Link] = model;
buildForm();
load();
[Link]();
[Link](true);
}

private class EditActionListener implements ActionListener {


private class EditActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
new RestaurentForm(window, selectedRestaurent());
load();
}
}

Comparing to a custom List Model

An obvious alternative to this approach is to use a custom list model. The


implementation above uses a built in list model which takes a copy of the data from my
list of restaurents. An alternative to a copy is to provide my own list model
implementation that is just a wrapper on the underlying list of restaurents.

private class RestaurentListModel extends AbstractListModel {


private List<Restaurent> data;
public RestaurentListModel(List<Restaurent> data) {
[Link] = data;
}
public int getSize() {
return [Link]();
}
public Object getElementAt(int index) {
return [Link](index).getName();
}
}

Now I create this wrapper on the list of restaurents and supply it to the list widget when I
create it. This way the list uses the underlying list of restaurents as its model, rather than
a separate list of strings. Any changes I make to the restaurent name is automatically
propagated through to the screen, so I don't have to write or call the load method.

A more tricky question is what to do about the sort order of the list. If the sort order
makes sense for the domain classes, then I can simply sort them there, as long as I re-
sort the restaurent list when I change a name. Often, however, sort orders are particular
to a screen, in that different screens may have different sort orders. In this case
triggering the sort scheme can be more of a problem. An alternative is to sort the list
each time it's asked for - but that may make the UI unresponsive, particularly if the list is
large.


© Martin Fowler | Privacy Policy | Disclosures

Observer Synchronization
Synchronize multiple screens by having them all be observers to a shared area of
domain data.

Martin Fowler

08 September 2004

This is part of the Further Enterprise Application Architecture


development writing that I was doing in the mid 2000’s. Sadly too
many other things have claimed my attention since, so I haven’t had
time to work on them further, nor do I see much time in the
foreseeable future. As such this material is very much in draft form
and I won’t be doing any corrections or updates until I’m able to find
time to work on it again.

In some applications you have multiple screens available that display presentations of a
common area of data. If a change is made to the data through one of these screens,
you want all the other screens to update correctly. However you don't want each screen
to know about the others, because that would increase the complexity of the screens
and make it harder to add new ones.

Observer Synchronization uses a single area of domain oriented data and has each
screen be an observer of that data. Any change in one screen propagates to that
domain oriented data and thence to the other screens. This approach was a large part
of the Model View Controller approach.

How it Works
The essence of this approach is that each screen, with its associated screen state, acts
as an Observer on a common area of session data. All changes to the session data
result in events which the screens listen to and respond by reloading from the session
data. Once you have this mechanism set up, then you can ensure synchronization
simply by coding each screen to update the session data. Even the screen that makes
the change doesn't need to refresh itself explicitly, since the observer mechanism will
trigger the refresh in the same way as if another screen made the change.
Perhaps the biggest issue in this design is deciding what granularity of events to use
and how to set up the propagating and observer relationships. At the very fine-grained
level each bit of domain data can have separate events to indicate exactly what
changed. Each screen registers for only the events that may invalidate that screen's
data. The most coarse grained alternative is to use an Event Aggregator to funnel all
events into a single channel. That way each screen does a reload if any piece of domain
data changes, whether or not it would have affected the screen.

As usual the trade-off is between complexity and performance. The coarse-grained


approach is much simpler to set up and less likely to breed bugs. However a coarse
grained approach leads to lots of uneccessary refreshes of the screen, which might
impact performace. As usual my advice is to start coarse grained and introduce
appropriate fine-grained mechanisms only when needed after measuring an actual
performance problem.

Events tend to be hard to debug since you can't see the chain of invocations by looking
at the code. As a result it's important to keep the event propagation mechanism as
simple as you can, which is why I favor coarse-grained mechanisms. A good rule of
thumb is to think of your objects as layered and to only allow observer relationships
between layers. So one domain object should not observe another domain object, only
presentation objects should observe domain objects.

Another thing to be very wary of is chains of events, where one event causes another
event to fire. Such event chains can quickly get very hard to follow because you can't
understand the behavior by looking at the code. As a result I tend to discourage events
within a layer and prefer either a single line of events, or going through an Event
Aggregator.

When an observer registers for an event, you get a reference from the subject to the
observer. If the observer doesn't remove itself from the subject when you get rid of the
screen, you have a zombie reference and a memory leak. If you destroy and create
domain data with each session and your session is short, this may not lead to a
problem. However a long lived domain object could lead to a serious leak.

When to Use It
Observer Synchronization is a particularly vital pattern when you have multiple active
windows that share common data. In this situation the alternative, having windows
signal each other to refresh, gets quite complicated as each window needs to know
about other windows and when they are likely to need a refresh. Adding new windows
means updating the information. With this approach adding new windows is very
straightforward and each window can be setup to maintain its own relationship with the
common domain data.

The principal disadvantage of Observer Synchronization is the implicit behavior


triggerred by events which is difficult to visualize from the code. As a result bugs in
event propagation can be very hard to find and fix.

Observer Synchronization can also be used with simpler navigational styles, although in
these cases Flow Synchronization is a reasonable alternative. The value of Observer
Synchronization may not outweigh the complexity introduced by using events for
updates.

Further Reading
Further Reading
This pattern is obviously very similar to Observer and is a central part of Model View
Controller. I see the main difference between this and observer is that this is a particular
use of observer - albeit the most common one. I see this part of several patterns that
make up Model View Controller.

Acknowledgements
Patrik Nordwall pointed out the problem with observers and memory leaks.

Example: Albums and Performers (C#)

Figure 1: Screens to display albums and performers.

Consider an application like Figure 1. We have active screens to edit names of


performers and the albums they appear from. If I edit the title of the album "Kind of
Blue" I want my edits to appear not just in the text box and form title of the album
screen, but also in the list entries for Miles Davis and John Coltrane.

Figure 2: Domain objects for album and peformer.

In this case I'm holding the domain data in a couple of simple domain objects for
performers and albums Figure 2. When I change the data in one of these classes I
need to propagate an event.

class Album : DomainObject


class Album : DomainObject
public string Title {
get { return _title; }
set {
_title = value;
SignalChanged();
}
}
string _title;

class DomainObject...
public void SignalChanged() {
if (Changed != null) Changed (this, null);
}
public event DomainChangeHandler Changed;

public delegate void DomainChangeHandler (DomainObject source, EventArgs e);

Here I just have a simple changed event defined in a Layer Supertype. This event
doesn't give any information about the change, just that some change has occurred -
suitable for a coarse-grained synchronization from the client.

In the form, I create a new album form by passing in an album. The constructor does its
usual gui stuff, sets the album reference, wires up the event listeners and finally loads
data from the album.

class FrmAlbum...
public FrmAlbum(Album album) {
InitializeComponent();
this._album = album;
observeDomain();
load();
}
private Album _album;
private void observeDomain() {
_album.Changed += new DomainChangeHandler(Subject_Changed);
foreach (Performer p in _album.Performers)
[Link] +=new DomainChangeHandler(Subject_Changed);
}
private void Subject_Changed(DomainObject source, EventArgs e) {
load();
}

The event listening is wired up so that any change in a dependent domain object
causes the form to reload its data.

class FrmAlbum...
private void load() {
[Link] = _album.Title;
[Link] = _album.Title;
[Link] = performerNames();
}
private string[] performerNames() {
ArrayList result = new ArrayList();
foreach (Performer p in _album.Performers)
[Link]([Link]);
return (string[]) [Link](typeof (string));
return (string[]) [Link](typeof (string));
}

If I change the title in the album, I make that change directly on the underlying domain
object.

class FrmAlbum...
private void txtTitle_TextChanged(object sender, EventArgs e) {
this._album.Title = [Link];
}

You could acheive much of this using data binding as long as each form can participate
in the binding with the shared domain objects. Another variation would be to use an
Event Aggregator - this would allow each form to register only with the aggregator and
not to have to register with each domain object. In the absence of performance issues, I
would do it that way - I didn't here as I prefer to keep examples as independent of each
other as possible.

If you're using Supervising Controller or Passive View the controller would act as the
observer of the domain events. If you're using Presentation Model then the Presentation
Model would act as the observer.


© Martin Fowler | Privacy Policy | Disclosures

Presentation Chooser
Select a screen appropriate for a particular domain object

Martin Fowler

31 August 2004

This is part of the Further Enterprise Application Architecture


development writing that I was doing in the mid 2000’s. Sadly too
many other things have claimed my attention since, so I haven’t had
time to work on them further, nor do I see much time in the
foreseeable future. As such this material is very much in draft form
and I won’t be doing any corrections or updates until I’m able to find
time to work on it again.

When the navigation between screens is directed by the presentation, the presentation
can encode the sequence of screens to display directly. This way the presentation
always knows which screen needs to be opened whenever a suitable event occurs.
Sometimes, however, the screen that should be displayed depends upon information in
the domain. The presentation does not know which screen to show, instead it knows
that it should display a domain object in some window. The domain object cannot
choose the screen, because that would violate Separated Presentation

A Presentation Chooser resovles what screen should be used for a particular domain
object. The client knows it should open a new screen to display a particular domain
object. The client asks the Presentation Chooser what screen should be used for this
domain object and opens the returned window.

How it Works
In its simplest form, you can think of a Presentation Chooser as a dictionary lookup
which indexes types of domain objects with types of screens.

Order => OrderWindow


Customer => CustomerWindow
PriorityCustomer => PriorityCustomerWindow
With this simple mode, looking up the appropriate screen is something like
aPresentationChooser[[Link]].

Although this simple idea is the essence of Presentation Chooser, there are some
common areas where things can get a bit more involved. Most of these stem from the
fact that although most lookups are based entirely on the type of the domain object, not
all are. As a result it's usually not worth exposing the type lookup nature of the
Presentation Chooser to its clients, so rather than asking the client to pass in the type of
domain object, instead pass in the object itself. This follows a general principle that an
object should never ask a client to do what it can reasonably do itself. It also allows the
Presentation Chooser to provide more sophisticated lookup rules should it need to.

The Presentation Chooser is usually a Service. During initialization some configuration


module will initialize the Presentation Chooser with details about how screens and
domain objects map together. Then during normal execution the screen uses the
Presentation Chooser to lookup screens.

When to Use It
You need Presentation Chooser when you have to use a different screen class (usually
a window, but could be an embedded panel in a form) in response to the same
navigational flow. A simple example, as I use below, is where you have different types
of objects in a single list and you need a different screen for each type.

Often the best way to handle this kind of situation is to use the same type of screen, but
use hidden and disabled controls on that screen to block access to innapropriate data. If
the variations between the types are small and you can use a similar screen without a
jarring interface, then this can work well. When screen loads you interrogate the domain
object to decide which controls to enable and display.

However using the same variable screen gives you less options for custom display of
the underlying domain object. Sometimes the similarities will end up confusing the user
more than helping them. In these cases it's better to use a different screen entirely, and
the Presentation Chooser is then useful to determine which one.

Although I concentrate here on varying the screen depending on the domain data, the
variation can also include overall customization factors, such as the user, the user's
affiliation, multiple providers of the same application, or different aspects of the state of
the interaction. All of these customizations may lead to using a different screen classes
dynamically and thus imply an indirection in choosing the actual screen class to use. In
these cases a Presentation Chooser is a good way of providing that indirection.

Both Presentation Chooser and Application Controller decouple the choice of screen
class the triggerring navigation. Presentation Chooser is best when the domain object to
be displayed is the primary variation, Application Controller is better when the state of
the application is the primary variation. When both vary it makes sense to combine the
patterns.

Example: Simple Lookup (C#)


The simplest example of a Presentation Chooser is one that has a simple lookup
capability based solely on the type of domain object. Consider a application that
displays information about musical recordings. The recordings are shown in a list, any
one can be edited. However the underlying recordings need to edited differently
depending on whether they are classical or popular recordings.

Figure 1: A window for picking recordings.

To react to this I have an event handler for clicking the edit button

private void btnEdit_Click(object sender, EventArgs e) {


edit(Recordings[[Link]]);
}
private void edit(IRecording recording) {
[Link](recording);
}

The crux of this pattern is the edit method which asks a Presentation Chooser to display
the dialog for editing the selected recording depending on whether it is a classical or
popular recording.

In this case the Presentation Chooser is really just a dictionary lookup. During
initialization we load the Presentation Chooser with details of the domain type and
corresponding window to use.

class PresentationChooser...
protected IDictionary presenters = new Hashtable();
public virtual void RegisterPresenter(Type domainType, Type presentation) {
presenters[domainType] = presentation;
}

This initialization just simply stores the domain and presentation types in a dictionary.
The lookup process is a little more complex. If I add a subtype of classical recording
later on, I want it to be edited by a classical recording unless I've registered a screen for
that subtype.

class PresentationChooser...
public RecordingForm ShowDialog (Object model) {
Object[] args = {model};
RecordingForm dialog = (RecordingForm) [Link](this[model], args);
[Link]();
return dialog;
}
public virtual Type this [Object obj] {
get {
Type result = lookupPresenter([Link]());
if (result == null)
[Link]("Unable to show form", "Error", [Link], [Link]);
return result;
}
}
private Type lookupPresenter(Type arg)
{
Type result = (Type)presenters[arg];
return (null == result) ? lookupPresenter([Link]) : result;
}

I've written this to show an error message dialog if it can't find a registered screen. I can
avoid needing to show this by providing a screen at the top of the hierarchy when I
register the screens.

[Link](typeof(ClassicalRecording), typeof(FrmClassicalRecording));
[Link](typeof(PopularRecording), typeof (FrmPopularRecording));
[Link](typeof(Object), typeof (FrmNullPresentation));

Example: Conditional (C#)


Here I take the simple example above and give it a slightly more sophisticated spin by
allowing some more dynamic chooser behavior. In this scenario I want most classical
recording to be displayed by the regular classical display form, but to use a special
display form for anything composed by Mozart. (I'm not sure why I'd want to do that, but
I'm not so good at coming up with convincing examples on a Tuesday.)

Much of the interface to the Presentation Chooser is the same as the simpler version.
The code to display a dialog for a recording is still just
[Link](aRecording). However the implementation of the Presentation
Chooser is a bit more involved.

I'm still using a dictionary indexed by type to store the information. However this time I
want to have multiple screens for each domain object. I can capture each choice with a
class.

class DynamicPresentationChooser…
Type _registeredType;
Type _presentation;
ConditionDelegate _condition;
public delegate bool ConditionDelegate(Object recording);
public PresentationChoice(Type registeredType, Type presentation, ConditionDelegate condition) {
this._registeredType = registeredType;
this._presentation = presentation;
this._condition = condition;
}

Here I'm using the C# delegate to allow the client to pass in a boolean function to
evaluate a condition against a domain object. The new lookup capability checks all the
evaluate a condition against a domain object. The new lookup capability checks all the
choices in the list in sequence returning the first one whose condition delegate
evaluates to true with the given domain object.

class PresentationChoice...
public override Type this[Object obj] {
get {
IList list= presenterList([Link]());
return (null == list) ? typeof(FrmNullPresentation): chooseFromList(list, obj);
}
}
private IList presenterList(Type type) {
IList result = (IList) presenters[type];
if (null != result)
return result;
else if (typeof (object) != type)
return presenterList([Link]);
else
return new ArrayList();
}
private static Type chooseFromList(IList list, object domainObject) {
foreach (PresentationChoice choice in list)
if ([Link](domainObject)) return [Link];
return typeof(FrmNullPresentation);
}

If nothing matches I return a Null Object.

To register the screens, I decided I wanted to maintain a compatable interface to the


simple case above. To do that I allow registration with just the domain and screen types
to work just like before with the help of a couple of convenience methods.

class DynamicPresentationChooser...
public override void RegisterPresenter(Type domainType, Type presentation) {
presenters[domainType] = new ArrayList();
presenterList(domainType).Add (new PresentationChoice (domainType, presentation));
}

class PresentationChoice...
public PresentationChoice(Type domainType, Type presentation) :
this (domainType, presentation, null){
_condition = new ConditionDelegate(TrueConditionDelegate);
}
public static bool TrueConditionDelegate(Object ignored) {return true;}

This way I can use the dynamic chooser in any sitatuion where I'd otherwise use the
simple chooser.

I then use an additional registration method to put in dynamic options. I've set this up so
I can only do this when I already have a default choice present. This makes the
configuration interface a little more awkward than I'd like, but this way any problems
show up in configuration so the result fails fast.

class DynamicPresentationChooser...
public void RegisterAdditionalPresenter(Type domainType, Type presentation, [Link]
[Link](
null != presenterList(domainType),
null != presenterList(domainType),
[Link]("Must register default choice for {0} first", domainType));
presenterList(domainType).Insert(0, new PresentationChoice(domainType, presentation, condition));
}

I can then register the classes like this.

[Link](typeof(ClassicalRecording), typeof(FrmClassicalRecording));
[Link](typeof(PopularRecording), typeof (FrmPopularRecording));
[Link](
typeof(ClassicalRecording),
typeof(FrmMozartRecording),
new [Link](MozartCondition));


© Martin Fowler | Privacy Policy | Disclosures

Separated Presentation
Ensure that any code that manipulates presentation only manipulates presentation,
pushing all domain and data source logic into clearly separated areas of the program.

Martin Fowler

29 June 2006

This is part of the Further Enterprise Application Architecture


development writing that I was doing in the mid 2000’s. Sadly too
many other things have claimed my attention since, so I haven’t had
time to work on them further, nor do I see much time in the
foreseeable future. As such this material is very much in draft form
and I won’t be doing any corrections or updates until I’m able to find
time to work on it again.

How it Works
This pattern is a form of layering, where we keep presentation code and domain code in
separate layers with the domain code unaware of presentation code. This style came
into vogue with Model-View-Controller architecture and is widely used.

To use it you begin by looking at all the data and behavior in a system and looking to
see if that code is involved with the presentation. Presentation code would manipulate
GUI widgets and structures in a rich client application, HTTP headers and HTML in a
web application, or command line arguments and print statements in a command line
application. We then divide the application into two logical modules with all the
presentation code in one module and the rest in another module.

Further layering is often used to separate data source code from domain (business
logic), and to separate the the domain using a Service Layer. For the purposes of
Separated Presentation we can ignore these further layers, just referring to all of this as
'the domain layer'. Just bear in mind that further layering of the domain layer is likely.

The layers are a logical and not a physical construct. Certainly you may find a physical
separation into different tiers but this is not required (and a bad idea if not necessary).
You also may see a separation into different physical packaging units (eg Java jars or
.NET assemblies), but again this isn't required. Certainly it is good to use any logical
packaging mechanisms (Java packages, .NET namespaces) to separate the layers.

As well as a separation, there is also a strict visibility rule. The presentation is able to
call the domain but not vice-versa. This can be checked as part of a build with
dependency checking tools. The point here is that the domain should be utterly unaware
of what presentations may be used with it. This both helps keep the concers separate
and also supports using multiple presentations with the same domain code.

Although the domain cannot call the presentation it's often necessary for the domain to
notify the presentation if any changes occur. Observer is the usual solution to this
problem. The domain fires an event which is observed the by presentation, the
presentation then re-reads data from the domain as needed.

A good mental test to use to check you are using Separated Presentation is to imagine
a completely different user interface. If you are writing a GUI imagine writing a
command line interface for the same application. Ask yourself if anything would be
duplicated between the GUI and command line presentation code - if it is then it's a
good candidate for moving to the domain.

When to Use It

Example: Moving Domain Logic out of a Window


(Java)
Most of examples you'll see from me follow Separated Presentation, simply because I
find it such a fundamental design technique. Here's an example of how you can refactor
a simple design that doesn't use Separated Presentation in order to use it.

The example comes from the running example of Ice Cream Atmospheric Monitor. The
main task I use to illustrate this is calculating the variance between target and actual
and coloring the field to indicate the amount of this variance. You can imagine this done
in the assessment window object like this:

class AssessmentWindow...
private JFormattedTextField dateField, actualField, targetField,
varianceField;
Reading currentReading;

private void updateVarianceField() {


if (null == [Link]()) {
[Link](null);
[Link]([Link]);
}
else {
long variance = [Link]() - [Link]();
[Link](variance);
long varianceRatio = [Link](100.0 * variance / [Link]());
if (varianceRatio < -10) [Link]([Link]);
else if (varianceRatio > 5) [Link]([Link]);
else [Link]([Link]);
}
}
As you can see this routine mixes the domain problem of calculating the variance with
the behavior of updating the the variance text field. The Reading object, that holds the
actual and target data, is here a data class - an anemic collection of fields and
accessors. Since this is the object that has the data, it should be the one to calculate
the variance.

To start this I can use Replace Temp with Query on the variance calculation itself, to
yield this.

class AssessmentWindow...
private void updateVarianceField() {
if (null == [Link]()) {
[Link](null);
[Link]([Link]);
}
else {
[Link](getVariance());
long varianceRatio = [Link](100.0 * getVariance() / [Link]());
if (varianceRatio < -10) [Link]([Link]);
else if (varianceRatio > 5) [Link]([Link]);
else [Link]([Link]);
}
}
private long getVariance() {
return [Link]() - [Link]();
}

With the calculation now in its own method, I can safely move it to the Reading object.

class AssessmentWindow...
private void updateVarianceField() {
if (null == [Link]()) {
[Link](null);
[Link]([Link]);
}
else {
[Link]([Link]());
long varianceRatio = [Link](100.0 * [Link]() / [Link]
if (varianceRatio < -10) [Link]([Link]);
else if (varianceRatio > 5) [Link]([Link]);
else [Link]([Link]);
}
}
class Reading...
public long getVariance() {
return getActual() - getTarget();
}

I can do the same thing with the varianceRatio, I'll just show the final result but again I
do it to steps (creating the local method then moving it) as I'm less likely to mess it up
that way - particularly with the refactoring editor (IntelliJ Idea) I'm using.

class AssessmentWindow...
class AssessmentWindow...
private void updateVarianceField() {
if (null == [Link]()) {
[Link](null);
[Link]([Link]);
}
else {
[Link]([Link]());
if ([Link]() < -10) [Link]([Link]);
else if ([Link]() > 5) [Link]([Link]);
else [Link]([Link]);
}
}

class Reading...
public long getVarianceRatio() {
return [Link](100.0 * getVariance() / getTarget());
}

The calculations are looking better, but I'm still not too happy. The logic about when the
color should be one color or another is domain logic, even though the choice of color
(and the fact that text color is the presentation mechanism) is presentation logic. What I
need to do is split the out the determination of which category of variance we have (and
the logic for assigning these categories) from the coloring.

There's no formalized refactoring here, but what I need is a method like this on
Reading.

class Reading...
public enum VarianceCategory {LOW, NORMAL, HIGH}

public VarianceCategory getVarianceCategory() {


if (getVarianceRatio() < -10) return [Link];
else if (getVarianceRatio() > 5) return [Link];
else return [Link];
}

class AssessmentWindow...
private void updateVarianceField() {
if (null == [Link]()) {
[Link](null);
[Link]([Link]);
}
else {
[Link]([Link]());
if ([Link]() == [Link]) [Link]
else if ([Link]() == [Link]) varianceField
else [Link]([Link]);
}
}

That's better, I now have the domain decisions in the domain object. But things are a bit
messy, the presentation shouldn't have to know that the variance is null if the actual
reading is null. That kind of dependency should be encapsulated in the Reading class.
class Reading...
public Long getVariance() {
if (null == getActual()) return null;
return getActual() - getTarget();
}

class AssessmentWindow...
private void updateVarianceField() {
[Link]([Link]());
if (null == [Link]()) {
[Link]([Link]);
}
else {
if ([Link]() == [Link]) [Link]
else if ([Link]() == [Link]) varianceField
else [Link]([Link]);
}
}

I can further encapsultate this by adding a null variance category, which also allows me
to use a switch that I find easier to read.

class Reading...
public enum VarianceCategory {
LOW, NORMAL, HIGH, NULL}

public VarianceCategory getVarianceCategory() {


if (null == getVariance()) return [Link];
if (getVarianceRatio() < -10) return [Link];
else if (getVarianceRatio() > 5) return [Link];
else return [Link];
}

class AssessmentWindow...
private void updateVarianceField() {
[Link]([Link]());
switch ([Link]()) {
case LOW:
[Link]([Link]);
break;
case HIGH:
[Link]([Link]);
break;
case NULL:
[Link]([Link]);
break;
case NORMAL:
[Link]([Link]);
break;
default:
throw new IllegalArgumentException("Unknown variance category");
}
}
As a last step, although not connected to Separated Presentation, I prefer to clean that
switch up to remove the duplication.

class AssessmentWindow...
private void updateVarianceField() {
[Link]([Link]());
[Link](varianceColor());
}

private Color varianceColor() {


switch ([Link]()) {
case LOW:
return [Link];
case HIGH:
return [Link];
case NULL:
return [Link];
case NORMAL:
return [Link];
default:
throw new IllegalArgumentException("Unknown variance category");
}
}

This makes it obvious that what we have here is a simple table lookup. I could replace
this by populating and indexing out of a hash. In some languages I might do that, but I
find the switch here to be nice and readable in Java.


© Martin Fowler | Privacy Policy | Disclosures

You might also like