Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

Intent

Facilitate the construction or mutation of complex data elements or objects into separate forms without knowing the details of the objects being translated. Translate Abstract Packets from one representation to another.

Problem

Similar to that of the “gang of four” Builder pattern, the Packet Translator separates the construction of a complex object from its representation. However, in addition to the Builder, this also facilitates a method to translate the complex object from one type to another and back again. The point of this translation service is to provide a means upon which to place the logic necessary to receive data packets of one format and convert them into another format. This is extremely typical when implementing an Abstract Packet pattern or any general object containing data parameters that must pass into another section of code that may understand a different set of values. For example, the Abstract Packet object a designer uses to pass data into the system may be quite different than the object used to pass from business service to business service. Different layers of the system or even different tiers sometimes require different parameter “packaging” rules. The data elements necessary for parameter passing at a business tier may be completely different for what is required at the persistence or data tier.

What this pattern solves is a fixed method of translation such that the implementation of the translation is generic and separated from its representation. Like an Adapter Pattern (GoF), this pattern provides an object different in interface yet containing similar internal data. The Packet Translator not only centralizes the translation implementation of turning one packet format into another but also provides a standard set of methods to do so. The calling of a Packet Translator will typically occur in a base class hidden from any concrete client, such as a Service Façade.

Forces

Use the Packet Translator Pattern when:

  • Using an Abstract Packet in your framework.

  • The format of received data does not match that used within the framework.

  • You want to isolate complex construction logic for an Abstract Packet.

  • You want to standardize the packet-building process within a framework.

Structure

04fig11.gifFigure 4.11. Packet Translator generic class diagram.

Consequences

  1. Encapsulates complex construction details of an Abstract Packet or any complex object. Typically when working with more than one set of data parameters, the logic used to map those parameters can become complex. This is especially true when incoming parameters do not directly match that of outgoing parameters. In our example, a DataSet is the external object format that must be translated into another Abstract Packet format called Packet. The construction of the Packet class can become complex and should be delegated to another entity. Complex construction such as this should also be abstracted in the likelihood that other translations may occur using different object formats.

  2. Provides a standard means of translating two object formats into one another. Translating packets can soon become a systemwide process. If there is more than one public entry point into an existing framework, this pattern will provide a standard means by which to translate packets of any format.

  3. Centralizes the construction and binding of type-strong objects into an Abstract Packet. Although this could be considered an optional feature of the Packet Translator, creating type-strong data objects is a preferred approach when binding the data that will either reside on or be aggregated by the Abstract Packet. HydrateDataObject() in the Packet Translator can also be used from a factory to create the appropriate type-strong data object that must be bound to an Abstract Packet. Please refer to the Abstract Packet Pattern section earlier in this chapter for more information. The implementation section below will explain how our example utilizes a type-strong data object and binds it to an Abstract Packet, using the Packet Translator.

Participants

  • ConcreteFacade (CreditCardFacade)— This is simply the driver object of the pattern. This entity can be any client that directly interacts with the Packet Translator. In our example, this is a CreditCardFacade object that during construction receives an external packet and translates it into a Packet object. Actually, in the CreditCard production application, the logic for packet translation lies in the parent class of all façades, alleviating the need to duplicate this process in each ConcreteFacade implementation. This is not a requirement, however.

  • PacketTranslator (Same name as implementation)— This is the heart of the pattern. All pattern logic is implemented here. This includes translation that constructs both object formats using an overloaded method called Translate(). The ConcreteFacade simply has to call Translate() on the Packet Translator, passing in the appropriate data object. In our example, if a business service is called, passing an external data object such as a DataSet, Translate () is then called, passing the DataSet to the Translator. The Translator constructs the destination object and maps the appropriate values into the new data object. This construction and translation logic is business-specific. The goal is to simplify and abstract this logic. The client does not know or care how the construction or translation takes place or which Translate method to call. The ConcreteFacade just invokes Translate(), and the overloaded method takes care of invoking the appropriate method, based on the type passed. Keep in mind that if you are using data objects of the same data type, an overloaded Translate method will not work because the signature will be the same. For those cases, a different Translate method should be created, such as TranslateA() and TranslateB(). The remaining piece of translation is the optional use of a type-strong data object in the translator. This is not a requirement but when using an Abstract Packet that does not include typed methods, this can improve performance of your application. The first step to implementing either Translate() method is to construct the destination data object. For those cases where a type-strong version of that data object can be used, a factory method should then be implemented to perform this construction. The factory method will construct a type-strong class based on some information in the received data object. For example, when receiving a DataSet type data object, HydrateDataObject() is called from the initial Translate method. In fact, this Translate method becomes our factory (see below). Here, the correct type-strong class is instantiated, hydrated with the incoming data from the DataSet, and returned to the calling Translate() method to complete the translation. Naming this method HydrateDataObject() seemed appropriate because an XML schema with instance data was used to “hydrate” our type-strong data object once it was constructed. How the data is actually “sucked” into in the newly constructed data object is up to the developer, and again, this is optional for the pattern. For more information on type-strong data objects, please refer to Chapter 5.

  • Packet (same)— This is the destination data object. This is typically an Abstract Packet that will act as a container to all business data passed to each method in the framework. The business methods in the framework “speak” the Packet language while the external world speaks the “DataSet” language. DataSets are mentioned next.

  • DataSet (same)— This represents the external data object. This type is passed into our business framework from the outside world. A DataSet is a great choice for this data object, due to its dynamic nature, flexible representation, and the fact that many .NET tools down the line will be supporting it. This type is optional. Other types could have been chosen for the PacketTranslator pattern, and for smaller applications, a DataSet could be considered overkill. For simpler cases, an ArrayList could have been used or even a custom data object. Keep in mind, however, that choosing a custom data object brings with it unique challenges to the data-marshaling world, and it is recommended that you stick with a “standard” .NET data type. This is especially true when using SOAP as your transport protocol.

  • ProductDataSet (CreditCardDS)— This represents the type-strong data object. This inherits from the DataSet and again is optional. Type-strong data objects are discussed in Chapter 5.

