Click here to close now.

Welcome!

.NET Authors: Kathy Thomas, Greg O'Connor, Liz McMillan, Esmeralda Swartz, Jayaram Krishnaswamy

Related Topics: .NET

.NET: Article

Implementing Patterns with Generics

It's more than just collections

It's been a few months since Visual Studio 2005 was released. In that time you've probably seen and read quite a bit about generics. Unfortunately all those articles and presentations can leave you with the impression that generics are useful only in the context of collections (List<T>, Dictionary<K,V>, Queue<T>, and so on).

It's true that many of the most common uses of generics involve collections. But limiting your use to collections will cause you to miss many of the opportunities for creating components that you can reuse in even more ways. In fact, many idioms where developers commonly copy, paste, and modify source code can be solved with generics. You should look for these opportunities, because you'll have more functionality in a smaller code base.

Enhance a generic class, and all users of it are one recompile away from the new features. That's much better than using code snippets. It's a manual task to track down and edit all the copies of a code snippet inserted into your project.

In this article, I'll show you how to find algorithms that can be replaced with generics and how to migrate specific code to its generic counterpart. As examples, I'll show you a quick example by serializing types as XML data, and I'll build a more complicated version, implementing the Proxy class from Design Patterns (Addison-Wesley, 1995).

The Sample Application
To illustrate these topics, I built a simple application that enables you build a collage from a list of images. (See Figure 1.) This is a small sample to illustrate the concepts, so keep your copy of Photoshop for now. The sample application lets you choose a source directory for your images, copy the images onto a background, and move and scale the images. Once you have something you like, you can save the composite image.

We'll examine this application and extract two generic algorithms that you can reuse in your own applications.

Making Generics
Generics are the .NET way of creating algorithms that are loosely coupled to the types on which they operate. That's a large part of the reason why so many of the examples use collections. Collection algorithms don't normally have any dependencies on the types contained in the collections. List<int>, List<string>, List<Employee>, or anything else would work just fine.

The implementation of the collection classes isn't dependent on any properties, or behavior, defined in the type contained. In fact, different generic collections only differ in the capabilities of the collection itself; rarely do they differ in the constraints mandated on the contained type.

In my example, I've used a List<Image> for the list of images in the current collage. The list of files is a BindingList<string> because the BindingList<T> class contains extra functionality that facilitates data binding in Windows forms applications. You've probably already used both of these classes.

Another area where you can see generics used in the .NET Framework is in interfaces that are often used in collections: IEquatable<T>, IEqualityComparer<T>, and ICompar-able<T>. Once again the key to using generics is that signature of the interface is very common: The implementation will depend on the specific type and the parameters depend on the specific type, but the semantic contract is independent of the type.

So the .NET Framework has a rich set of generic classes that are great for various common uses. These classes are designed for very horizontal applications. But they probably aren't all the reusable bits of functionality you'll use in your applications or across multiple applications in your organization. As you develop more code, you'll discover that you've written bits of functionality that you want to reuse in many different ways. With a little work, you can modify these bits of code so that you can reuse them, unmodified, in many different ways.

The first example will provide a mechanism to store and retrieve the current application state. Most desktop applications will store some form of user preferences, or last actions, or similar data. I find that persisting that information using the .NET XML serialization framework is an easy way to implement that. You write a simple class that contains public properties for all the user-controlled options. Then you write two methods to load and save the options. My sample application used the specific UserPreferences class shown in Listing 1.

You'll notice that the LoadFromFile and SaveToFile methods are almost completely independent of the type used (UserSettings). You should be able to reuse these methods anywhere, right? You can. Simply factor out those two methods and put them in a generic class. The wrapper class contains a single member of the target type and provides the load and save code. It also provides a read-only property to access the embedded target object. Limiting the target object to a class type enables you to add a read-only property to modify the embedded storage and still provide appropriate access to the embedded object for the rest of the program. The generic wrapper is shown in Listing 2.

Reusing this is a simple matter of creating a new instantiation with different type information. As an example, let's add the ability of saving your current work to the sample application. Doing so will leverage the AutoSave generic class. Inside the Main form, you've got a list of images:

private List<CollageImage> listOf-Images = new List<CollageImage>();

Essentially, that's the entire storage for the current collage. So let's make a couple of modifications to the CollageImage class that will make it easier to save that via XML serialization. The images need the XMLIgnore attribute:

[XmlIgnore()]
public Image Thumbnail
{
      get
      {
         generateThumbnail();
         return thumbNail;
      }
}

      And the image path must be a read/write property:

public string ImagePath
{
      get { return path; }
      set { path = value; }
}

