Silverlight Code: Reduce, Reuse and Recycle
A developer's guide to unlocking the power of code reusability.
On April 22, 1970, U.S. Sen. Gaylord Nelson introduced the world to "Earth Day," an annual day devoted to raising awareness of and educating consumers about environmental issues affecting the planet. For its part, the U.S. Environmental Protection Agency joined in the effort by creating a hierarchy known as the "Three R's" -- Reduce, Reuse, Recycle -- that were to help spur solid waste reductions and promote better use of sustainable consumer practices. More than 40 years later, hundreds of millions of people around the globe join in annual Earth Day celebrations, with the Three R's as their rallying cry.
The Three R's concept focuses on extracting maximum benefit while generating minimum waste. Although created to address environmental issues, the principles behind the Three R's have practical application elsewhere. For example, imagine what would happen if the Reduce, Reuse, Recycle paradigm was applied consistently in software engineering. What if software developers resisted the urge to recreate and instead concentrated on the Don't Repeat Yourself (DRY) principle? What productivity gains and quality improvements might be achieved by simply developing software with an initial greater emphasis on lasting reusability?
Taken at face value, there are immediate tangible benefits that come quickly with the addition of the Three R's to the development environment, such as cleaner, more flexible code and improved portability.
Yet, digging beneath the surface of these imminent positives reveals a far more significant long-term advantage: The restructuring of the organizational approach to application development can elevate the overall development process and lifecycle. By adopting a systematic approach to reusability at the point when a project begins, teams can raise their software development processes to the next level, generating long-term benefits that include enhanced product quality, faster time-to-market, reduced risk and improved ROI.
Rethinking application development to incorporate reusability as a fundamental underpinning can require more upfront investment and effort, especially as the process is first learned. The value of long-term benefits spawned by superior reusability, however, far outweighs the cost. Or, stated more concisely, a small amount of short-term pain will ensure maximum long-term gain. Developers and project teams willing to take on the challenge of achieving optimum reusability will gain the competitive edge necessary to excel in today's crowded marketplace.
The First R: Reduce
In February 2011, the Agile Manifesto celebrated a historic milestone: its 10th birthday. In the decade since the manifesto's debut, Agile has matured into a sophisticated development model leveraged by millions of individuals and organizations around the world. While its methodologies have evolved to assimilate the latest technology advancements, innovations and best practices, the ideals at the heart of the Agile doctrine remain unchanged: rapid development, continuous delivery, unparalleled quality and lower costs.
At first glance, pairing Agile and the Three R's may seem counter-intuitive. Agile dictates swift, continuous delivery, with a focus on individuals and interactions rather than processes and tools. Coding for maximum reusability, however, requires a more careful approach and increased investment into strategic project planning and execution. Yet Agile and reusability are not mutually exclusive -- far from it, in fact. Since its debut, the Agile Manifesto has been augmented with "The 12 Principles of Agile Software," a dozen foundational standards that define the qualities of Agile applications. According to these principles as laid out by the Agile Alliance, simplicity -- "the art of maximizing the amount of work not done" -- and sustainable development are essential Agile software components.
Harking back to the Three R's analogy finds that both of these elements dovetail nicely with the first R, Reduce. For example, by engineering their work with an eye toward greater reusability, developers can achieve significant reductions in:
- Development cycle times and time-to-market
- The amount of new code that must be created per project
- Imbalances in project pacing and workload distribution
- The amount of time devoted to code reengineering and refactoring in the future
- Process and project risk
- Project development and maintenance costs
In his 2009 book, "Software Engineering Best Practices: Lessons from Successful Projects in the Top Companies" (McGraw-Hill Osborne Media, 2009), Capers Jones, president and CEO of Capers Jones & Associates and chief scientist emeritus at Software Productivity Research, notes that reusability has one of the highest returns on investment, with reports of ROI gains reaching up to an extreme of 300 percent. Designing reusable code lowers the amount of original code that must be written, allowing developers to rely instead on previously created elements that can be repurposed as needed.
Furthermore, by maximizing simplicity -- the amount of work not done -- teams will in turn achieve greater sustainability, minimizing the erratic pacing that can often plague Agile projects. The result is a better working environment with more evenly distributed workloads, preventing developer burnout. In short, reusability delivers its greatest value to Agile teams in the form of increased simplicity and better sustainability, which eventually equates to a higher ROI.
The Middle R: Reuse
If the first of the Three R's, Reduce, defines the "why," it's up to the next R, Reuse, to address the "how" of reusability. Talking about adding a higher degree of reusability to application development is well and good, but it's the nuts and bolts of implementation that most developers could use a little help with. The misconception still endures that building reusability into the development process is painful. Clearly, there's some short-term "pain," including evaluating current methodologies for increased reusability, taking a more considered approach to development and accounting for refactoring time. But the process is not as complex or onerous as many developers believe it to be. Once embarked on the journey toward greater reusability, developers and teams will begin to realize those long-term agility gains that more than compensate for any initial difficulties.
The first step to building in reusability as a common part of the development environment and process begins with a self-evaluation. Individual developers and teams alike must start by answering questions of "when," "what" and "how." When is greater reusability a good fit for my project or application development environment? What reusable artifacts best lend themselves to my development processes and model? How do I successfully create these reusable assets?
The question of "when" might be the easiest to answer. Instances where better reusability is an advantage might include:
- Long-term roadmaps calling for application portability between devices; for example, a desktop application slated for translation to the Web, mobile or both
- Applications with multiple platform-specific versions
- The creation of a project or enterprise-wide component library
While the "when" will vary depending on development models, business strategies and organizational priorities, elevated reusability almost certainly has some relevance to nearly every development environment.
With the "when" answered, there's a natural progression to the next question -- that of "what." Reusability need not be limited to simply creating lines of code that can be copied and pasted from one application to the next; rather, there are numerous elements that can be ideally molded into reusable artifacts:
- Design, architecture and frameworks
- Project requirements, plans and estimates
- Source code and controls
- Screens and interfaces
- Documentation and training materials
- Testing plans and scripts
With so many opportunities for injecting it into the development landscape, reusability is a quality that doesn't have to be restricted to coding alone. Approached properly, it can become a valuable end-to-end resource across the full length of the application lifecycle.
With "when" and "what" squared away, the final question of "how" is ready to be dealt with. Examining how code can be shared between Windows Phone 7 and Silverlight desktop applications can provide clear illustration of practical methods for fostering or increasing reusability in development.
But They're Both Silverlight ... Right?
The latest Microsoft UI technology, XAML, has quickly become the common foundation for desktop, Web and -- with the introduction of Windows Phone 7 -- mobile applications. Combined with the common Microsoft .NET Framework programming environment, developers are presented with a technology stack that encourages reuse regardless of application type.
The most significant reuse the XAML and .NET platforms provide is skill reuse. Development teams familiar with the underlying technologies can quickly move between desktop, Web and mobile applications using the same set of development skills to produce results. This is a significant advantage over previous technologies, even in the Microsoft space, which required developers to learn different UI technologies for each targeted environment.
Code reuse between these environments, though, is actually more difficult to achieve. While the concepts and syntax are consistent, the diversity of the target platforms requires unique attention.
When first looking at "desktop" Silverlight and the Windows Phone platform, many developers might initially be under the impression that, with both platforms using a .NET back-end and a XAML front-end, the code being used for one can be swiftly and easily be ported to the other. Upon closer examination, however, it becomes apparent that though the two platforms share some common DNA, there are significant differences between the two that can quickly add up.
The primary difference between platforms is interaction. While Silverlight on the desktop is designed at its core to interact with the mouse and keyboard, Windows Phone Silverlight is designed to primarily support touch-screen interactions. This transition from mouse to touch can be seen in differences between the APIs for both platforms. Silverlight for Windows Phone 7 represents a hybrid of Silverlight 3 and 4, adding embedded, native support for touch events and removing anything specific to mouse and keyboard input. This key difference may be better illustrated with an example using Silverlight code for a standard button:
<Button Content="Standard Button" />
The code is the same and reusable, but the rendered results are very different on the two platforms (see Figure 1).
|Figure 1. A simple button object rendered in Silverlight (top) and Windows Phone 7 (bottom).|
Why is there such a difference?
The red rectangles around each button represent the "hit area" for the control, the region in which users can either click or tap the screen and generate an expected response. Desktop Silverlight, with its optimization for mouse- and keyboard-driven input, has very specific hit areas, as a high degree of precision is possible. Conversely, Windows Phone 7 must accommodate a number of variables -- such as the great diversity in sizes of users' hands -- for its touch-based interface, meaning that, in this case, usability will win out over precision during the UI design process. So, while the code may be reusable, the design concepts are not. Direct code reuse will produce results that do not appropriately target these device differences, potentially driving negative ROI as code is endlessly "tweaked."
Moving on to a more advanced scenario, a typical page layout between the two platforms is substantially different and needs to be handled as such. For the desktop, it's safe to assume display parameters of 1024 x 768 for low-end monitors, and 1920 x 1200 for high-end screens. This widely varying range equals a great deal of screen real estate when it comes to design, especially considering the fact that well-designed and executed Silverlight applications will often use modular design concepts that allow different regions of the screen to be updated dynamically based on the needs of the application.
Windows Phone 7 takes a linear navigation approach through an application, with the general guideline falling somewhat closer to Model-View-Controller (MVC) tenets specifying that every screen has a particular purpose. For example, need a list item? Navigate to a details screen. Want to modify a record? Navigate to an edit screen. This keeps the application flow moving with a minimum of scrolling required across individual pages, and provides a logical "back stack" -- the history of pages in Windows Phone 7 applications -- in case users need to back out through the application to return to a particular point.
This brings up the question of why this matters, but the answer is simple: Designing for the desktop and mobile are two very different environments, therefore reuse of XAML is quite low between the two distinct versions of Silverlight. As an example, Listing 1 shows a typical page in a navigation-based Windows Phone 7 application.
While desktop Silverlight stresses flexibility, Windows Phone 7 stresses conformance to standards. From the top, the application title and page name are standard across any type of Windows Phone 7 page, such as portrait, layout, panorama or pivot, providing a consistent user experience. The application bar at the bottom is also consistent and should always function the same way across any Windows Phone 7 application.
However, the equivalent for a standard desktop Silverlight application is not quite as easy. Developers can do anything using desktop Silverlight, given that they're creating standalone applications that can be viewed in and out of browser across two OSes.
Silverlight presents a great case for skill reusability, but direct code reusability is not generally advisable at the UI layer. The environments are too divergent, and the interaction models are too different. Instead, it's better to focus on building UIs specifically targeted to each environment and focus on code reuse in other layers.
While the reusability of XAML between environments like Silverlight and Windows Phone 7 may not represent a great opportunity for developers to reduce code, there are many other layers of an application that can be constructed for maximum reusability -- even across diverse devices. An application's business and data-access logic are perfect candidates for code reuse.
Simplified, any application should be constructed of at least three distinct layers:
- The UI layer
- The logic layer
- The data layer
The UI layer is generally the least reusable. An application that presents multiple GUIs will typically create UI code specifically optimized for each UI environment. As in the previous example, even when the programming language is common, creating unique UIs for Silverlight and Windows Phone 7 ultimately produces the best results, as each platform has vastly different design assumptions and interface models. Done right, however, a UI will contain very little "application logic," so creating new UIs should be a low-effort task for a development team.
The logic and data layers, meanwhile, should be highly reusable. With solid application architecture, all business rules and data access should be cleanly encapsulated within these layers. Isolating the application logic and data access in this manner ensures minimal coupling to the UI, which in turn makes it easier to add and remove UIs for an application as user behaviors evolve.
For example, a Silverlight application built using these basic architecture principles might consist of the following Visual Studio projects:
The "Services" project is added to account for the client-side execution model of Silverlight, which requires Web services to exchange data with servers. With this architecture, the process of adding a new Windows Phone UI requires only one additional project: MyApp.UI.WindowsPhone.
All code in the logic and data layers can be consumed directly by the new Windows Phone 7 UI. There's no need to recreate code for defining business rules and data access. By leveraging reusable code, the start-up time for creating new UIs is minimized, along with the long-term maintenance costs of updating the application.
With proper application architecture, UI implementation represents the "last mile." The majority of an application's functional code lives in easily consumable reusable modules, empowering development teams to quickly deliver new interfaces for applications.
The Last R: Recycle
There's one R left in the Three R's paradigm, and that's Recycle. This R has less to do with the many benefits of greater reusability or the practical recycling methodologies developers can leverage when architecting and producing reusable artifacts. Rather, Recycle is more of a cautionary tale -- a modern-day parable that expresses the dangers that can befall sloppy developers and unwary project teams.
As with many things in life, there's a strong temptation for developers across the .NET ecosystem to take the path of least resistance. Today's next-generation tools and control suites make it easier than ever to jumpstart the application-development process. Drag-and-drop and quick-start functionality make quick-and-dirty application development and data access far easier now than any time before. Because these tools make it so easy, there's some reluctance on the part of .NET developers to take the extra steps and care needed to fully implement best practices and achieve clean data-access layer separation.
The same holds true for reusability. The temptation there is to resort to "copy-paste coding," or to move elements around and call it good. Unfortunately, these efforts tend to fall short. Take, for example, reusing desktop UI code in mobile applications. While copying and pasting desktop elements into a mobile application might generate up-front time savings, it will also lower productivity in the end: tweaking and converting the old UI to properly fit the mobile form factor will end up eroding those short-term gains. Therefore, in this example, it would be wiser to invest the resources necessary to create artifacts geared toward maximum reusability and extensibility right from the start, instead of attempting to shoehorn in recycled components.
Other pitfalls lie in wait for developers using recycled code in the name of reusability. The previously cited observation by Capers Jones, wherein he found that reusability could generate ROI gains of up to 300 percent, only tells half the story -- he also discovered that reusing poorer quality materials could result in negative ROI of up to 300 percent. Source code and other reusable elements must be dependency-, bug- and defect-free, if they're to deliver positive ROI. Without zero tolerance for weaknesses such as code defects and dependencies, recycled code is more of a liability than an asset.
In summary, while the recycling of elements and artifacts can be an effective means of boosting reusability, it's not a task to be undertaken lightly. It's a process that requires a strategic, forward-looking approach, strict adherence to best practices, and a high-quality, defect-free foundation upon which to build.
The Most Important R: Results
There's a final R that really needs to be added to this equation -- and it's the most important one of all: Results. While achieving greater reusability is a laudable goal, it will mean nothing if it doesn't produce the desired positive result, and could even be a recipe for disaster should it generate a negative outcome.
The idea of "reusability" is far deeper and more complex than simple, repeated code reuse; rather, it's a deliberate strategy that calls for careful planning and forethought before execution ever occurs. Tangible results that can be quantified and analyzed so that methodologies can be further refined are critical for those developers, teams and organizations that place a premium on reusability. Teams must set expectations prior to structuring or restructuring the development environment and processes.
Developers should define parameters such as:
- The meaning of a "result," whether it be lowered development costs, shortened cycles, greater code robustness or improved product quality
- What the desired and expected results are from reusability efforts
- What methodologies and metrics will be used to qualify and quantify short-term and long-term impacts
With clearly defined goals, expectations, metrics and strategies in place, reusability can become a truly constructive, embedded element of the development process.
Although designed to raise environmental awareness in consumers, the principles behind the Three R's are an apt proposition for the software development landscape. Like its impact on the environmental movement, Reduce, Reuse, Recycle has the power to substantially alter the developer ecosystem for the better. However, the unparalleled benefit that the Three R's concept holds will remain dormant until developers recognize and embrace the true value it offers, and devise forward-looking strategies to unlock its full potential.