Implementation

Figure 4.12 looks much more complicated than it really is. The base of the pattern lies in the encapsulation of the packet construction. All construction and translation take place in one location—PacketTranslator. Where the class model becomes more complex is when a type-strong data object is used. In our case, that type-strong data object is a child class of a DataSet called CreditCardDS, and using it (as mentioned many times in this section) will be one of the focuses of Chapter 5.

04fig12.gifFigure 4.12. Packet Translator implementation class diagram.

The code in Listing 4.9 is implemented in the client of the translator. In our example, this is the CreditCardFacade class. It simply takes an external DataSet object, instantiates the PacketTranslator class, and calls Translate. It, like the Translator, uses an overloaded method called PreparePacket to alleviate its client from having to know which method to call. The return value of each PreparePacket is the appropriately formatted data object.

Listing 4.9 Abstract Packet sample implementation—preparing packets.

public Packet PreparePacket(DataSet dsRawPacket)
{
try
    {
          SetRawPacket(dsRawPacket);
PacketTranslator oPacketTranslator = new
PacketTranslator();

SetPacket(oPacketTranslator.Translate(
GetRawPacket()));
    }
catch(Exception e)
    {
    ...
    }
    return GetPacket();
}

public DataSet PreparePacket(Packet oPacket)
{
    try
    {
          SetPacket(oPacket);
          PacketTranslator oPacketTranslator = new
    PacketTranslator();

    SetRawPacket(oPacketTranslator.Translate(
    GetPacket()));
    ...
    return GetRawPacket();
}

The code in Listing 4.10 shows the implementation of each Translate method in the PacketTranslator object, along with our HydrateDataObject(). In this example, a DataSet is received, and in the above PreparePacket, the Translate(dsRawPacket) is called. Here the Translate method acts as factory and instantiates the appropriate type-strong data object. Because each type-strong data object inherits from DataSet, the returned type from HydrateDataObject is of type DataSet. In fact, as was mentioned earlier, the Packet type simply contains our DataSet. For those cases that use type-strong data types, this type can actually be downcast to the appropriate type-strong DataSet and later accessed by those methods wishing to interact with type-specific behavior. This is great for Visual Studio's Intellisense! To construct our destination Packet, HydrateDataObject() is called, passing into it both the incoming DataSet via dsRawPacket and the newly instantiated type-strong DataSet called CreditCardDS. Here in HydrateDataObject(), we use the XML serialization services of .NET to perform the data hydration of the destination object (see the technology backgrounder in Chapter 5). Once hydrated, it is returned to Translate(), which in turn returns the entire packet back to PreparePacket(). You should also notice that before HydrateDataObject() is called, members of the Packet are filled with high-level data that will be used to route this packet. This is optional but points out that this is the place to implement such construction behavior. Finally, the other Translate method that is called with a packet must be turned into a DataSet. This is much simpler, at least in our example, because the DataSet is already contained in our Packet class on the way out and simply needs to be returned as is.

Listing 4.10 Packet Translator sample implementation—translating packets.

private DataSet HydrateDataObject(DataSet dsRawPacket,
                                               DataSet oDataObject)
    {
    System.IO.MemoryStream stream = new
    System.IO.MemoryStream();
          dsRawPacket.WriteXml(new XmlTextWriter(stream, null));
          stream.Position = 0;
          oDataObject.ReadXml(new
    XmlTextReader(stream),XmlReadMode.IgnoreSchema);
          return oDataObject;
    }

    public Packet Translate(DataSet dsRawPacket)
    {
          Packet oPacket = new Packet(this);

          // fill in packet values from DataSet (rawPacket)
          oPacket.Type = GetType(dsRawPacket);
          oPacket.Service = GetService(dsRawPacket);
          oPacket.Action = GetAction(dsRawPacket);

          switch (oPacket.Type)
          {
             case (Constants.CREDIT_CARD_TYPE):
             {
    oPacket.RawData =
    HydrateDataObject(dsRawPacket, new
    CreditCardDS());
                break;
             }
             case (Constants.TYPEB):
                {
                   ...
                   break;
                }
             default:
             {
                oPacket.RawData = dsRawPacket;
                break;
             }
          }

          return oPacket;
}

public DataSet Translate(Packet oPacket)
{
    return oPacket.RawData;
}

Related Patterns

  • Value Object (Alur, Crupi, Malks)

  • Builder (GoF)

  • Abstract Packet (Thilmany)

  • + Share This
  • 🔖 Save To Your Account