Wednesday, July 28, 2010

The Use and Misuse of Design Patterns

Design Patterns have always been of great interest to me.  (If you doubt this, you can see that I have a section of my Bookshelf dedicated to the topic.)  One of the greatest advantages to learning the basic patterns is to share a common language with your fellow developers, so when you talk about a Factory Method or Decorator, I know what you are talking about.  But at the same time, I see a tendency for some developers to use patterns for the sake of using patterns without fully considering the benefits and costs.

Rocky Lhotka has a great article about what developers should think about when considering patterns in their projects.  You can find it here: On the use and misuse of patterns.  Go take a look at it now.  Don't worry; I'll wait.

Okay, are you done reading it?  Go back and read it again.  It's that important.

Welcome back.  I've experienced a few of the issues that Rocky mentions.  First, I have seen the "Pattern of the Year" phenomenon.  It seems like some of the developers in my group get stuck on the current popular pattern.  I won't mention any specifics, because as Rocky notes, there's nothing wrong with the pattern itself.  The problem is that the popularity leads to a sort of cult of people who feel like they need to implement the pattern whether it fits in with the application or not.

Second, I have seen developers that get so enamored with a particular pattern than they try to use it at every turn.  Rocky's analogy is great on this:
"It is kind of like a carpenter who spends a lot of money buying some really nice new power tool.  And then trying to use that power tool for every part of the construction process -- even if that means being less efficient or increasing the complexity of the job -- just to use the tool."
Design patterns are just tools.  Part of being a good developer is understanding the strengths and weaknesses of each of those tools.  As developers, we need to focus on the problem space that we are working on and pick the appropriate tools for that job.  (As a side note, this extends beyond design patterns to the technologies that we use -- whether WPF, Silverlight, or WebForms -- and even further out to the platform -- whether .NET, LAMP, Java, or whatever.)

I do have an issue that I'm not quite sure how to approach: I have worked with a developer and talked about the benefits and costs of a specific design pattern.  We both agreed on the strengths (what the pattern was trying to solve for) and the weaknesses (the added complexity).  And we also agreed that we would not get the benefits of the pattern in the current application we were discussing.  The frustration is that the other developer still wanted to use the pattern because "we might need it later."  Experience shows that this would be unlikely.

So, if you have any suggestions on how to approach this type of situation, let me know.  I'll be sure to share the good responses here.  Send them to feeback@jeremybytes.com.

If you are new to the design patterns world, I would encourage you to learn the benefits and costs of each pattern.  And above all, consider their usage carefully.  Patterns are a wonderful tool.  But don't get so wrapped up in the tool that you forget the problem you are trying to solve.

Before you go, go back and read Rocky's article one more time: On the use and misuse of patterns.

Happy Coding!

Saturday, July 10, 2010

Intro to XAML Questions

While presenting the Intro to XAML session at recent code camp and user groups, a few questions came up.  Here's some more information on those topics that I didn't have at my fingertips at the time.

FrameworkElement in the Ticker Class
Question: Why does the Ticker class in the demo code descend from FrameworkElement?

Answer: As I noted during the session, the Ticker class exposes the DisplayInterval property as a DependencyProperty.  A DependencyProperty is a WPF/Silverlight construct that adds functionality above a normal property.  This is used for features such as animation, styles, and data binding.  We used it for data binding in our sample.

So where does FrameworkElement come in?  A dependency property can only be added to a DependencyObject (or a class that descends from DependencyObject).  FrameworkElement happens to be a descendent of DependencyObject.  And since it is also the base class for most of the elements in WPF and Silverlight, it also makes a convenient base class for our custom Ticker class.

If you want more information on dependency properties, you can check out MSDN here: http://msdn.microsoft.com/en-us/library/ms752914.aspx.

User Controls in WPF/Silverlight
Question: Can you create user controls in XAML that would allow you to use the same control on multiple screens?

Answer: The answer to this is definitely yes.  "UserControl" is one of the common root-level elements in XAML UIs (in addition to "Window" and "Page").  UserControl is now the default root element for Silverlight, but you can create your own user controls and embed them in other screens (whether they are Window, Page, or another UserControl).

I do have an example in Silverlight that creates a UserControl in a separate XAML file and then uses it on a screen.  The sample is available here: http://jeremybytes.blogspot.com/2009/06/more-silverlight-part-2-user-controls.html.  There is a small caveat to this, though: it is Silverlight 2.  Fortunately, the part that shows how to create a user control and use it in your application is still relevant in Silverlight 4 (and WPF as well).  The section on events is also still accurate; however, there is a much easier way to build this particular sample in Silverlight 3 or 4 by using object binding instead of events.

Attached Properties
Question: The XAML syntax for attached properties is intriguing.  How do they work?

Answer: An attached property is a construct in WPF and Silverlight, and how the framework handles it internally is more information that you probably want.  So, let's just take a look at a short sample.

