Showing posts with label Patterns. Show all posts
Showing posts with label Patterns. Show all posts

Thursday, April 17, 2008

WCF: Design of Client Domain Objects

The client Domain Objects [Evans] (aka business entity - BE) must be related to the data contracts provided by the web-services. Still, they will need to be enhanced with e.g. dirty-tracking, validation, state, property conversions (xs:date), business rules, and other aspects needed to produce a fully working client application. This article describes how to achieve this when sharing domain objects across layers is not an option (i.e. interop with JEE services), and the same applies to AOP.

There are two models for this: annotating the BEs with XML serialization attributes to decorate the WSDL data contract, or creating separate Mapper classes [Fowler] in addition to the BE classes. The mapper will then map to and from the service proxy DTO objects [Fowler] at run-time. Note that the mapper model will be required whenever the BE is significantly different from the data contracts. Thus, BEs should be implemented using the first model to the maximum extent possible, only using the second model for advanced mapping requirements.

The decorator option is easier, performs better, and gives less code to maintain - but requires knowledge of XML serialization and will not give compilation errors when the data contract changes (even if the proxy is updated). Good integration test coverage is needed to make this option viable, i.e. to detect that the DTO's XML payload has changed.

Easier, less code: Only one BE class to implement and maintain as the BE is a Decorator object [GoF] wrapping the "DTO" XML. Note that there is no auto-generation of these classes and that there are no mappers or DTO objects. The BE classes are shared directly by the service proxies.
Performs better: There will only be one de-serialization step directly into the BE because it wraps the XML directly. This also applies to any nested child objects and collections - there will be no looping code to create and map the BE structure. The same applies to sending BE objects to the services - they will be directly serialized into "DTO" XML.
Contract change risks: As the BE classes are not auto-generated from the data contracts, changes to the contracts will not be automatically reflected in the serialization attributes on the BE properties. As (de)serialization happens at run-time, any mismatch between the XML and the serialization attributes cannot be detected by the compiler. Thus, adequate integration tests are required to detect that BE properties are not being set/read during (de)serialization. Breaking data contract changes will require that the serialization attributes are updated accordingly.

The mapper option is also quite easy, but performs worse and requires more code to be implemented and maintained (two classes: BE and mapper). However, it requires no knowledge of XML serialization and it will give compilation errors when the proxy + DTO objects are updated after data contract changes. Note that good unit testing is required to ensure that the mappings to and from the DTO objects are correct, including the complete object graph (nested child objects and collections).

Quite easy, more code: Two classes to implement and maintain, one BE class and one related mapper class. The mapper class must cover nested child objects and collections, both to and from the DTO objects. The DTO objects are auto-generated and will never be manually maintained by developers.
Performs worse: In addition to the de-serialization step of the DTO objects, the service agent must execute the mapping code to fill the BE object with data from the DTO object. Add to this extra transformation looping through nested child objects and collections, and the performance gets proportionally worse with the complexity of the object graph.
Contract change risks: The DTO objects are auto-generated based on the WSDL and are thus always in synch with the data contracts. Any breaking changes to the DTO classes will cause the mapper classes to give compilation errors. Breaking data contract changes will require that the mapper classes are updated accordingly - both to and from the DTO classes.

To complement this BE design approach, read the programming models for the Decorator option and the Mapper option to learn about the technical details and issues of each option.

Wednesday, April 16, 2008

WCF: Client Domain Objects, Decorator Pattern

The client domain objects (aka business entity - BE) must be related to the data contracts provided by the web-services. Still, they will need to be enhanced with e.g. dirty-tracking, validation, state, property conversions (xs:date), business rules, and other aspects needed to produce a fully working client application. This article describes how to achieve this when sharing domain objects across layers is not an option (i.e. interop with JEE services), and the same applies to AOP.

One option for implementing the BE objects, described in this article, is to apply the Decorator pattern to the WSDL scema-based DTO objects to enhance them into full-fledged domain objects. Read ‘
Design of Client Domain Objects’ for an intro this option and the related Mapper option.

If you do not like this Decorator option due to the weak [XML attribute] link to the data contracts (see end of article), you can always use a derived decorator class instead of a partial class. Make all your BE enhancements in the derived class using a combination of DTO overrides and new domain logic. If you prefer explicit, debuggable code, you're better off using the Mapper option.

Service Proxy

Use the SVCUTIL.EXE /REFERENCE switch when generating the proxy code and messages to reuse your BE objects as DTOs and to avoid getting new, duplicate DTO objects generated (might not compile due to name clashes). Alternatively, just remove the DTO code from the generated proxy. Make sure that the proxy code reference the .NET namespace and interface assembly that contains your BE objects.

Business Entities

You can use the data contract DTO objects generated by SVCTIL.EXE /DCONLY to get started. This will give you data-binding enabled (/EDB) anemic entity objects with all the properties in place, annotated with XML serialization attributes. Just ensure that the output files from SVCUTIL.EXE do not overwrite your code. The DTO objects become your generated BE objects - ready for decoration.

The BE objects must be manually maintained whenever you make changes to the generated BE code, e.g. to add EntLib3 validation attributes on the properties. Keep your additions to the generated BE in a partial class as far as possible, e.g. add new properties and methods in a partial class extending the decorated class. If all your decorator code can be isolated into a partial class, then the generated BE code can be re-generated without losing your extended BE code.

Our programming model for decorator-based client domain objects is based on using two partial classes; one T.schema.cs class file for all code based originally on the data contracts, and one T.cs class file for all added aspects. T is the type name of the BE.

Note that BE constructors will not be called during deserialization. Create a method to be used as a surrogate constructor to be run after deserialization and mark it with [OnDeserialized]. This is a good place for resetting e.g. the dirty flag:

[OnDeserialized]
void DeserializationCtor(StreamingContext context)
{
_isDirty = false;
}

