Portable is as portable does... Maximizing code reuse via the magic of the Portable Class Library
- Posted: Aug 20, 2012 at 6:00 AM
- 5,542 Views
Today's Modern UI Monday project and post from Alnur Ismail provides some great guidance and information on to increase your code's portability across many of the Microsoft development platforms. With the number of platforms growing, the more code we can reuse, via a binary library, the better, right? What's better than writing library code once and reusing it on Windows 8, Windows 7, Windows Phone 7.5, Windows Phone 8, Silverlight, and even the XBox 360?
A common ask among customers and developers is around guidance on how to structure/architect their code to maximize reuse across Windows 8 and Windows Phone apps. This post will explain what is/isn’t reusable across apps, cover some patterns that will help increase code reuse across Microsoft platforms, and puts the theory into practice with a sample that shows common code being used for both a Windows 8 and Windows Phone 7.5 app — available here.
Note: This post focuses on Windows 8 and Windows Phone 7.5 app development. However, the patterns and practices described can be applied to other platforms (i.e. Windows Phone 8 when it’s generally available).
PCL (Portable Class Libraries)
PCL by definition are constrained and can only reference APIs that are available across multiple platforms (i.e. Windows 8, Windows Phone 7.5). Consequently, libraries can be shared across projects without modification.
By combining MVVM with PCL it is possible to architect code so large portions like the ViewModel and Model can be reused across supported platforms. It is also possible to reuse parts of the View because a significant amount of XAML (i.e. StackPanel, Grid, Button, etc.) is available to both platforms but the general guidance is to focus on taking advantage of the form factor instead of forcing the issue.
Practice, however, is never as clear cut as theory. For example, when creating a ViewModel that is responsible for retrieving data the first wrench appears. Writing code to retrieve data that is common across both platforms is non-trivial because WinRT introduces HttpClient that is asynchronous using async/await to simplify networking.
The sample I’ve provided shows how to work around both wrenches and uses a common ViewModel and Model for both the Windows 8 and Windows Phone apps.
Other Reuse Tips
From my experience there are two other ways to maximize code reuse that can be used in conjunction with MVVM and PCL.
- Linked Files – allows a file to be shared between two projects but only one copy is maintained
- Preprocessor Directives – compiles code based on conditions that are set up in the build environment (contributes to code smell and not recommend but I’ve included an example in the sample for reference)
For more information and details on the Portable Class Library please check out, Portable Class Library Overview