In the demo code, we use an attached property by setting Grid.Row="0" inside of our TextBlock.  Here's a reminder of the code:

To get an idea of how this property gets set, let's take a look at how we would set this property in code rather than in the XAML.  We'll assume that our text block is named "myTextblock".  There are actually 2 ways we can set the property: either from the point of view of the Grid or from the point of view of the TextBlock.

From the Grid's viewpoint, the property is set like this:
Grid.SetRow(myTextBlock, 0);

From the TextBlock's viewpoint, the property is set like this:
myTextBlock.SetValue(Grid.RowProperty, 0);

Although this doesn't explain the internals, it does give you an idea of how it works.  With the first method, we are passing the element (myTextBlock) and value (0) to the Grid's SetRow method.  SetRow is a static method of the Grid class that allows for the "Row" attached property to be set.  With the second method, we use the SetValue method which allows us to set an attached property from the element (myTextBlock) itself.

Of course, there is more info on attached properties available on MSDN: http://msdn.microsoft.com/en-us/library/ms749011.aspx.

ZoomIt
Question: Where can I get the zooming tool used during the presentation?

Answer: ZoomIt is a tool that was created by a Microsoft employee (Mark Russinovich) for his own use in presentations.  It has several features including zooming the screen (like a magnifier), adding annotations (either drawing or text), and showing a break timer.  I ran across it while watching a webcast where the speaker was using the tool.

You can download ZoomIt for free here: http://technet.microsoft.com/en-us/sysinternals/bb897434.aspx

Additional XAML Samples
Not exactly a questions, but there are additional XAML samples available on my website.  The Target Practice application is a sample I built to see if I could build an application using XAML only.  I did this in both WPF and Silverlight 3.  Here are the links to the walkthroughs:

WFP: http://jeremybytes.blogspot.com/2009/03/wpf-xaml-sample.html
Silverlight: http://jeremybytes.blogspot.com/2009/09/target-practice-silverlight-3-xaml.html

As with all of my samples, the code can be downloaded from my website: http://www.jeremybytes.com/Demos.aspx.

That's it for now.  If you have any questions, feel free to send them to feedback@jeremybytes.com.

Happy Coding!

Thursday, July 8, 2010

What's Wrong with VB.NET?

VB.NET has the reputation of being a second class language in the .NET world.  A lot of this has to do with the history of VB and its transformation from VB6 into VB.NET.  Conversely, there is a perception that C# is the "real" .NET language, and I think that comes from its (much shorter) history.

At a recent user group meeting, someone joked that VB had been deprecated, and I will admit that I picked up and echoed that joke.  I hope that folks could tell that I wasn't serious.  When I'm talking to people, I try to point out VB resources where I can -- for example, my favorite Silverlight and WPF books have both VB and C# versions available -- but I'm personally more familiar with the C# resources since those are the ones I use on a day-to-day basis.

Today, VB.NET and C# are pretty much the same language with different syntax (at least that's how I like to think of them).  And the great thing about .NET is that whatever language you work with still gets compiled down to the same IL, and you can use assemblies in your project that are created in any .NET language (in fact, you probably don't even know what language a third-party assembly was created with).

Real programmers don't get stuck on syntax.  Programmers in general are opinionated and have their tools and languages of choice.  Good programmers generally have several different languages under their belts (and not just .NET languages, but things like Ruby, Python, Perl, Delphi, and Java).  I have my language of choice (which is currently C#, but has been different in the past), and before I start a task I try to make sure there isn't another tool that would do the job better.