Your BE class must still have a constructor to initialize the object for normal use. The constructor must initialize all properties that must have a defined initial value. In addition, the c'tor must initialize all child objects that are exposed as (de-normalized) public properties, to avoid null reference exceptions when using the BE (make it simple to use the BE). This also applies to child collections; create the collection to make it ready for use.

public NominationType()
{
//NOTE: WILL NOT BE CALLED ON DE-SERIALIZATION
//initialize all normalized valueobjects with members
this.NominatedValueField = new UnitValueType();
this.NominatedValueField.Unit = String.Empty;
}

Also initialize all fields that are required by the XSD schema, failure to initialize these fields will give serialization errors:
[DataMemberAttribute(IsRequired=true, . . .) ]

Don't break the DRY principle by adding the value object initialization code multiple places.

Dirty Tracking

If your BE implements INotifyPropertyChanged to enable data-binding, then the event is a good place to add dirty-tracking: Simple Dirty Tracking in Domain Objects

Converting XML Data Types to/from Strongly Typed Properties

Note that xs:date becomes string in .NET as there is no Date only type, just DateTime. Do not let this kind of weak type design leak into your BE objects. Contain the weak typing inside your BE object by converting to/from strongly typed properties.

private string _demandDateData; //XML xs:date datatype

public DateTime DemandDate
{
get
{
return DateTime.ParseExact(this._demandDateData, WSDateFormat, null);
}
set
{
string xsDate = value.ToString(WSDateFormat);
if (this._demandDateData.Equals(xsDate) != true)
{
this._demandDateData = xsDate;
this.RaisePropertyChanged("DemandDate");
}
}
}

This keeps your BE object within the "Simple vs Easy" principle.

De-normalization of BE Value Objects

The data contracts provided by the web-services will most likely contain some DDD value objects for numeric types annotated with some related attributes (e.g. money with currency) and other similar cases. These value objects will become child objects of the BE object, which is not very data-binding friendly as most controls (grids, etc) needs the data to be non-nested properties of the bound object. In addition, one control can only have one binding source. Thus, unlike master-details type binding that can be resolved using multiple binding sources, nested value objects must be de-normalized and projected as normal properties directly on the BE objects.

Start by making the value object private and give the property a new name (e.g. suffix with Data) while specifying the original name in the serialization attribute to keep the link to the XML. Keep the RaisePropertyChanged parameter equal to the property name.

[DataMemberAttribute(Name = "NominatedValue", IsRequired = true, EmitDefaultValue = false, Order = 2)]
private UnitValueType NominatedValueData
{
get { return this.NominatedValueField; }
set { . . . }
}

Then create the de-normalized public properties (in a partial class) as required by the BE and data-binding needs. The new public properties should be wrappers exposing an element of the original private member value object, using a friendly name and the correct data type. Make sure that the new-old value comparison is correct. Keep the RaisePropertyChanged parameter equal to the new property name.

public Decimal NominatedValue
{
get { return this.NominatedValueField.Value; }
set
{
if (this.NominatedValueField.Value.Equals(value) != true)
{
this.NominatedValueField.Value = value;
this.RaisePropertyChanged("NominatedValue");
}
}
}

public string NominatedValueUnit
{
get { return this.NominatedValueField.Unit; }
set { . . . this.RaisePropertyChanged("NominatedValueUnit"); }
}

As can be seen from the example, the new public properties are named by concatenating the value object name and the exposed property name; except for when the property name is just repeating the last part of the value object (i.e. NominatedValue.Value).

Remember to initialize all the value object children in the BE c'tor; both create the child objects and set their initial values.

Keeping the BE Synchronized with the Data-Contract Schema

It is imperative that the XML serialization attributes in code are correct according to the data contract XSD when using the decorator approach on proxy DTO objects to implement BE objects. There are three typical changes that can break the mapping between the BE code and the payload XML:

  • Changes to the code by renaming properties without updating the XML serialization attributes accordingly
  • Changes to the data contract XSD schema without adding properties with correct XML serialization attributes
  • Changes to the data contract XSD schema without updating the XML serialization attributes accordingly
The first issue can happen when e.g. re-exposing a property by renaming and hiding the original property (such as for de-normalizing a value object). This will require updating the XML serialization attribute to keep the mapping of the code to XSD correct:

[DataMemberAttribute(Name = "NominatedValue", . . .) ]
private UnitValueType NominatedValueData

The next two issues are caused by adding new items to the data contract or changing some existing items. The latter is not recommended and is definitively not a recommended practice for published contracts:

  • It is a proven practice that published contracts are not changed, except for non-breaking changes in minor versions.
  • For new, non-breaking versions of the contract, items must only be added at the end of the existing contract.
When a new minor version of a published data contract must be incorporated into your BE class, then start by adding the properties to hold the new data items, then add the applicable XML serialization attributes with the correct sequence order value:

[DataMemberAttribute(. . . , Order=<order number in XML xs:sequence element for item>) ]

For new major versions of data contracts, you must consider creating a new version of the BE class in a new .NET namespace. This allows you to do controlled versioning of your domain objects in synchronization with the versioning policy of the service contracts.

However, during the development of the web-services, the contracts are bound to get breaking changes as the data contracts evolve (which is OK as they are still not published). For this reason, wait as long as you can to make changes to the generated BE code, stick to working on the partial class used to decorate the BE. This will allow you to re-generate the schema-bound parts of your BE to keep up with the changes in the data contracts.


A side note: deriving your BE objects from the DTO objects is an alternative to partial classes that strictly enforces the separation of decorator code from generated code, and allows the generated code to be auto-generated over and over again - like for the Mapper option. Alas, there are drawbacks to inheriting the DTOs also, as none of the generated proxy artifacts are geared towards this. Look into using an AOP framework to do dynamic subclassing if chosing to derive your BE objects.