Next, let's build a simple class that contains the list of images. (See Listing 3.) There is one interesting problem in the generic collections with respect to XML Serialization. For some reason, the XML Serializer can't save or restore a generic IList<T>, but it can serialize and IList interface, provided the appropriate attributes are added to the property. Therefore, I've added two different IList properties to this class, one IList<CollageImage>, one IList. The second is correctly serialized.

Finally, you can use the AutoSave template to create a version of this class that can be serialized. That's it. The point is that you can reuse the AutoSave generic class with only minimal extra work.

Pondering Patterns
Load and save was fairly simple, so let's move on to the more complicated Proxy pattern. Stripped of all the glamour normally associated with a new buzzword, a design pattern is simply a standard proven solution to a common programming problem. Nothing more; nothing less. As such it's a way to reuse common solutions to common problems. Design Patterns by Gamma, Helm, Johnson, and Vlissides (Addison-Wesley, 1995) is still the definitive catalog of patterns.


More Stories By Bill Wagner

A frequent writer and speaker, Bill's work is published in ASP.NET Pro and Visual Studio Magazine. He is the author of C# Core Language Little Black Book and Effective C#. You can reach Bill at [email protected]

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
SYS-CON Events announced today the IoT Bootcamp – Jumpstart Your IoT Strategy, being held June 9–10, 2015, in conjunction with 16th Cloud Expo and Internet of @ThingsExpo at the Javits Center in New York City. This is your chance to jumpstart your IoT strategy. Combined with real-world scenarios and use cases, the IoT Bootcamp is not just based on presentations but includes hands-on demos and walkthroughs. We will introduce you to a variety of Do-It-Yourself IoT platforms including Arduino, Raspberry Pi, BeagleBone, Spark and Intel Edison. You will also get an overview of cloud technologies s...
SYS-CON Events announced today that SafeLogic has been named “Bag Sponsor” of SYS-CON's 16th International Cloud Expo® New York, which will take place June 9-11, 2015, at the Javits Center in New York City, NY. SafeLogic provides security products for applications in mobile and server/appliance environments. SafeLogic’s flagship product CryptoComply is a FIPS 140-2 validated cryptographic engine designed to secure data on servers, workstations, appliances, mobile devices, and in the Cloud.
The WebRTC Summit 2014 New York, to be held June 9-11, 2015, at the Javits Center in New York, NY, announces that its Call for Papers is open. Topics include all aspects of improving IT delivery by eliminating waste through automated business models leveraging cloud technologies. WebRTC Summit is co-located with 16th International Cloud Expo, @ThingsExpo, Big Data Expo, and DevOps Summit.
Containers and microservices have become topics of intense interest throughout the cloud developer and enterprise IT communities. Accordingly, attendees at the upcoming 16th Cloud Expo at the Javits Center in New York June 9-11 will find fresh new content in a new track called PaaS | Containers & Microservices Containers are not being considered for the first time by the cloud community, but a current era of re-consideration has pushed them to the top of the cloud agenda. With the launch of Docker's initial release in March of 2013, interest was revved up several notches. Then late last...
SOA Software has changed its name to Akana. With roots in Web Services and SOA Governance, Akana has established itself as a leader in API Management and is expanding into cloud integration as an alternative to the traditional heavyweight enterprise service bus (ESB). The company recently announced that it achieved more than 90% year-over-year growth. As Akana, the company now addresses the evolution and diversification of SOA, unifying security, management, and DevOps across SOA, APIs, microservices, and more.
After making a doctor’s appointment via your mobile device, you receive a calendar invite. The day of your appointment, you get a reminder with the doctor’s location and contact information. As you enter the doctor’s exam room, the medical team is equipped with the latest tablet containing your medical history – he or she makes real time updates to your medical file. At the end of your visit, you receive an electronic prescription to your preferred pharmacy and can schedule your next appointment.
GENBAND has announced that SageNet is leveraging the Nuvia platform to deliver Unified Communications as a Service (UCaaS) to its large base of retail and enterprise customers. Nuvia’s cloud-based solution provides SageNet’s customers with a full suite of business communications and collaboration tools. Two large national SageNet retail customers have recently signed up to deploy the Nuvia platform and the company will continue to sell the service to new and existing customers. Nuvia’s capabilities include HD voice, video, multimedia messaging, mobility, conferencing, Web collaboration, deskt...
The Open Compute Project is a collective effort by Facebook and a number of players in the datacenter industry to bring lessons learned from the social media giant's giant IT deployment to the rest of the world. Datacenters account for 3% of global electricity consumption – about the same as all of Switzerland or the Czech Republic -- according to people I met at the recent Open Compute Summit in San Jose. With increasing mobility at the edge of the cloud and vast new dataflows being predicted with the growth of the Internet of Things (and The Coming Age of Many Zettabytes) in the near...
The list of ‘new paradigm’ technologies that now surrounds us appears to be at an all time high. From cloud computing and Big Data analytics to Bring Your Own Device (BYOD) and the Internet of Things (IoT), today we have to deal with what the industry likes to call ‘paradigm shifts’ at every level of IT. This is disruption; of course, we understand that – change is almost always disruptive.
SYS-CON Events announced today that Cisco, the worldwide leader in IT that transforms how people connect, communicate and collaborate, has been named “Gold Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Cisco makes amazing things happen by connecting the unconnected. Cisco has shaped the future of the Internet by becoming the worldwide leader in transforming how people connect, communicate and collaborate. Cisco and our partners are building the platform for the Internet of Everything by connecting the...
Temasys has announced senior management additions to its team. Joining are David Holloway as Vice President of Commercial and Nadine Yap as Vice President of Product. Over the past 12 months Temasys has doubled in size as it adds new customers and expands the development of its Skylink platform. Skylink leads the charge to move WebRTC, traditionally seen as a desktop, browser based technology, to become a ubiquitous web communications technology on web and mobile, as well as Internet of Things compatible devices.
SYS-CON Events announced today that robomq.io will exhibit at SYS-CON's @ThingsExpo, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. robomq.io is an interoperable and composable platform that connects any device to any application. It helps systems integrators and the solution providers build new and innovative products and service for industries requiring monitoring or intelligence from devices and sensors.
SYS-CON Media announced today that @WebRTCSummit Blog, the largest WebRTC resource in the world, has been launched. @WebRTCSummit Blog offers top articles, news stories, and blog posts from the world's well-known experts and guarantees better exposure for its authors than any other publication. @WebRTCSummit Blog can be bookmarked ▸ Here @WebRTCSummit conference site can be bookmarked ▸ Here
Docker is an excellent platform for organizations interested in running microservices. It offers portability and consistency between development and production environments, quick provisioning times, and a simple way to isolate services. In his session at DevOps Summit at 16th Cloud Expo, Shannon Williams, co-founder of Rancher Labs, will walk through these and other benefits of using Docker to run microservices, and provide an overview of RancherOS, a minimalist distribution of Linux designed expressly to run Docker. He will also discuss Rancher, an orchestration and service discovery platf...
Sonus Networks introduced the Sonus WebRTC Services Solution, a virtualized Web Real-Time Communications (WebRTC) offer, purpose-built for the Cloud. The WebRTC Services Solution provides signaling from WebRTC-to-WebRTC applications and interworking from WebRTC-to-Session Initiation Protocol (SIP), delivering advanced real-time communications capabilities on mobile applications and on websites, which are accessible via a browser.
SYS-CON Events announced today that Aria Systems, the leading innovator in recurring revenue, has been named “Bronze Sponsor” of SYS-CON's @ThingsExpo, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Proven by the world’s most demanding enterprises, including AAA NCNU, Constant Contact, Falck, Hootsuite, Pitney Bowes, Telekom Denmark, and VMware, Aria helps enterprises grow their recurring revenue businesses. With Aria’s end-to-end active monetization platform, global brands can get to market faster with a wider variety of products and services, while maximizin...
SYS-CON Events announced today that Vitria Technology, Inc. will exhibit at SYS-CON’s @ThingsExpo, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Vitria will showcase the company’s new IoT Analytics Platform through live demonstrations at booth #330. Vitria’s IoT Analytics Platform, fully integrated and powered by an operational intelligence engine, enables customers to rapidly build and operationalize advanced analytics to deliver timely business outcomes for use cases across the industrial, enterprise, and consumer segments.
SYS-CON Events announced today that Akana, formerly SOA Software, has been named “Bronze Sponsor” of SYS-CON's 16th International Cloud Expo® New York, which will take place June 9-11, 2015, at the Javits Center in New York City, NY. Akana’s comprehensive suite of API Management, API Security, Integrated SOA Governance, and Cloud Integration solutions helps businesses accelerate digital transformation by securely extending their reach across multiple channels – mobile, cloud and Internet of Things. Akana enables enterprises to share data as APIs, connect and integrate applications, drive part...
SYS-CON Events announced today that Solgenia will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY, and the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Solgenia is the global market leader in Cloud Collaboration and Cloud Infrastructure software solutions. Designed to “Bridge the Gap” between Personal and Professional Social, Mobile and Cloud user experiences, our solutions help large and medium-sized organizations dr...
SYS-CON Events announced today that Liaison Technologies, a leading provider of data management and integration cloud services and solutions, has been named "Silver Sponsor" of SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York, NY. Liaison Technologies is a recognized market leader in providing cloud-enabled data integration and data management solutions to break down complex information barriers, enabling enterprises to make smarter decisions, faster.