Monday, July 29, 2013

August Speaking Engagements

I was at the So Cal Code Camp in San Diego this weekend and had a lot of fun.  There were tons of good sessions and good speakers.  I got to see a lot of old friends, and I got to meet a lot of new friends.  A big thanks to everyone who came up and said "Hi" to me.  I always like to meet new people.

If you want to meet me in person, I'll be speaking at a couple of events in August:

Tuesday, August 6, 2013
San Diego .NET Developers Group
San Diego, CA
Topic: Clean Code: Homicidal Maniacs Read Code, Too!

Thursday, August 22, 2013
South East Valley .NET User Group
Chandler, AZ
Topic: Clean Code: Homicidal Maniacs Read Code, Too!

I've been enjoying talking about Clean Code (including this past weekend at Code Camp).  We take a look at some bad code (some *really* bad code) to see what to avoid.  It's always fun to laugh at code you don't have to actually work with.  But we'll spend most of our time looking at some easy ways that we can make our code more readable and easier to maintain.

We'll also be spending some time looking at "not bad" code to see how we can use a few techniques to make it more approachable to other developers (or even yourself 6 months down the road).  If you want to get a sneak peak at this refactoring portion, you can check out a video of it: Clean Code: The Refactoring Bits.

Hope to see you at an upcoming event!

Happy Coding!

Sunday, July 14, 2013

Refactoring Question

Earlier today, I got a question through Twitter in response to my recently published video: Clean Code: The Refactoring Bits.  Since I can't answer adequately in 140 characters, I thought it would be better to answer here.

What is the best way to refactor C# code containing goto statements?

It depends.

This is my standard answer to pretty much everything.  It's nearly impossible to answer a question like this without further context.  I tend to stay away from the words "always" and "never" just because they tend to over-simplify things.  And the real world is never simple.

As an example, I have heard of developers who say that say we should never use a "switch" statement; instead, we should use the Strategy Method pattern.  A dramatic over-simplification.

I'll say the same thing here.  The "goto" statement has fallen out of favor over the years.  The primary reason is that it tends to make code more difficult to follow.  And in the circles I've been in, the developers don't even know the C# syntax off the top of their heads.  But just because you run across a "goto" doesn't mean it must be changed.  Again, it depends.

Refactoring Resources
I'm definitely not a refactoring expert, but I will point to some resources.