For data contracts under development, any combination of adding, changing, removing and reordering of data contract items can be expected to occur. The XML serialization attributes must then be updated accordingly.

Tuesday, April 15, 2008

WCF+SCSF: Client Domain Objects, Mapper Pattern

The client domain objects (aka business entity - BE) must be related to the data contracts provided by the web-services. Still, they will need to be enhanced with e.g. dirty-tracking, validation, state, property conversions (xs:date), business rules, and other aspects needed to produce a fully working client application. This article describes how to achieve this when sharing domain objects across layers is not an option (i.e. interop with JEE services), and the same applies to AOP.

One option for implementing the BE objects, described in this article, is to apply the Mapper pattern to the WSDL scema-based DTO objects to transform them into domain objects. Read ‘Design of Client Domain Objects’ for an intro this option and the related Decorator option.

Service Proxy

The mapper option has no special requirements for the service proxy or its message and data contracts, as there are no shared objects between the proxy and the business entities, i.e. the proxy is totally self-contained. The mapper objects do all transformation to/from the DTO objects and the BE objects.

CAB EntityTranslatorService, CAB EntityMapperTranslator

The EntityTranslatorService class is a service that provides a registry of translators and translation services between two classes. The user must implement the translators and register them with the service.

For more information see: ms-help://MS.VSCC.v80/MS.VSIPCC.v80/ms.practices.scsf.2007may/SCSF/html/03-01-090-How_to_Translate_Between_Business_Entities_and_Service_Entities.htm

The EntityMapperTranslator class is a base helper implementation of an IEntityTranslator that provides placeholders to translate from business entities to service and viceversa.


For more information see: ms-help://MS.VSCC.v80/MS.VSIPCC.v80/ms.practices.scsf.2007may/SCSF/html/03-01-090-How_to_Translate_Between_Business_Entities_and_Service_Entities.htm

Mappers and the Translator Service

A mapper must be derived from the CAB class EntityMapperTranslator<BE, DTO> and implement two methods:

DTO = BusinessToService(BE)
BE = ServiceToBusiness(DTO)

A mapper must traverse the complete object graph to translate all child collections and objects when the mapped object is a DDD "aggregate root".

Always add a mapper for collections of the mapped DTO and BE objects. A list mapper must iterate the collection and use the applicable object translator to map each item in the list.

Each module must register its own mappers with the CAB translator service from the CAB module AddServices:

public override void AddServices()
{
AddEntityTranslators();
_workItem.RootWorkItem.Services.AddNew<MyService, IMyService>();

}

private void AddEntityTranslators()

{
IEntityTranslatorService translator = _workItem.RootWorkItem.Services.Get<IEntityTranslatorService>();

translator.RegisterEntityTranslator(new MyTranslator());
translator.RegisterEntityTranslator(new MyListTranslator());

. . .
}

The mappers are used by the service agents to map DTO objects to BE objects and vice verca. Each CAB service that depends on a service agent must have a [ServiceDependency] on IEntityTranslatorService:

[InjectionConstructor]
public MyService([ServiceDependency]IEntityTranslatorService translator)
{
_translator = translator;
_myServiceAgent = new MyServiceAgent(_translator);
}

MyService is a CAB service and will thus get the EntityTranslatorService injected by the DI-container. It then creates the required service agents using the translator service reference. MyServiceAgent is not a CAB service, thus it is not subject to any DI-container dependency resolving magic.

Service Agents Perform the Mapping

The service agents use the EntityTranslatorService to map the DTO objects returned by the service proxy into BE objects:

AllocationTypeList allocationTypeList;
NominationTypeList nominationTypeList = _proxy.GetNominationAndAllocation (periodType, out allocationTypeList);

nominationList = _translator.Translate <List<Nomination>>(nominationTypeList);
allocationList = _translator.Translate <List<Allocation>>(allocationTypeList);

The reverse mapping must be performed on all BE objects passed as DTO objects into the service proxies.

NEVER LET A DTO OBJECT BE USED OUTSIDE SERVICE AGENTS.

Mapping from DTO to BE

Your BE class must have a constructor to initialize the object for normal use. The constructor must initialize all properties that must have a defined initial value. In addition, the c'tor must initialize all child objects that are exposed as public properties, to avoid null reference exceptions when using the BE (make it simple to use the BE). This also applies to child collections; create the collection to make it ready for use. Don't break the DRY principle by adding the initialization code multiple places.

public Nomination()
{
//initialize all contained valueobjects with members
this.NominatedValueField = new UnitValueType();
this.NominatedValueField.Unit = String.Empty;
. . .
}

The mapper code will create a new instance of the BE class and initialize it based on values from the DTO object. This can involve the whole specter from simple value copying to complex conversion logic.

Mapping from BE to DTO

Your mapper class must initialize the created DTO object before using it. The mapper must initialize all properties that must have a defined initial value. In addition, the mapper must initialize all child objects that are exposed as (de-normalized) public properties, to avoid null reference exceptions when mapping the BE. This also applies to child collections; create the collection to make it ready for use.

//initialize all normalized valueobjects with members
dto.NominatedValueField = new UnitValueType();
dto.NominatedValueField.Unit = String.Empty;

Also initialize all DTO fields that are required by the XSD schema, failure to initialize these fields will give serialization errors:

[DataMemberAttribute(IsRequired=true, . . .)]

The mapper code will create a new instance of the DTO class and initialize it based on values from the BE object. This can involve the whole specter from simple value copying to complex conversion logic.

Converting XML Data Types to/from Strongly Typed Properties

Note that xs:date becomes string in .NET as there is no Date only type, just DateTime. DO NOT LET THIS KIND OF WEAK TYPE DESIGN LEAK INTO YOUR BE OBJECTS. Contain the weak typing in your DTO object by converting to/from strongly typed properties in the mapper.

