Home > Articles > Programming > Windows Programming

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)

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020