Why the Bum Rap?
So, why does VB.NET have this reputation?  My theory is based on looking at the history of .NET.  When .NET launched, it was a brand new platform.  Along with that launch, Microsoft was promoting a brand new language (C#) that was created just for that platform.  In order for .NET to succeed, Microsoft had to get as many people on board as possible.  C# was the vehicle they used for most of their demonstrations.  This was because C# had all of the capabilities of .NET (at the time).  Because of this, C# became equated in many people's minds as the "primary" .NET language.

But Microsoft also knew that there were millions of people invested in VB.  They could not succeed if they forced all of the programmers who were comfortable with the VB syntax to switch over to a C-based syntax.  And more importantly, they couldn't force those developers to abandon all of their existing code.  So, we got VB.NET.  And that's sort of where the problems started.

First of all, VB.NET was very different from VB6.  There were a number of "features" that were put in to VB.NET to make migration of existing VB6 code easier.  But if programmers wanted to really start using the .NET platform to its full potential, they needed to re-write quite a bit of code to fit in with the new paradigm.

VB.NET and C# had quite a few differences in the early versions.  There were some constructs in C# that did not have an equivalent in VB.NET (and vice-versa).  In addition, Visual Studio tended to favor C# when it came to features such as refactoring and IntelliSense.  C# would get these feature updates first, and then they were made available to VB.NET later (as much later as the next release).

Forget Everything You Thought You Knew
But it's time to forget everything you thought you knew about the differences between VB.NET and C#.  With the latest release of .NET 4, the languages are almost equivalent; there are a few minor differences, but for all intents and purposes, you can accomplish the same tasks in similar ways.

Steve K. pointed me to this blog article from Steve Wiltamuth regarding the futures of both languages: VB and C# Coevolution.  In short, Microsoft is committed to moving both languages forward in the same direction and keep parity in the features and tools (such as the refactoring and IntelliSense features in Visual Studio).

Wrap Up
The good news of the similarities between the languages is that both C# and VB.NET programmers can take advantage of the vast amount of sample code that's available on the net.

Having both C# and VB.NET is great for the .NET development community.  C# (and the C-based syntax) provided a comfortable migration for folks using Java and C++; VB.NET provide a comfortable migration path for folks using VB.  Together, this has created a mix of developers that can share code and still hang on to their preferred syntax.  That sounds like the best of both worlds to me.

Happy Coding!

Monday, June 28, 2010

Upcoming User Groups

I'll be presenting at a couple of upcoming users groups in the Greater Los Angeles area.  Here are the dates and links to the websites:

Tuesday, July 6
LA C# (Manhattan Beach, CA) - http://www.lacsharp.org/

Wednesday, July 7
SoCal .NET (Buena Park, CA) - http://www.socaldotnet.org/

Meetings start at 6:00 p.m., and it's a great chance to interact with other developers in your local area.  Hope to see you there!

Sunday, June 27, 2010

Thanks for Coming - SoCal Code Camp San Diego

Thank you to everyone who took the time to attend my sessions at the SoCal Code Camp this weekend.  I had a great time doing the presentations, and I hope you found the information useful.

As a reminder, all of my sessions are available on my website here: JeremyBytes.com - Demos.

If you liked the sessions (or didn't like the sessions), feel free to drop me a note at feedback@jeremybytes.com.  I'll also be glad to answer any follow-up questions you may have.

Happy Coding!

Sunday, June 20, 2010

Book Review: Effective C# - Second Edition

I just finished up Effective C#: 50 Specific Ways to Improve your C# (Second Edition) by Bill Wagner.  This is a collection of expert tips presentented in a clear and concise manner.  These are targeted at the intermediate/advanced developer; it is assumed that you understand the basics of C# programming.  With that said, this is an excellent resource for folks like me.  Bill Wagner brings to light best practices, some pitfalls, and issues to consider, especially if you are designing libraries/APIs for consumption by other developers.

Overview

This is an updated version of Effective C# (First Edition) and More Effective C#.  Each of these covered different versions of the .NET framework.  This edition covers C# 4; the content is not limited to "what's new in C# 4."  It covers items that go back to the earliest versions of .NET, but also includes new items such as dynamic typing and parallel programming with PLINQ.

As the title suggests, there are 50 "items" (spread over 6 chapters).  The book is a fairly brief 300 pages; which translates into an average of 6 pages per item.  The items are well-presented with an introduction to the problem space, a recommendation (based on a set of parameters), and clearly written code snippets.  Each item is also summarized in a closing paragraph that reiterates the problem and solution.

Here's one thing that I like: Bill Wagner does not say "always do this."  Each recommendation includes the pros and cons as well as when you may want to do things one way versus another.  Many items will also refer to other items in the book.  This helps build a cohesion to the overall text.

Chapters
Here's a quick listing of the chapters with a few items from each to give you an idea of the types of things covered in each:
  1. C# Language Idioms
    Item 3: Prefer the is or as Operators to Cast
    Item 5: Always Provide ToString()
    Item 8: Prefer Query Syntax to Loops
  2. .NET Resource Management
    Item 14: Minimize Duplicate Initialization Logic
    Item 15: Utilize using and try/finally for Resource Cleanup
    Item 18: Distinguish Between Value Types and Reference Types
  3. Expressing Designs in C#
    Item 22: Prefer Defining and Implementing Interfaces to Inheritance
    Item 24: Express Callbacks with Delegates
    Item 25: Implement the Event Pattern for Notifications
  4. Working with the Framework
    Item 32: Avoid ICloneable
    Item 35: Learn how PLINQ Implements Parallel Algorithms
    Item 37: Construct Parallel Algorithms with Exceptions in Mind
  5. Dynamic Programming
    Item 38: Understand the Pros and Cons of Dynamic
    Item 40: Use Dynamic for Parameters That Receive Anonymous Types
    Item 44: Minimize Dynamic Objects in Public APIs
  6. Miscellaneous
    Item 45: Minimize Boxing and Unboxing
    Item 47: Prefer the Strong Exception Guarantee
    Item 48: Prefer Safe Code
A Couple Specific Examples
Item 8: Prefer Query Syntax to Loops
Wagner takes a look at advantages that query syntax (LINQ) has over loops (for, while, do, foreach).  He doesn't say that standard loops are bad or that we should stop using them.  Instead, he shows some specific examples that illustrate how query syntax can make your code more readable and maintainable.

Personally, I've become a big fan of LINQ.  But it did take me a while to get to that point.  Wagner challenges the developer to step out of his/her comfort zone (loops) and take a look at query syntax and to consider the difference between the imperative model (telling your code how to do the task) and the declarative model (telling your code what task you want to do).

Item 14: Minimize Duplicate Initialization Logic
Wagner points out the pitfalls of having multiple constructors as part of your class and having "copy/paste" code in each of the constructors.  This seems obvious once you think about it; after all, we always strive to minimize duplicate logic.  The first tendency may be to move all of the logic into a shared private method, but Wagner points out that this is not the optimum solution.  Instead look toward having the simpler constructors (those with fewer or no parameters) call the more complex constructors (those with several parameters).

Then he goes a step further and shows specific cases where you may introduce bugs in your code if you are not careful with how you implement the shared logic.  In addition, he takes a look at the efficiency of the code generated by the C# compiler in various situations.

Overall Quality
The overall quality of the text is very good.  I did notice a few typos here and there (no one is perfect -- I'm sure you'll also find some typos in this post).  There was only one item (#23) that had what I would consider significant issues with the code samples.  Fortunately, there is a blog on the SRT Solutions (co-founded by Wagner) web site that lists the errata.  Be sure to check this out.

Tech books are notoriously hard to produce due to how quickly technology changes (especially Microsoft technologies).  The errors that I noticed were well within the tolerable range and did not distract from my understanding of the content.

Recommendation
I would definitely recommend this book to intermediate and advanced C# developers.  There are a number of items (especially in the dynamic and parallel items) that gave me insight into things to watch for as I look into the new features in C# 4.  As any developer advances, he/she usually ends up creating shared libraries (shared utilities, for example). Wagner includes many items that cover best practices for creating shared libraries and APIs that are consumed by other developers.  This is also helpful when one works as part of of a team on projects that have multiple interoperating assemblies/modules.

So, pick this book up.  It has bite-sized chunks of good information and some good tips on new C# features.

Happy Coding! 

Monday, May 31, 2010

Updated Sessions

I have updated a number of my sessions for Visual Studio 2010 and/or Silverlight 4.  I will be presenting three of these sessions at the So Cal Code Camp coming up on June 26 & 27, 2010.  These are all available for download here: http://www.jeremybytes.com/demos.aspx.

Introduction to the BackgroundWorker Component with WPF
Long running processes are a user experience killer. How many times have you had an application "lock up" while trying to do some function? The BackgroundWorker component in .NET allows you to spawn those long running processes in the background and keep your WPF, Silverlight, or WinForms user interface responsive. We'll take a look at the features of the BackgroundWorker in a WPF application including running a background process, updating the progress in the UI, and cancelling the process before it has completed.

This session has been expanded to include Exception Handling and additional error checking.

Walkthrough: BackgroundWorker-WPF2010.pdf
Sample Code: BackgroundWorker-WPF2010.zip

Introduction to Data Templates and Value Converters in Silverlight
Business applications are all about data, and laying out that data is critical to creating a good user experience. Silverlight has several tools, including Data Templates and Value Converters, that make this easier for the business developer to manage. By the time we're done, you will have a good understanding of the basics of both of these valuable tools.

This session has been updated for Silverlight 4.

Walkthrough: DataTemplatesAndConverters2010.pdf
Sample Code: DataTemplatesAndConverters2010.zip

Introduction to XAML - WPF 2010 / Silverlight 4
Understanding XAML (eXtensible Application Markup Language) is a key to creating the latest .NET user experiences in WPF and Silverlight. We will introduce the basic concepts around XAML and take a look at various features such as namespaces, elements, properties, events, attached properties and some basic layout. We’ll create a simple WPF or Silverlight application that covers these fundamentals. Although you will probably end up doing most of your UI design with a drag-and-drop tool such as Expression Blend, knowing the internals gives you a leg up in making the final tweaks to ensure an excellent user experience.

This session has been updated to include both WPF and Silverlight versions.  The same core XAML features are covered in each environment.

Walkthrough (WPF): IntroToXAML-WPF2010.pdf
Sample Code (WPF): IntroToXAML-WPF2010.zip

Walkthrough (Silverlight): IntroToXAML-Silverlight4.pdf
Sample Code (Silverlight): IntroToXAML-Silverlight4.zip

As always, your feedback/questions on any of these sessions is appreciated: feedback@jeremybytes.com.

Happy Coding!