dto.DemandDate = value.DemandDate.ToString(WSDateFormat);

entity.DemandDate = DateTime.ParseExact(value.DemandDate, WSDateFormat, null);

This keeps your BE object within the "Simple vs Easy" principle.

Dirty Tracking

If your BE implements INotifyPropertyChanged to enable data-binding, then the event is a good place to add dirty-tracking: Simple Dirty Tracking in Domain Objects.

Thursday, July 05, 2007

Composite Services: Information Model, Federated Information Models

A SOA solution is typically implemented by composition of services provided by different systems. The solution might comprise a mix of of in-house services, 3rd party and outsourced services. In addition, the solution might also involve cross-enterprise service compositions.

To be able to efficiently compose the services, a model that ensures shared sematics is needed, and in my last post I described the business process information model (BPIM). David Chappell calls this approach semantic data integration. BPIM is a similar concept to the EAI canonical data model [Hohpe/Woolf CDM pattern (355)], but it is a model with a slightly different purpose at a different architectual layer and it is not just about the data. The BPIM is about the events, messages and data passed between services, not about having a unified superset of the entities within an enterprise.


The BPIM allows for composition of services without having to know and comply with the model of the underlying service logic, all you need to know is the message types. This is a big advantage, and allows for the consumers to be isolated from the details of the consumed services. E.g. all a service consumer need to know is the "AddressChange" data of the "CustomerHasMoved" event, not the complete data schema of the "Customer" service.

BPIM is closely related to the Common Information Model (CIM) concept. Note that the BPIM message types are projected compositions of the referenced CIM resources - not just simple compositions of resource objects. In addition, the messages covers more than just activity data, they also contain queries, notifications (events) and commands. Design the BPIM based on the CIM, ensuring that the model is canonical for each process domain.

The term 'domain' is borrowed from Domain Driven Design (DDD). Domain-driven design is not a technology or a methodology. It is a way of thinking and a set of priorities, aimed at accelerating software projects that have to deal with complicated domains. Read stories about how DDD can be applied to a diverse set of architectual problems: Practitioner Experience Reports.

Focusing on the bounded context for modeling the flow, events, messages, data and semantics involved in implementing the core business processes of the domain, should make it easier to come up with a working model. Note again that the information model is about more than just the data. Hence the name business process information model. Arvindra Sehmi and Beat Schwegler used the same term in Service-Oriented Modeling for Connected Systems, an article that also provides details about creating a service model.

Partner/ 3rd party/ outsourced services are not part of the core business domain according to DDD. If they were core processes in your business, how come they are so general that they can be outsourced or bought? Core processes are those that make your business unique and give you a competitive edge. DDD dictates using translators or an "anti-corruption layer" against services/systems that are not within the domain.

Having a canonical schema model at the service layer might be feasible within an enterprise, but should be avoided as this will cause very tight coupling to the One True Schema. Making every service depend on the One True Schema will make it impossible for the services to evolve separately, they will no longer be autonomous. If agility at the service layer is less important for you, then such a service straight-jacket might initially feel good. Trying to make a enterprise data model (EDM) is not a good idea for the same reasons. Steve Jones has a good post about canonical form issues and how you cannot enforce your model upon the world: Single Canonical Form - not for SOA

Federated Business Process Information Models

DDD recommends splitting big, diverse and complex solutions into several bounded contexts. Set explicit boundaries based on e.g. orgranizational units and application usage. A natural boundary in SOA is partner/ 3rd party/ outsourced services. Each set of services that is not under your control and that you cannot enforce your information model upon, is a separate bounded context (domain model).

Note that also within your enterprise service model there will be several other bounded contexts for different domains, each with its own information model that is canonical per domain
.

You should identify each model in play on the project and make a context map.
A context map describes the points of contact between the domain models, in addition to outlining explicit translation for any communication between the models.

This figure show how a context map is used to show how two domains relate to each other:
The figure and the definitions of "bounded context" and "context map" is taken from the 'Strategic Design' chapter of the book "DOMAIN-DRIVEN DESIGN" by Eric Evans [Addison-Wesley, 2004].

Note how not all elements of a domain model needs to be mapped to other models. Only the interconnected parts needs to have a translation map. E.g. the credit check process is provided by a 3rd party, thus it exists in a separate external information model. Your BPIM needs to have a translation map to the other service to be able to invoke it. Note how similar this is to the purpose of the BPIM itself: translating between business process compositions and the underlying, composed services. Thus, the context map is the basis for modelling a set of Federated Business Process Information Models. A federated BPIM system map shows the integration of multiple enterprise service models, avoiding the pitfall of designing a single canonical data model across a set of different domains.

Friday, June 01, 2007

Enum Flags, Specification Pattern & Explicit Semantics

We use the specification pattern for all the dynamic query operations in our WCF service, and this includes using Nullable<T> on all criteria elements and several "multiple choice" criteria based on [Flags] enumerations. To ensure that our contracts convey explicit semantics, we have used long meaningful names in the enumerations instead of the more cryptic codes that are wellknown in the internal system and that are the domain terms used by the biz-people. These internal codes is not, however, very meaningful to the partners that are consuming the WCF service.

As the multi-choice lists sometimes contain 20+ items, I feared that interpreting the [Flags] enum
and building the repository query would become huge switch statements with lots of ugly bit-wise "and" logic to deduce which of the 20+ items were specified in the criteria. In addition, I needed a way to add the translated code items to a SQL @parameter list as part of a SQL in clause to actually filter records on the criteria.

As I never embark on implementing something ugly, I decided to look for a simpler way of interpreting the [Flags] enum. Knowing that an enum internally is represented by the integers and not the human-friendly names, I decided to add another internal enum that exactly mirrors the contract enum, just using the internal domain codes, and then cast to the internal enum. But the DataContractSerializer has a simpler approach using the [EnumMember] attribute:

[DataContract]
[Flags]

public enum DisciplineFlags
{
None = 0,
. . .
[EnumMember(Value = "
Instrumentation ")]
I = 0x000100,
[EnumMember(Value = "
MarineOperations")]
J = 0x000200,
[EnumMember(Value = "
Materials")]
M = 0x000400,
[EnumMember(Value = "
Navigation")]
N = 0x000800,
//
[EnumMember(Value = "
Process")]
P = 0x001000,
[EnumMember(Value = "
QualityManagement")]
Q = 0x002000,
[EnumMember(Value = "
Piping")]
S = 0x004000,
[EnumMember(Value = "
Telecommunications")]
T = 0x008000,
. . .
}

Note that you must apply the [DataContract] attribute to the enum for the [EnumMember] to take effect. If you just use the plain enum as a [DataMember] property, then the internal names will be published in the contract.

The "None" item is there as the default value for the DataContractSerializer when the incoming XML specification contains no flags filter element (xsi:nil="true"). The nullable flags filter must be asserted like this before usage:

if (filter.DisciplineFlags.HasValue
&& filter.DisciplineFlags != DisciplineFlags.None)

{
. . .
}


So now I had the real one-letter domain codes, but how to avoid bit-wise interpretation ? Also, I needed a list of the codes making up the flags combination. The answer is really simple:

string disciplineList = filter.DisciplineFlags.ToString();
string[] inValues = disciplineList.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);

The last problem is that you cannot add the list of values for an in-clause as a @parameter. Just concatenating the CSV-string into the SQL is not an option due to SQL-injection attacks. So a for-loop is needed to add SQL parameters and related values:

for (int i = 0; i < inValues.Length; i++ )
{
string param = "@in" + i;
if (i > 0) sql += ", ";
sql += param;
filterCommand.Parameters.AddWithValue(param, inValues[i].Trim());
}

I would rather have avoided the for-loop, but at least the specification interpreter became much simpler than I expected it to be. No pesky switch statements and bit-wise logic.

See the end of this earlier post for further details about implementing specification filters using TableAdapters.

Tuesday, October 17, 2006

Enter Supervising Presenter, exit MVP

This june I wrote about how we used model reference data and the Model-View-Presenter pattern in a WinForms container control with pluggable views. What I did not say was that we did not implement pure MVP, but rather a modified version that fitted better with WinForms data binding and object data sources.

Just about the same time in june, Martin Fowler retired the MVP pattern for just about the same reasons, and the new data binding friendly pattern is the Supervising Controller. The MVP pattern has actually been split in two, the other pattern being the Passive View.

So if you're still using MVP, be sure to catch up on the new patterns.

Monday, September 11, 2006

Intention Revealing Interfaces, Bad Naming and Maintenance

As an architect I am trying to guide the other programmers on my current project that the design of our components is very important for the reusability of our solution. There are some bad naming of methods and properties that makes me think of the famous "How to write unmaintainable code" article, and to make things worse, this especially applies to some core common objects (which are of course reused from another project group :).

The naming focus is on intention revealing interfaces, but still new methods/properties/class members with creative misspelling, abstract names such as PerformDataFunction, abbreviations such as IntAccount (integer, internal, international ?) , pops up in the design now and then.

What triggered me to write this post is misleading name reuse. One of the domain objects is the AccountNumber and the account number does either belong to the bank or it does not. In addition, an account belong to the bank can be an internal account for e.g. book-keeping, currency exchange, etc. Looking through the .IsXxx properties of the object I found .IsInternal, but no property to tell me if the account belongs to the bank or not. As the object did not reveal its intention to me, I had to find and ask the developer. And surprise, surprise; the domain term 'is internal' had been used as the 'own bank' indicator as it "seemed natural at the time".

"So why did you not change it when you discovered the misleading term?" I asked, knowing the answer: "I am afraid that it will break the other project. Also, it might be a lot of work to make it build after the refactoring". I know that the "other project" has low unit tests coverage and a complicated build configuration, but none of the solutions using the common component is in production yet.

This leads me to the difference between public and published, i.e. it is the published parts of your object model/API you cannot change (it is the contract of your service). The public parts is subject to change without notice. As none of the components are published yet, we decided to refactor the design of the object model to comply with best practices, now rather than later.

The main goal of the refactoring of our components is to comply with some of the central design goals of our components: "power of sameness" and "tools for communication (revealing intention)". As it is now, coding against the common core components is like being an archeologist; piecing together fragments left behind by long gone developers.

Being complex is easy, being simple is hard - Brad Abrams

Friday, August 04, 2006

BBoM: Golden Hammer, Hammer-Nail Metaphor

The Golden Hammer and "When you have a big enough hammer, everything starts to look like a nail" are two metaphors that are related to the Big Ball of Mud pattern. A central part of BBoM is that developers (coders) stick to the tools and technologies that they know, independent of the actual problem at hand.

This kind of thinking is more common than you might believe. A while ago, I did some work assisting on an integration project that exported data from a RDBMS to an FTP server. As this was a typical ETL process, I recommended using DTS on one of the client's existing SQL Server 2000 servers. DTS is perfect for fetching data, transforming and writing it to files, and then transferring them using FTP.

One of the developers, however, was not familiar with DTS; but he knew how to write Windows services in VB6. And so he implemented his part of the ETL as a service - running on his PC (on his own, doing his "thing"). In addition, there is no 'deployment & configuration' documentation (also very typical for BBoM solutions). The 'truck factor' for his solution is one, and now he is gone/unavailable for six months; and there is a huge note on his PC: "DO NOT LOG OFF OR TURN OFF THIS COMPUTER. PRODUCTION CODE IS RUNNING HERE". Say no more . . .

Another of my favorite phrases is "Assumption is the mother of all fuck-ups" (from the Steven Seagal movie Dark Territory). I apply it anytime a programmer coder tells me that something need not be tested/checked/verified.

Wednesday, June 14, 2006

Model Reference Data = Observer pattern + Reference Data + MVP (Part II)

In part I, I outlined how we use common business process reference data (BPRD) in our WinForms user controls contained in a model-view-presenter application. Before the refactoring, the presenter was used to hold and provide the data, and also had the responsibility of notifying the applicable views that the reference data had changed. This lead to a rather unreadable and unmaintainable design as the set of events and views got bigger

All who have developed a tabbed wizard control know that using a common data object shared between all the tabs is a good design. The refactored design is analogous to this, in addition to employing the Observer pattern. The WinForm user control container module described in Part I is just an advanced, decoupled MVP implementation of a multi-tabbed user interface module.

The refactoring of the module comprises these steps:
1. Extract all common reference data into a new ‘subject’ class as private members.
2. Expose the reference data as public properties.
3. Add event definitions to the applicable properties to notify ‘observers’ of changes to the ‘subject’.
4. Add a property to the presenter to hold an instance of the new BPRD object type.
5. Add a property to the view interface, of the new BPRD object type.
6. Add code in the presenter to create an instance of the reference data (BPRD).
7. Add code in the presenter to set the BPRD property of each of the views.
8. Add event handlers in the presenter and views (observers) to subscribe to applicable notifications from the new BPRD object.

In the new design, all views hold a reference (pointer) to a common, shared instance of the BPRD object. They all change the common object and they all can subscribe to whatever event they need to get notified of. Thus, the presenter need not contain any code to handle BPRD events to then invoke methods on the views. This leads to a much simpler presenter. The views are also somewhat simpler, as the view interface now contains less to implement.

The refactored view interface looks like this:

public
interface IEkspederingView

{

//note how all the get/set events from part I are gone

//property pointing to the current common, shared BPRD

EkspederingFellesData GjeldendeEkspederingFellesData{get; set;}

...

}


The new business process reference data class looks like this:

public class EkspederingFellesData

{

public EventHandler<EventArgs> KontonummerSatt;


public string Kontonummer

{

get { return _kontonummer; }

set

{

_kontonummer = value;

//subject: notify subscribers of change

if (KontonummerSatt != null) this.KontonummerSatt(this, new EventArgs());

}

}

private string _kontonummer;

...

}


The presenter looks like this:

public class EkspederingPresenter

{

public EkspederingPresenter()

{

//create and load the BPRD

_currentReferenceData = new EkspederingFellesData();


//add the current BPRD to all the views

_innbetalingView = new InnbetalingView();

_innbetalingView.GjeldendeEkspederingFellesData = _currentReferenceData;

}


public EkspederingFellesData GjeldendeEkspederingFellesData

{

get { return _currentReferenceData; }

}

private EkspederingFellesData _currentReferenceData;


private InnbetalingView _innbetalingView;

...

}


And finally, one of the views looks like this:

public class InnbetalingView : IEkspederingView

{

public InnbetalingView()

{

//observer: add event handlers to subscribe to notifications to BPRD

this.GjeldendeEkspederingFellesData.KontonummerSatt += new EventHandler<EventArgs>(OnKontonummerSatt);

}


public EkspederingFellesData GjeldendeEkspederingFellesData

{

get { ... }

set{...}

}


public void OnKontonummerSatt(object sender, EventArgs e)

{

//do function X13

}

...

}


The reference data value object is the ‘Subject’ of the Observer pattern, while the ‘Observer’ objects are the presenter and (possibly) the views. Thus, the reference data ‘Subject’ object (don’t get confused) is in fact a ‘Model’ object, although not a domain object such as a customer or an order.

If this combination of the observer pattern, the MVP pattern and a reference data object should have a name, I would call it the “Model Reference Data” pattern, the subject/model being the common, shared and observed reference data.

[UPDATE] Martin Fowler has since retired MVP and replaced it with the Supervising Presenter pattern. The new pattern is actually very like our adapted MVP usage, as it fits better with WinForms data binding.

Friday, June 09, 2006

Tell, don’t ask – MVP – Biz Process Reference Data (Part I)

A good programming practice is “tell, don’t ask”, which concerns class responsibility (btw, don’t try to apply this practice at home with your wife…). In these postings, I will outline how we use this rule to avoid excessive use of events in a model-view-presenter (MVP) WinForms module to get at the reference data of the current business process.

Reference data
is used in the model to annotate the business transaction work item data with extra information such as the customer number, account number, zip code, country, etc.

I have successfully used “tell, don’t ask” to refactor code that used events to get business process reference data (BPRD) values stored in a WinForms presenter control, to use a common, shared ‘current reference data’ object to contain and control the reference data. This also leads to a better design that follows the “single responsibility principle”
and leads to better cohesion / separation of concerns in the presenter and the current-reference-data classes.

The WinForms module consists of a container user control that hosts a set of child user controls inside a tab control. In fact, one of the child controls is it self a tabbed container with further child controls. Before the refactoring, the reference data was stored in the presenter, much like the view-state data of the presentation-model
. Note that we use an adapted version of MVP due to our extensive use of WinForms databinding. Note also that we by constraint cannot use CAB in this project.

See J Aron Farr’s post at JadeTower
on ‘MVC, MVP, Presenter Model’ for more info about the different presentation logic patterns.

The old code contained several events for getting and setting the reference data defined in the view interface (one event pair per value). The child user controls (the views) would raise an event that the presenter would handle to provide the requested reference data value. Thus, a view would need ask for the data to get it and beg for the presenter to change it. After all, raising an event is not dictating (tell) something to happen, it is more like pleading (ask). This coding style started out small with just one value to get.

An example view interface (sorry about the Norwegian naming imposed on me):


Public Interface IKasseEkspedisjonView

#Region "Events"
Event KontonummerHent as EventHandler(Of GenericEventArgs(Of String))
Event KontonummerSett as EventHandler(Of GenericEventArgs(Of String))

Event BuntnummerHent as EventHandler(Of GenericEventArgs(Of Integer))
Event BuntnummerSett as EventHandler(Of GenericEventArgs(Of Integer))

Event EkspedisjonsnummerHent as EventHandler(Of GenericEventArgs(Of Integer))
Event EkspedisjonsnummerSett as EventHandler(Of GenericEventArgs(Of Integer))
#End Region

...


End Interface


The presenter would handle these events both to provide and to update the BPRD values stored in the presenter.


Note that I do not want the views to have a pointer/reference to the presenter. In addition, to keeps things simple, the container is also the presenter. The container naturally has pointers to all the views, added automatically by the Visual Studio designer when adding the child user controls to the tab control.

The events defined in the view interface had to be implemented by all child user controls using BPRD, and even using a user control base class to implement the events only once, it still would lead to a growing number of events and handlers as the number of reference data values increased. Likewise, the presenter would have to add handlers for each new event and for each new child user control added to the container.

It was time for a simpler solution to sharing the business process reference data. The refactoring involves creating a new value object to keep all the reference data and removing all of the get/set events from the view interface in favor of property changed events on the value object. The refactoring will also remove the need for the presenter to subscribe to BPRD events for each view instance.

Stay tuned for details about the refactored business-process-reference-data object in the upcoming part II.


[UPDATE] Martin Fowler has since retired MVP and replaced it with the Supervising Presenter pattern. The new pattern is actually very like our adapted MVP usage, as it fits better with WinForms data binding.

Monday, May 01, 2006

Coders vs Programmers: Big Ball of Mud

In a recent post, Scott Bellware rants about the Microsoft developer personas Mort, Elvis, and Einstein and the software development methodologies and tools Microsoft promotes through them; and also throws in a few punches at Rocky Lhotka's opinions on TDD and software development.

The post has spurred a lot of comments, one of them from a "programmer" that feels that all these efforts to define better methodologies and to build better tools to support them, is the search for the holy grail and, in fact, the real problem of the software industry:


"Some people actually have a life and the holy grail of software engineering is not it. Go home, relax, get a life. Let the rest of us go to work, do our thing and go back to living. Working a 40hr/wk job with real deadlines and with a real family life or life that has it own requirements and demands quite honestly doesn't leave much time to learn all this new methodolgy. Especially when it changes so quickly.

That my friend, is the reason why the industry is the way it is. PLAIN AND SIMPLE! Perhaps if we were all workaholics that had no other ambitions in life but to reach the holy grail of software development nirvana, then things may be the way you want. Your wishing against reality."

I have heard this kind of arguing before, it is not uncommon. In fact, it is part of a pattern called the Big Ball of Mud. I really recommend reading the whole BBoM article, it even contains a finding to support the "get-a-life/workaholic/nirvana/against reality" arguments above:

"it is inevitable that 'on average, average organizations will have average people'. One reason for the popularity and success of BIG BALL OF MUD approaches might be that this appoach doesn't require a hyperproductive virtuoso architect at every keyboard."

This leads me to my own little quest at work these days:

Coders vs Programmers.

A lot of developers are campers inside big companies, hiding in their cozy foxholes, doing their thing, blaming the everchanging tools and methodologies (and requirements) for not being able to produce anything but a BBoM. This kind of (demotivated) developer is what I call a "coder" (see also the related "code monkey - type 1").

Perhaps if they could make their code just a little better by using some methodology, they could go home knowing that their solution is built to last, and in addition, be proud of their workmanship ("Software Craftsman"). There is no conflict between having a life, working 40 hours a week, and producing quality code.

The real problem of the software industry is that there are way too many coders, and too few programmers. Programming is more than just emitting code that compiles and works; I state that coders produce BBoM even when not constrained by time or money.


I believe that the whole software quality issue revolves around being genuinely interested in software design issues, striving to be an architect rather than a "swamp guide" (from BBoM). The book "Zen and the Art of Motorcycle Maintenance" by Robert M.Pirzig contains a lot of good thoughts about quality, and "pride of workmanship" is a central theme in the book. I recommend reading ZAMM, it will give you some philosophical insight to the topics discussed in the BBoM article.

Sunday, February 05, 2006

Implementing "RowState" for Entity Objects

At my current project, we have some object model design discussions about "the how" for our entity objects (whose primary objective is "the what" of the domain), between the DataSet clan and the POCO clan. Our system is quite big, and must be designed to make it easy to provide future services to other parts of the organization (including Java-based systems) and to external partners. Support for web-services is a planned feature of the system, not to mention SOA.

Personally, I always like to design a system in a way that make the client application just another consumer of the system services. This promotes re-usability and low coupling, and is best achieved through a TDD approach. Thus, as you may guess, I am not in favor of using DataSets as the basis for entity objects, value objects, messages, or for DTOs. I recommend reading Scott Hanselman's famous blog post about using DataSets as business objects or as message elements in web-services. Also check out this MSDN Mag article, including the referenced blog posts at the end of the article.

Design-time data-binding of anything but DataSets was not simple in .NET 1.1, but with the advent of the object binding source and generics (List<T>) in .NET 2.0, it has become viable to do data-binding to entity objects and lists/collections.

The software design discussion now revolve around the RowState to signal the state of an entity object in relation to a containing list. Having a RowState property is really useful when e.g. implementing the 'Unit of Work' pattern. I have promoted that the 'cloning' and 'is dirty' mechanisms, plus a deleted flag as enough, while the DataSet clan advocates the need for a separate, setable row-state property, which will introduce some ambiguity in deducing the actual state of an entity object when received from a client.

I claim that the RowState need not be a separate, serializable property, it is just a read-only combination of the entity object identifier .Id, .IsDirty, and an .IsDeleted flag (the latter being the only setable property, the other two are read-only to the clients). Each entity object must have a class member that contains a clone of its original state. The .Id (internal, hidden entity identifier; PK) is assumed to be e.g. -1 when the object is not an existing entity in the data store. The state of an entity object is deduced like this:

  • Added: .Id == -1 && .IsDirty == true && .IsDeleted == false
  • Deleted: .IsDeleted == true && .Id != -1 (must exist to be deleted)
  • Detached: not applicable, entites are not defined by membership in any List<T>
  • Modified: .Id != -1 && .IsDirty == true && .IsDeleted == false
  • Unchanged I: .IsDirty == false && .IsDeleted == false
  • Unchanged II: .Id == -1 && .IsDeleted == true (aborted insert, no operation on this operand)
Thus, RowState is just a read-only property on the entity object. If your system requires the need for public setable row-state (like the new feature in ADO.NET 2.0), I recommend that you add an AdviceRowState property that the system clients can use to signal their intended state of the entity object.

Remember to keep any "how" properties away from the serialization of the "what" when using serialization as the basis for .IsDirty, otherwise such extra properties will cause bogus 'is dirty' logic. This includes any 'original values' clone that you may include in the entity object to support the .IsDirty method. As the 'is dirty' code uses the BinaryFormatter, use the [NonSerialized] attribute on all fields/class members that should not be comprised by the .IsDirty comparison.

You may also need to exclude some properties from XML serialization e.g. to prevent exposure in your web-services.
Apply the XML serialization control attribute XmlIgnore to such properties. You may also conditionally serialize properties such as the AdviceRowState property to XML. Add an extra control property bool AdviceRowStateSpecified and set it to false to exclude the actual property from XML serialization. Apply [XmlIgnore] to the AdviceRowStateSpecified property as you do not want it to be serialized anyway.

It should always be an internal aspect of your system how domain entities are stored, how you implement locking, how you implement long-running work/operations, etc ( see Data on the outside vs. Data on the inside by Pat Helland). The AdviceRowState property is just for giving the client the perception of having a say. The operations provided by your system should always make the client say please: "please update the account with this data", "please delete this order", etc.

The WinForms DataGridView still favors the use of DataSets as it has built-in support for DataTable.DataRow.RowState, e.g. automatically hiding deleted rows. This will not happen when using an object binding source bound to a generic list. Using two List<T> are one way of solving this, one for the deleted entities and one for the others. Use the latter as an object binding source, and the former to keep track of deleted entities. Pass both lists in the message to your service to save the changes (the lists are the 'operands' of the message).

Thus, the RAD model of Visual Studio favors developer productivity over good software design. Read 'Does Visual Studio Rot the Mind?' by Charles Petzold for more on this topic.

Thursday, February 02, 2006

VS2005 inherited user control, abstract factory/dependency injection pattern

Yesterday the need arised for inheriting a WinForms user control to implement four specializations of a user control. Creating inherited user controls is very simple in Visual Studio, just click 'Add-New item' and select 'Inherited user control', name the new user control appropiately and click 'Add'. I then selected the user control to derive from (note that the class must be plain public, while the constructor can be protected) and clicked OK.

VS2005 dutifully added the new user control files, but the VS designer failed with this error message:


One or more errors encountered while loading the designer. The errors are listed below. Some errors can be fixed by rebuilding your project, while others may require code changes.

Object reference not set to an instance of an object.

at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection)
. . .
at Microsoft.VisualStudio.Design.Serialization.CodeDom. VSCodeDomDesignerLoader.DeferredLoadHandler.Microsoft.VisualStudio. TextManager.Interop.IVsTextBufferDataEvents.OnLoadCompleted(Int32 fReload)


Some googling did provided me with only a few similar problems, but none of the suggested solutions worked for me. Even adding two new user controls with no code or children would fail when trying to inherit one from the other.

The designer always calls the user control's parameterless constructor New and the control's Load event handler (provided that they exists), thus these methods should not do any operations that depend on some run-time resources.

I was quite puzzled when even added the two new plain user controls failed, as they of course had no constructor or load event handler. Then I noted that I could no longer open any user controls or forms in the whole solution. The VS designer had gone into a zombie state. A restart of Visual Studio, plus clearing the TFS workspace cache, corrected the VS designer problem for all the forms and the non-inherited user controls. Before I even tried to add a derived user control again, I did the recommended rebuild (see error message above) to ensure that coding errors did not cause the problem.

This time I added a standard user control and manually added the Inherits statement to the class code file and the designer partial class file. Then I opened the user control in designer mode, and I still got the famous designer error page, but this time with useful error details pointing me to a specific line in the base class.

The offending line was a private class member that created a biz-logic component using the abstract factory pattern:

Public Class GenericUCBase
. . .
Private _bizManager As IBizManager = ObjectFactory.BizManager()
. . .

Protected Sub New()

' This call is required by the Windows Form Designer.
InitializeComponent()
End Sub
. . .

The factory uses a Public Shared (static) method that creates objects using the dependency injection pattern (interface based) from pre-compiled assemblies deployed to the VS project location. It was the Type.GetType(typeName as String) method that failed when called from the private member initialization. I don't know why the VS designer failed to locate my assemblies during initialization, VS has no problems with non-derived controls, or with running or debugging the project.

All class members that are "declare initialized" gets called when the designer loads a user control, along with the constructor and the load event handler. Knowing this, I moved the initialization of the biz-logic component to my InitControl method, and this solved the VS designer problem.

The TFS workspace cache is located here:

\Documents and Settings\%user%\Local Settings\Application Data\Microsoft\Team Foundation\1.0\Cache

I clear it whenever I have problems with VS or TFVC, typically when the 'pending check-ins' list contains bogus entries from other solutions that cannot be removed in any other way.