The first is Working Effectively with Legacy Code by Michael C. Feathers (Jeremy's review).  The thing that I really like about this book is the emphasis on unit testing.  Before doing any refactoring, we need to bring the current code under effective automated testing.  This way, when we start our refactoring, we get nearly immediate feedback if we inadvertently break something.

This is something that I show several times in the refactoring video.  If our refactoring goes awry, our unit tests let us know about it right away so that we can take action.

There are two other books that are generally recommended: Refactoring: Improving the Design of Existing Code by Martin Fowler and Refactoring to Patterns by Joshua Kerievsky.  Both of these books are currently in my library, but they are still in the "To Be Read" pile.  I've flipped through both of them and see lots of useful advice, but I haven't actually sat down to read them yet.

These resources will help get us headed in the right direction.  But, ultimately, like every other situation that we deal with in programming, what we actually should do depends on the particular situation.

Happy Coding!

Screencast for Clean Code: The Refactoring Bits

New video available: Clean Code: The Refactoring Bits

New Screencast
One of my latest presentation topics is Clean Code: Homicidal Maniacs Read Code, Too!  One problem is that I usually run out of time during the refactoring portion of the presentation (there's always too much good stuff to talk about).  We always get through the important bits: intentional naming and hierarchical methods, but it's nice to be able to see multiple examples to reinforce the concepts.

To remedy this, I put together a screencast of just the refactoring portion: Clean Code: The Refactoring Bits.  As with all of my presentations, there is a PDF walkthrough of the session available on my website at the link above.

Live Presentations
The Clean Code session has received a good response from folks who've attended.  If you want to see it live, be sure to stop by one of these upcoming events:

Saturday/Sunday, July 27-28, 2013
So Cal Code Camp
San Diego, CA

Thursday, August 22, 2013
Southeast Valley .NET User Group
Chandler, AZ

Saturday/Sunday, October 5-6, 2013
Silicon Valley Code Camp
Los Altos Hills, CA

These are the events I currently have on my schedule; I'm sure there will be others as well.  If you'd like me to come to your user group, Code Camp, or other event, feel free to send in a request through INETA or contact me through my website.

I hope to see you at an upcoming event.

Happy Coding!

Friday, July 12, 2013

I Didn't Expect That

My C# Interfaces course launched on Pluralsight last week.  The interest in the course has been much higher than I expected.  And today, it's showing up at the top of the leaderboard (at least for now):

You can see the live list here: Pluralsight Top 100 Leaderboard.

Helping Developers
The most exciting part of this is how many people are getting benefits from my course. For those of you who've seen me speak in person, you know that I really love to share information with other developers.  What really drives me forward is when I get an email from a dev who tells me that he/she was able to make use of something learned from one of my presentations.  It's also great to get an email from someone on the other side of the world who was able to use one of my articles.

I'm focused on helping developers take a step up.  So, it's very cool to be able to reach so many developers through a single source.

I'm available to help you.  If you're looking for training (single day, multi-day, or ongoing) or for someone to speak at an event such as a "Lunch & Learn", user group, or developer conference, contact me through my website.

Check It Out
If you haven't taken a look at Pluralsight, spend a little time and look through their catalog.  There are hundreds of courses on all different technologies.  If you just browse the categories, you'll see a huge variety to choose from.

Everyone learns best in different ways.  Books are my preferred way of learning.  But some people like blog articles, some people like trial-and-error experimentation, some people like videos, some people like live demos, and some people like one-on-one training.  If you are a "video" or "live demo" person, Pluralsight is a great resource.  They offer a 10 day free trial, and this gives you a chance to check out the quality of the courses for yourself.

More to Come
I'm currently working on my next course about one of my favorite things: the BackgroundWorker Component.  It's a great little tool that's easy to work with.  And even though some people say that it's no longer necessary, it definitely still has its place.

So, stay tuned.  There's definitely more to come.

Happy Coding!

Sunday, July 7, 2013

Changing Culture in WPF

I know my blog has been a bit empty over the last 6 weeks or so.  I've been working heavily on my C# Interfaces course for Pluralsight which released last week.  So now it's time to catch up on some articles that I've been intending to write.

This time around, we'll look at a bit of a hack that makes changing the culture in a running WPF application a bit easier than the majority of the solutions out there.  The sample project can be downloaded here:

Using the Machine Culture is Easy
.NET provides us a fairly straightforward way to support different languages and cultures in our applications. By default, our applications use the culture for the machine that they run on.  This means that if we provide resource files with different strings (or images or whatever) that are appropriate for a language, we get the behavior basically for free.

For example, we can provide a resource string in a resx file:

We have resource files set up for "en-US", "en-GB", and "en-AU":

Then in our XAML code, we just need to reference that resource string rather than providing a hard-coded string:

Notice that our "Text" property of this TextBlock references the static "Greeting" string resource.  So, when our application runs, it will automatically get the culture-specific value.

Here's the output:

And we can see "Howdy, Y'all!" is used in our TextBlock.  If our machine is set to a different culture, then we would get that culture-specific string (or the default culture if it's not available).

Note: This isn't a tutorial on how to localize your application, so you'll need to dig into that yourself.  We're just getting the basics in place so we can look at the "hack".

[Update Jan 2014: If you do want to learn how to localize an application in .NET, you can check out my Introduction to Localization and Globalization in .NET course available on Pluralsight.]

Changing the Culture is Hard
So, we've seen how easy it is to use the machine culture.  And, in fact, it's not hard to put in a custom culture (different from the machine) as the application is starting up.  But if we want to change the culture while the application is running, we run into a bit of a problem.

The "free" behavior that we get above (culture-specific resource strings from a file) only happens when the WPF window is being created.  This means that even if we change the culture of our thread while our application is running, the open windows will continue to use the already-bound resource strings -- no automatic updates.

The Scenario
The first question you might ask is "Why do we want to change culture in a running app?"  Well, I ran across this issue while helping a friend working on a project.  He was building a kiosk application in WPF that needed to support multiple languages.  The idea is that the user would walk up to the kiosk, press the button for the language they wanted, and then go from there.

If you cruise the internet, you will come across some interesting solutions.  Some people have built libraries where you call a method to rebind all of the resources of an open window.  I'm not a big fan of this solution just because it seems overly complicated.  And some of the libraries required you to put an attached property on all of the UI controls.

The most basic recommendation to change the culture of your application is to shut down and restart the app.  The idea behind this is that you update a configuration file with the new culture that you want.  Then you restart the application (which is never as easy as it sounds).  When the app starts up, it uses the new culture from configuration.

The "restart" solution sounded like the better solution of these two, but then I had a kind of crazy idea.

The Application MainWindow Property
In my sample code for my session on Dependency Injection (Dependency Injection: A Practical Introduction), I manually create the MainWindow for a WPF application.

Here's what the simplified code looks like (from App.xaml.cs):

The Application.Current.MainWindow is a property on our application that tells us what the main window is.  When the main window is closed, the application itself shuts down.  In this example, we create a new instance of the MainWindow class (which is defined by MainWindow.xaml) and then assign it to the MainWindow property of the application.  Then we Show the MainWindow.

The effect of this is that the MainWindow class is shown.  And when it is closed, the application shuts down.

So, I started to wonder if we could hack around with the MainWindow property a little bit so that we could simply create a new window (with a different culture) rather than shutting down the entire application.

The Hack: Resetting the Main Window
In the App.xaml.cs file, I added a new static method that would swap out the main window of the application.  Here's the code:

Let's step through this.

First, we set the CurrentCulture and the CurrentUICulture for the current thread.  The CurrentCulture defines the culture that the thread operates on.  The CurrentUICulture determines which resource file is going to be used.  For example, if we set the CurrentUICulture to a CultureInfo for "en-US", it will use the resources that are defined in the "Resources.en-US.resx" file (which gets translated into its own assembly/folder when the app is compiled).

We want to set the CurrentUICulture *before* we create the window.  This makes sure that the correct resources will be picked up.

After setting the culture, we create a local variable ("oldWindow") that points to the currently assigned MainWindow. We grab a reference so that we can programmatically close this window later.

Then we create a new MainWindow instance (again, this is coming from MainWindow.xaml).  This will be created with the resources for the new culture.  We assign it to the MainWindow property, and it becomes the main window for the application.

Next, we show the (new) MainWindow.

As a last step, we close the "old" window -- the one with the previous culture.  Since this is no longer the application's "MainWindow", it does not shut down the application.

The result is that the application will have a noticeable "window opening / window closing" effect, but we've managed to do this without shutting down the application.

The Results
Let's see the result in our sample application.  First, as we've seen, we have a TextBlock that uses the "Greeting" resource string.  In addition to that, we have 3 other text blocks.  In the code, we show the current culture, and we assign a date to display with both the short date format and the long date format.

Here's the code for that:

"displayDate.ToString("d")" gives us the short date format, which is "MM/dd/yyyy" in en-US.  "displayDate.ToString("D")" gives us the long date format, which is "dddd, MMMM dd, yyyy" in en-US.

We also have 3 buttons to change the culture.  Each button is similar.  Here's the click handler for the "US" button:

We can see that this calls the ChangeCulture method we looked at earlier.  This will re-create the window.  The constructor of the MainWindow calls "UpdateUIElements" to put the appropriate values in the text blocks.

Here are the outputs if we click each button in turn:

We can see that the "Greeting" text is different for each window.  Also, the short date and long date formats are appropriate to the culture.

As a bit of a humorous side note: I originally used today's date for the sample.  But since today is July 7, 2013, it would be very difficult to tell the difference between "07/07/2013" and "07/07/2013".

Wrap Up
So, this is a bit of a hack to re-create the main window for a WPF application.  But it is easier than restarting the application with new configuration values.  And with the kiosk scenario, it isn't a problem if we "reset" the entire application when the language is changed.

You might be able to use this same hack in a Windows Forms application (although getting to the application is a little less straight-forward).  It may also work in Silverlight by resetting the RootVisual (but I have not tried that).  I seriously doubt that it would work in a Windows 8 App Store app; this is also based on speculation since I have not done much with those types of apps.

Sometimes we come up with creative solutions to specific problems.  This one probably isn't very widely applicable, but it's fun to see what we can come up with nonetheless.

Happy Coding!

Saturday, July 6, 2013

Clean Code Question: Exception Handling

Earlier this week, I spoke about Clean Code (Clean Code: Homicidal Maniacs Read Code, Too!) and a couple of questions came up that are good to explore a little further.  In the last article, we talked about properties vs. methods.  This time, we'll think a little more about exception handling.

Exception Handling
This question came up during the refactoring portion of the session.  Here's the code before the refactoring:

Notice that there are two places where exceptions may be thrown.  This will result if the dependency injection container is not initialized properly.

As noted in the session, this is not bad code.  The method is short, and there isn't much complexity.  But it does take a little while to figure out what it's doing.  Our goal is to make this readable, so we refactored out two of the "detail" parts into separate methods.

The updated code looks like this:

Now the original "Initialize" method is easier to follow.  It performs 3 actions, and if we need to drill into the details, we can.  But if we don't need the details, we still have a good idea of what this method is doing.

This leads us to the question:
Where does the try/catch block go?
Since we know that this method could throw an exception, shouldn't we have this wrapped in a try/catch block?  And should we have the try/catch in the original "Initialize" method?  Or should it be in the detail methods?

A Global Exception Handler
So, the answer I gave is that we don't catch exceptions here, we have a global exception handler that takes care of that.  For this application (which is based on a production application), the scenario is that if we have a problem on the client-side code, there really isn't much that we can do about it other than log it and reset.

This was just the first implementation of error handling for this application.  If a workflow failed partway through, it would generally be due to a server error.  The client application really doesn't do much beyond display, basic data validation, and submitting to the server.  If there is an error, the application would alert the user that something went wrong, log the error to the logging service, and reset the user application.  This could result in lost (unsubmitted) data, but this was considered acceptable to the business.  If it became a problem, then a more robust solution with client-side storage would be put into place.

Here's an example of a global exception handler.  This is in the "App.xaml.cs" file in the WPF sample:

So, we can see that our sample application would just shut down (and this is highly simplified for this sample).  But this leads us to an important part of exception handling:
Only catch an exception if there's something you can do with it.
Let's explore this a little further.

Catching Exceptions
Back to the original question: should we have a try/catch block in our high-level "Initialize" method, or should we have the try/catch blocks in the detail methods?

The answer is neither.

In this instance, an exception will get thrown if the dependency injection container is not initialized with the required objects.  If the service (IPersonService) is not configured in the container, it will throw an error.  If the model (CatalogOrder) is not configured in the container, it will throw an error.

If the Dependency Injection container is not populated with the right objects, then what can our class (a View Model) do about it?  The answer is nothing.  Our class relies on having a correctly configured DI container.  Someone else is responsible for making sure that happens.

If we caught the exception, what would we do with it?  In this case, there really isn't much we could do.  We could alert the user that there is a problem, and we could log the error, but that's about it.  We can't "recover" from this problem; our View Model will not work.  So, we don't gain anything by trying to handle the error here versus letting the global exception handler take care of things.

We've seen how we should not catch an exception if we can't do anything with it.  But there are times when we want to try again.  For example, if we are making a service call, we may get a TimeoutException.

In that scenario, we could catch the TimeoutException locally, wait a few seconds, and then try the service call again.  If we fail again (or maybe after a few more tries), then we will simply let the exception propagate up to our global exception handler.

Wrap Up
Exception handling is a big topic.  There are a lot of different approaches.  Our primary focus is that our application behaves appropriately.  There may be times that the risk of data corruption is high and we want to simply abandon all of our uncommitted changes.  There may be times that our application is left in an inconsistent state, and we need to try to reset it somehow.

And there may be times when we can handle the exception by trying again or by alerting the user of a change that he needs to make in order for the transaction to succeed.

What our simple sample shows is that we don't always need to handle exceptions locally.  There are times where it is appropriate to let an exception propagate up to the next level.

Exceptions in .NET are an example of the Chain of Responsibility pattern.  For more information, check out "Learn the Lingo: Design Patterns" that talks specifically about Exceptions and the Chain of Responsibility.  We just need to make sure that our exceptions don't drop off the end of the chain.  Something needs to be there to pick up any unhandled exceptions.

Happy Coding!

Friday, July 5, 2013

Clean Code Question: Properties vs. Methods

Earlier this week, I spoke about Clean Code (Clean Code: Homicidal Maniacs Read Code, Too!) and a couple of questions came up that are good to explore a little further.  We'll talk about properties here.  In the next article, we'll think a little more about exception handling.

Properties vs. Methods
The first question had to do with the refactoring of a conditional.  Here's the original code:

It's easy to see what this block is doing (checking to see if something is more than 10 seconds old), but it doesn't really tell us why.  In following our principle of intentional naming, we want to make the code a bit more clear.  So, we created a property called IsCacheValid wrap the details:

Now, we can tell that this conditional is checking to see if the cache is valid.  If we need details on how that decision is made, we can drill into the property.

So, the question came up:
Why use a property here instead of a method?
A very good question.  My answer was that it didn't really matter either way and that I chose a property to show other ways of wrapping details other than just methods.

That's mostly true from a "wanting to show stuff" standpoint of this particular session, but there's a little more consideration to give this.

Let's see what this same code looks like as a method:

There's not that much difference.  Just a few syntactic changes: (1) adding parentheses and (2) removing the "get" block.

Is There a Performance Difference?
Our first concern is to see if there is a performance difference.  We know that Properties are really just methods in disguise (Explained: Properties in .NET or video).  And if we were to explore the IL, we would see some (but not many) differences between the two.

Realistically, even though there are technically some differences that may affect performance, this code will not see any noticeable difference.  Remember where this code is: it's in a view model.  This is part of the code our users interact directly with.  In this scenario, the slowest part of this application is the user.  So, we don't need to worry about differences between 10 or 12 clock cycles affecting real-world performance.

Now, if this were in a tight loop or the functionality was called repeatedly (hundreds or thousands of times per second), then we would really need to dig in and see what the performance is.  But in this case, the difference is undetectable.

Is There a Readability Difference?
So, now that we've decided we don't need to be concerned about performance differences, we need to focus on the readability of the code and what developers expect to find.

Since the conditionals end up being almost identical, it's hard to argue that one is easier to read than the other.



So, we'll decide that the physical readability is the same either way.

What do Developers Expect?
The last thing to consider is what would a developer expect to see.  Remember, our goal here is to have code with no surprises.  We want to make it as obvious as possible.  The code should be easily readable by a developer who is not entirely familiar with the details of the application.

So, the only argument that I would have to prefer a Property over a Method has to do with the naming. As discussed in the session, we prefer to have nouns for "things" in our code (classes, properties, parameters, variables).  And we like to have action verbs for our methods and functions.

There is one more state that we talked about: it is common (especially in the XAML world) to have properties that are state verbs.  Some examples would be "IsReadOnly" and "IsEnabled" that we have on a number of UI controls.  These aren't action verbs, they are simply a way to query the current state of an object.

We followed this same naming convention with the "IsCacheValid" property name.  So, in this instance (with this particular name), I would prefer for this to be a property rather than a method.  But we could just as easily change the method name to something more appropriate.

Wrap Up
We've seen that when we're working in the user code space, it doesn't really matter whether we use a property or a method to wrap up coding details.

We do need to be aware of a few standard guidelines regarding properties, such as, we don't want to put "slow" code into properties.  Developers expect properties to return quickly (and definitely not asynchronously).  So, we should not put things like database calls or network calls into properties.  And we should not put processor intensive code into properties -- in cases where we "get" a property many, many times, this can add up.

As always, we need to be aware of our environment.  We need to keep our code unsurprising to other developers.  And we need to make sure that we weigh the pros and cons for the decisions that we make.

The more we understand, the better able we are to make those decisions.

Happy Coding!

Tuesday, July 2, 2013

New Pluralsight Course: C# Interfaces

As mentioned about six weeks ago, I've been working on a course for Pluralsight.  I'm happy to announce that the course is now available.

C# Interfaces
Do you want code that's maintainable, extensible, and easily testable?  If so, then C# interfaces are here to help. In this course, we’ll take a look at how we can use interfaces effectively in our code. We'll start at the beginning ("What are interfaces?") and then explore why we want to use them. Along the way we'll create and implement own interfaces, see how to explicitly implement interfaces, and take a look at dynamic loading, unit testing, and dependency injection. All of which is made possible with interfaces.
Check out the course for yourself at Pluralsight: C# Interfaces.

Happy Coding!