Quick access to useful documents inside Visual Studio

Here’s one of those little tips that can save you time and useless brain processing when the need arises.  When developing in Visual Studio, does it ever happen that you need to read some documentation pertaining to your current work?  In my case it happens a lot.  I don’t like to switch context and fire up a web browser to find the needed documentation, or even launch Windows Explorer to find that document in some obscure, deep directory hierarchy.  No, instead I like to have everything I need, whether tools or documentations, under my fingers in one place: inside Visual Studio. 

Two documentations that I use the most when programming in .NET are the ReSharper 4.5 Default Keymaps and the C# Language Specification (ECMA-334).  In order to quickly access those two documents (and future documents I might need), I simply created an entry in the External Tools section of Visual Studio.  In order to do this, you can follow these simple steps:

  1. Go to Tools -> External Tools…
  2. In the External Tools window, click on the Add button to create a new entry
  3. Fill in the required information, such as Title, Command, Arguments, etc.  In my case, the Command is simply the path to the executable of my favorite PDF reader (Foxit Reader) and the Arguments is simply the path to the PDF file.  You can also define a keyboard shortcut for them by prefixing the “&” symbol to one of the letters that aren’t already defined as shortcuts. 
  4. When you’re done, click on OK

Take a look at the following screenshot:

With this little setup, I don’t need to go to either the ReSharper or ECMA’s website, not even launch Windows Explorer to look for those files.  I have access to those files directly from Visual Studio.  No more context switching.

Three talks you should watch this week (Series #1)

Whenever I can’t get myself too tired to go to sleep, or I’m on the bus commuting to work or to a client, or plain simply have an hour or two open in my schedule, I often fill it up watching a few talks online.  Though I’m passionate about software development and technology in general, I don’t always focus entirely on it, as it isn’t very fulfilling for the imaginative mind.  Recently, I’ve listened to some great talks about technologists speaking about starting online businesses, marketing, life, faith, etc., which really pump me up to a level that makes me thankful to live, to dream and to achieve what I value most in life.  I’ll start making a series out of this one, as I believe it can be as helpful and motivating to you, as it is for me.  That being said, here are the first three talks I recommend you to watch this week:

  1. David Heinemeier Hansson on The Secret To Making Money Online (less than 30 minutes)

In this talk given in 2008, David Heinemeier, the creator of the Ruby on Rails framework and partner at 37Signals, gives a very creative and down-to-earth talk on how to create a profitable startup company.

  1. Guy Kawasaki on The Art of Innovation (less than 60 minutes)

This is the first time I heard Guy Kawasaki speak.  This guy is a one of my “online heroes”.  He’s smart, he’s funny, and he speaks from experience.  In this talk, Guy talks about innovation about products, services and marketing.  He shares his experience from his work at Apple to now as a venture capitalist.  You’ll also learn about the 10-20-30 rule that can increase your chances in not only getting fund for your business, but most importantly, getting your point across.

  1. Joel Spolsky on What Makes a Great Software (less than 60 minutes)

This is a talk that Joel Spolsky, founder of Fogcreek Software, gave as a keynote at RailsConf 2008, where he shares his valuable insight in what really makes a great software, so much so that we can actually qualify the software as great.  His talk is fantastic: it’s entertaining, it’s focused and it’s without a doubt an eye-opener for software developers to watch out some common pitfalls that can make your software not being adopted at all by potential users.

The Architectural Journal, a quarterly journal about software architecture

image Microsoft has many valuable resources for .NET developers under its MSDN umbrella: newsgroups, blogs, forums, magazines, etc.  One very valuable resource from Microsoft that seems to be ignored by most developers is The Architectural Journal:

The Architectural Journal is an independent platform for free thinkers and practitioners of IT architecture.  New editions are issued quarterly with articles designed to offer perspective, share knowledge, and help you learn the discipline and pursue the art of IT architecture.  The Architectural Journal reaches over 67,00 subscribers worldwide.

I think one reason that it isn’t getting much attention is because its “feedless”, meaning you can’t directly subscribe to a feed, through your browser, that will notify you whenever a new issue has been published.  So in order to get notified when a new issue has been published, you need to subscribe through a fairly simple, but tedious, subscription workflow.  Once subscribed, you’ll get the quarterly journal as a PDF as soon as it’s released.  In short, here are the steps you should follow in order to subscribe to The Architectural Journal:

Go to the e-newsletters page in the Profile Center.  You may be required to sign up for a Windows Live ID account if you don’t have one already.  You may use your current email account or create a new one if you don’t have one.  From there, you follow these three steps:

  1. Find The Architectural Journal in the list of available communications on the left and select it.
  2. Press the Subscribe button.  You should now see your choices in the list on the right.
  3. Select your delivery format: HTML (suggested) or plain text.

(Note: it would’ve been much easier had someone put an RSS feed link instead.)

So that’s it! Now, you should be getting four issues per year.  All great content about software architecture topics.  All free.  Past topics include:

You can also skip the whole subscription process and directly download the current and previous issues in English, French, Spanish, etc., as a compressed (ZIP) file.

My five favorite features in ReSharper 4.5

With the recent release of ReSharper 4.5, many productive features have been added to this already great product, such as performance and memory usage improvements, solution-wide code inspections, VB9 support, and many more.  I’ve been using ReSharper as my pair programmer for many years as it helps me to enhance my C# refactoring whenever I overlook some portions of code I’m writing, as well as to manage my unit tests.  In this post, I will concentrate on sharing with you my five most favorite new features in ReSharper 4.5.

1. Find dependent or referenced code

Using this new feature, you can find dependent or referenced code at either a project or file level.  Before going forward with this feature, it is important to understand what is meant by “dependent code” and “referenced code”.  Both of these terms have to do with dependencies/coupling.  When you ask ReSharper to tell you the dependent code at the project level, you are actually asking it to tell you which other projects (or assemblies) are dependent on that specific project.  On the other hand, when you ask ReSharper to tell you the referenced code at the project level, you are asking it to tell you which other projects (or assemblies) that specific project depends on.  For example, suppose the following UML class diagram:

In this scenario, I have four different assemblies: one client console executable (Client), and three class libraries (Provider, Utilities and SecurityManager).  Our Client executable references the three other assemblies because it’ll make use of their services.  Those references were created when I asked Visual Studio to add me the references for those three projects at the project level.  Now, if I were to ask ReSharper to tell me the dependent code at the project level (which means that you right-click on the Client project in the Solution Explorer, and then click on the Find Dependent Code contextual menu item), a message box will appear telling me that “Code dependent on project ‘Client.csproj’ was not found”: 

This is normal, because according to our class diagram above, Client has an afferent coupling of zero (Ca = 0). 

Afferent coupling(s) is the number of class(es) outside this component (i.e., Client) that depend on classes within this component (i.e., Client). 

On the other hand, if we were to ask ReSharper to tell us the referenced code at the project level (for Client), by this time clicking on the Find Referenced Code contextual menu item, you will get the following results:

In this case, ReSharper is telling us the types which are being used in that specific project (Client), even .NET types and assemblies like mscorlib.dll.  Since the Client class has a positive non-zero efferent coupling (Ce > 0), we actually get a result.

Efferent coupling(s) is the number of classes inside this component (i.e., Client) that depend on classes outside this component (i.e., Client).

These results could look daunting at first sight, but that’s because the results window is showing too much information.  All you have to do to get a more simplistic and lighter view of the results is simply to click on the Filter Usages button (that’s the one surrounded in red in the screenshot below) and unselect the Show Attribute Usage from the proposed choices, as you don’t really care that you’re depending on the AssemblyAttribute class for example.  Furthermore, you should also click on the Merge Occurences on the Same Line button (that’s the one surrounded in green in the screenshot below), so that you eliminate some of the redundancy usages on the same line.  Finally, choose an appropriate view to group your results (in this case, I have chosen to group the results by Namespaces and Types.  That’s the one surrounded in blue in the screenshot below).  This will give you the following (much more compact) result view:

NOTE: If you only reference external projects or assemblies in a project without actually using the public types or members in those external dependencies, ReSharper will not tell you that you are actually referencing those dependencies.  This is pretty slick, as you can visually know whether or not a reference is unnecessary, and thus proceed with its removal.

Ah, much better! And you know what?  That’s pretty much right, because the Client class is actually using those classes (Provider, SecurityManager and Utilities), as shown in the screenshot below:

At the file level, you only get to ask ReSharer to tell you the referenced code, through the Find Referenced Code contextual menu item.  In this case, the results will include any type being used in that file.  Suppose for example that in the SecurityManager class, you’re using an instance of a Logging class to log some errors in a few critical methods.  In that case, the results will include the Logging class, as it is a type being referenced in that file.  So far, so smart.

2. Go to implementation (Ctrl+Shift+Alt+B)

This one is pretty simple and very much useful.  Suppose you have the following class hierarchy:

image

In the previous versions of ReSharper, you couldn’t ask the tool to directly tell you which concrete classes derived from an abstract type.  Instead, you had to select the abstract type and ask it to tell you the derived types (or inheritors) through the Ctrl+Alt+B shortcut, which would give you a list of all the types deriving from that abstract type…even if those derived types were abstract themselves.  This was pretty frustrating when you had a hierarchy with a lot of abstract relationships amongst types, as it was the case in one WCF-driven project I was involved in, because you would lose a couple of seconds filtering out the concrete types from the abstract ones in the results list.  Well, that’s an old story because now you can get the list of all the concrete types (or implementation types) directly from a new shortcut: Ctrl+Shift+Alt+B, or through the “Go to implementation” command in the “Go to” navigation menu.  For example, if you asked ReSharper to tell you the concrete classes for IProvider, it’ll tell you that MembershipProvider and SecurityProvider are the only ones.  It will ignore ProviderBase, as it is abstract.  Well done!

3. Naming styles

With ReSharper 4.5, we get more flexibility in the naming style department.  You can apply either a common naming style for both C# and VB code, or set one differently for each of them.  It’s up to you.  The UI interface to manage the naming styles is pretty simple.  Here, for example, is the Naming Style window pertaining to both C# and VB:

So you get a list of predefined styles out-of-the-box which might suit most of your basic needs.  The flexibility offered by these features comes in handy when you want to create new styles, modify some existing ones, etc.  Suppose you want to add a new naming style for private fields only, and make them prefixed by an underscore.  You would simply click on the “Add” button under the User defined naming rules panel, which will show the following window:

 

All I have to do is select the affected entities, which in this case would be “Field” and “Readonly field”.  Then I would specify the access modifiers, which sould be Private and Protected. Following that, I will specify the underscore as the name prefix and tick the lowerCamelCase naming style, as to be follow the .NET design guidelines.  Finally, I would set the rule description to something explicit, such as “Private fields”.  That’s it!  Now I can save and share the code style file with my team.

4. Collapse all project nodes (in Solution Explorer)

Suppose you have the following project structure in Solution Explorer:

This would be a very typical folder structure in an ASP.NET MVC project, for example.  Every time you collapse the node associated with the SecurityManager project, and you expand it later, you will see the same result as above.  This can be very frustrating when you have dozens of projects with their child nodes expanded in a similar way in Solution Explorer, and God forbid you have also expanded the References node, because it tends to visually pollute the Solution Explorer.  ReSharper 4.5 introduced a new feature that allows you to definitively collapse a node, be it a folder or the project node itself, so that the next time you expand the root node, the previously collapsed node stays closed!  This might sound like nothing, but have you ever calculated how many seconds you probably were wasting trying to navigate the Solution Explorer when you have a multitude of projects with folders, or solution folders, all open at the same time even though you don’t really need them to be?  That’s not being productive.  That’s not being professional.

So here’s the trick: when you’re done with one node and you need to collapse it for good, simply right-click on it in the Solution Explorer, and choose “Collapse All”.  This would permanently collapse the node until you explicitly expand it again.  For example, if I decide to execute this “Collapse All” command on the Users folder, then each time I expand the SecurityManager node, the Users folder will stay collapsed, until I explicitly expand it.  In my opinion, this should’ve been a standard option for Visual Studio.  Good thinking once again!

5. Inline field (Ctrl+Alt+N)

The fifth of my favorite new features in ReSharper 4.5 is the possibility to inline a field.  As to tweak the original Inline Temp refactoring definition to suit this one:

You have a field that is assigned to once with a simple expression, and the field is getting in the way of other refactorings.  Replace all references to that field with the expression.

I think that little definition sums it up well what Inline Field does.  Simply highlight the field, then hit the Ctrl+Alt+N shortcut, and you’re done.  Here’s a last example.  Suppose you have the following class definition:

As you can see, the someString field is used only once in this class, which is pretty much useless.  In that case, I will place my cursor on it, then hit Ctrl+Alt+N to have it inlined:

And that’s it! Now through all the code, the field’s expression will be inlined.  This was a simple scenario, but I’m sure you can think how useful this refactoring could be in your codebase.

[UPDATE: 2009-04-14] The Inline Field refactoring also works to inline methods and properties, not only fields! This is very sweet.  They should call this command Inline Construct as it doesn’t just inline fields.

But there’s more!!!

Of course, my list of favorite new features in ReSharper 4.5 isn’t the whole story behind this new release.  For a complete list of new feature in ReSharper 4.5, I’ll invite you to review its What’s New in ReSharper 4.5 features page. ReSharper is getting better and better through each release, and I can’t wait to see what the team is going to include in the 5.0 release.  But meanwhile, if you haven’t upgraded to this new version, I urge you to do so.  Plus, the upgrade is free if you’re already a ReSharper 4.x licensee, so you really have no excuse.  And if you’re not currently using ReSharper at all, then I hope that the following post has incited you to ask your tech lead or manager to get a license for it (I would suggest to start with the trial, then demo it to your group).  I’ll also invite you to read my post on The Case for ReSharper in the Enterprise which might give you some pointers on the necessity of this tool in your development toolbox.

Book Review #10: 97 Things Every Software Architect Should Know

image

What started as an article a few years ago, titled 10 Things Every Software Architect Should Know, has morphed into a collection of essays written by software professionals and for software professionals. The author of the original article, Richard Monson-Haefel, did well on following the suggestion of Jay Zimmerman to publish a book as a collection of essays sharing pragmatic experience, wisdom, insight and diversity in the field of software architecture.  From the back cover, we can read the following:

In this truly unique technical book, today’s leading software architects present valuable principles on key development issues that go way beyond technology.  More than four dozen architects - including Neal Ford, Michael Nygard, and Bill de hÒra - offer advice for communicating with stakeholders, eliminating complexity, empowering developers, and many more practical lessons they’ve learned from their years of experience.

Published by O’Reilly, “97 Things Every Software Architect Should Know” turns out to be authored by a multitude of different people from around the world and from diverse companies.  The common point of interest amongst all the contributors is their role on the job, that of a software architect.  As the title suggests, there are in fact 97 different essays written by many practicing software professionals that were willing to share their experience, wisdom, proven techniques, mistakes, lessons learned, etc., about their profession and role of that of a software architect.

But what exactly is a software architect?  Though there isn’t a specific definition for that title, there are many accepted ones.  According to Wikipedia (source),

Despite the lack of an accepted overall definition, the role of software architect generally has certain common traits:

Strategic thinking
Architects address the technological aspects of business needs by considering what a given technology can contribute to the overall functions of the system, as distinct from how that technology will perform its own functions.  This encourages opportunities for re-use of the technology and ultimately contributes to the organization’s efficiency.

System interactions
Architects deal with the interactions of systems, whether between components written in different languages at different time and at different locations, or between components of the same software system that use the same coding language.

Design
The architect makes high-level design choices much more often that low-level choices.  In addition, the architect may sometimes dictate technical standards, including coding standards, tools, or platforms, so as to advance business goals rather than to place arbitrary restrictions on the choices of developers.

Communication
Architects also have to communicate effectively, not only to understand the business needs, but also to advance their own architectural vision.

As there are many different traits pertaining to software architecture, there also many different roles a software architect can play, be it: Enterprise Architect, Application Architect, Infrastructure Architect, Security Architect, etc.  As the author acknowledges,

“97 Things Every Software Architected Should Know” provides advice from software architects around the world on everything from how to avoid common pitfalls to how to build talented teams.  It’s a smorgasbord of advice from established software architects for other software architects or those who aspire to become software architects.

Throughout the book, you will find many essays dealing with at least one of these traits and some specific to a role.  The essays aren’t categorized in any way, so each one you read can deal with something different than a previous one, which might be a good idea…or not.  I would’ve preferred if the essays were categorized by traits (or other subject) so that I can focus my reading on a group of them when I want or need to.  For example, if I want to read some essays pertaining to effective team building, I could focus on reading a subset of those essays.  As it stands, I have no much choice but to read each of them sequentially, which can become quite tedious as some essays can be lightly equivalent to another in terms of idea and interest.  Nevertheless, since the content of the essays are rich, insightful and resourceful, I don’t mind too much about the overall layout.  On a last note about the structure of the book, I was very pleased to see that each essay was presented on a two-page presentation (left page and right page).  In other words, if you turn a page, you get a new essay.  At the end of each essay, you also get a brief bio of the author who wrote it so that you can either stalk him…or Google him.  Finally, there aren’t only male authors who contributed in this project.  As a matter of fact, Allison Randal and Rebecca Parsons (CTO of ThoughtWorks) also contributed their own insights.

Many of the co-authors that participated in this project were unknown to me, so reading this book actually allow me to plug into the world of some them through their personal websites or blogs.  Amongst the list of people who contributed to the book are Erik Doernenburg, Udi Dahan, Niclas Nilsson, Neal Ford, Keith Braithwaite, Gregor Hohpe, and many, many more.  Funny thing is that two articles that I very much enjoyed  much reading were written by a guy I’ve never heard of before: Timothy High, a software architect working for Sakonnet Technologies.  In fact, he’s the author of two of my favorite essays in the book: the first one being Empower Developers, in which he urges managers and architects to essentially “protect developers from nonessential parts of their job.  Too much paperwork and too many office chores add overhead and reduce their effectiveness.” and making sure developers have the tools, the skills and the trust necessary to get the job done; and the second one being Record Your Rationale where he suggests that architects should write down their rationale behind some of their technical decisions, as it may come in handy in a number of situations, as he writes:

  • As a means of communication to developers regarding important architectural principles that should be followed
  • To get the team “on the same page,” or even head off a mutiny, when developers question the logic behind the architecture (or even to humbly accept criticism if it turns out a decision doesn’t hold up under scrutiny)
  • To show managers and stakeholders exactly why the software is being built the way it is (such as why an expensive piece of hardware or software is necessary)
  • When handing off the project to a new architect (how many time have you inherited a piece of software and wondered exactly why the designers did it THAT way?)

Another interesting thing about this book is that O’Reilly agreed that all of the content of the essays should be freely available (Creative Commons) for to anyone through the book’s website.  Excellent idea, O’Reilly!

In essence, this book is all about software architecture, but not only for software architecture, but rather anyone involved in the software development lifecycle (testers, developers, QA, analysts) and even up the corporate ladder (CIO or CTO).  The content being technology-agnostic, there’s no doubt that the audience for this book will be heterogeneous, so whether you’re a .NET, Java or Ruby fan, you will surely find the essays valuable.  And just like the Head First series, this book has sprung another series focused on a “97 Things Every [fill in the blank] Should Know” idea.  [Note from my wife, the environmentalist: “There goes more trees!”].  If you’re a developer aspiring to take on more responsibilities and challenges for a software project, I would highly recommend you get a copy of this book.  Furthermore, I would also recommend reading a good complement for this book: “The Role of an Architect” published by The Architectural Journal (Microsoft).

[UPDATE: 2008-04-15] You can also read the other proposals which didn’t make it to the final cut.

Published my first Windows Live Writer plugin: Amazon Book Linker v1.0

Well, after using Windows Live Writer as my default blogging platform for quite some time, I decided to play around with the provided API to build a little plugin which will speed up the process of finding and linking books from Amazon directly to a blog post.

Amazon Book Linker v1.0 is a free plugin for Windows Live Writer which provides many innovative functionalities for searching and linking books from Amazon on your blog post.  It allows you to specify your own Amazon Associate Tag to every link (you only have to provide this information once, and the plugin will remember it next time) so that you can make a sales commission out of a direct sale from one of the links.  Furthermore, it empowers the HTML ninja (or ninjette) to also customize the HTML template to better match the link layout to your own design.  In order to assist you with this process, the plugin also lists you a series of predefined macros to use.  You can also choose your preferred Amazon locale (US, CA, CO.UK, JP, FR or DE) too!

For more information, I’ll invite you to check the brand new Projects page on this site.  Meanwhile, here are a few screenshots.

image

image

Now that this little project is out the door, I can resume posting new ideas on our beloved craft and technologies. :)

Dear VB Developer…

Whenever someone coming from a VB6 background asks me which language they should adopt to learn .NET, I recommend them C#.  I know that, intuitively, I should tell them to embark the journey with Visual Basic.NET (VB.NET) since that language should already be familiar to them.  However, the familiarity of the language is mostly a costume on its own, since underneath it lives a totally different beast.  The VB.NET compiler now speaks a very different language than its VB6 cousin did: the language of the object-oriented paradigm.  Though the first release version of Visual Basic for the .NET platform was an increment of VB6’s, Visual Basic v7.0, I consider it to be more of a v1.0, because it’s much more than a major revision.  Yes, the language is very much the same, but not the compiler.  According to Microsoft,

Visual Basic .NET is not Visual Basic 6 with inheritance tacked onto it.  Rather, Visual Basic .NET has been entirely rewritten to be fully object-oriented.” For a programming language to be a true OOP language, the language must meet the following criteria:

  • Abstraction: Abstraction manages the complexities of a business problem by allowing you to identify a set of objects involved with that business problem.
  • Encapsulation: Encapsulation hides the internal implementation of an abstraction within the particular object.
  • Polymorphism: Polymorphism provides for multiple implementations of the same method.  For example, different objects can have a Save method, each of which perform different processing.
  • Inheritance: The excitement of Visual Basic .NET lies in inheritance.  Visual Basic 5 introduced the concept of interface inheritance, which allows you to reuse the interface of a class, but not its implementation.  Visual Basic .NET provides for true implementation inheritance whereby you can reuse the implementation of a class. [Source: MSDN]

Chances are that a VB6 veteran, that has been programming with VB since its earliest versions, will tend to write VB.NET code in a more traditional “procedural” way, instead of an “object-oriented” way. This is sad because .NET itself is not only built around, but also provides a rich object-oriented model for programming.  However, that doesn’t rattle my cage too much, because with enough practice and mentorship, they could learn to embrace the OO way of analysis, design and programming, as well as to appreciate its benefits.  What rather tends to rattle my cage is that I said could (in italic in case you haven’t noticed) because there’s not much out there that benefit Visual Basic (VB6 and VB.NET) programmers to really appreciate the OO paradigm to its fullest.

C++ and Java programmers coming to .NET via C# tend to reap more of the benefits from the platform than VB6 developers do when jumping on the .NET wagon with VB.NET, because they are already minded to the OO way of doing things.  I think the main reason that makes this balance shift more on one side than the other is because there is just SO MUCH MORE resources (open-source projects, books, blog posts, articles, training, etc.) that focus on the C-family languages, such as C++, JavaScript and C# (for the sake of this post, I will also include Java in this family).  OO concepts such as inheritance, encapsulation, polymorphism, and constructs such as interfaces or abstract classes, tends to be very hard subjects to grasp for VB6 and VB.NET developers (on a professional level, I can only support this fact through those same comments I get from VB developers taking my VB.NET courses and from fellow developers at user groups).   The VB development community will be in a much better position to take advantage of the OO model, the same way that C++, Java and C# developers did, if for every OO book, article or blog posts, there would be the equivalent counterpart code samples in VB.  Last time I checked on Amazon, there wasn’t many books focused on design patterns for Visual Basic developers.  However, there is a ton available for C++, Java, C# and even Ruby developers.  It’s hard for VB developers to grasp the essence of design patterns if they struggle to understand the concept of inheritance and polymorphism.

You know what?  Let’s dig a little deeper on the programming books case.  Table 1 shows the total number of books found in Amazon for Visual Basic, C#, C++ and Java:

Table 1. Books results for various programming languages at Amazon.com (search made on March 10th, 2009)

Visual Basic

C#

C++

Java (not JavaScript)

12,788 books

16,527 books

22,248 books

64,158 books


 
This is very shocking, because if my memory serves me well, Visual Basic is much older than C# and Java! I’m going to spare you the proportions for each of these books, because I think the numbers speak for themselves.  However, I do want you to notice something important: if we consider C# and Java being almost equivalent (putting the CLR and JVM aside), that means that VB developers have close to 68,000 books less to read from.  There’s a little “gotcha” in this study though: just for the programming related books for all these languages, Java comes first with 12,241 books, C++ comes at second place with 10,465 books, Visual Basic comes at third position with 6,351 books and C# comes last with 3,884 books.  However, most of the VB books are for VB6 and older versions (and maybe VBA or VBScript).  Joking aside, there’s not even a Head First series on Visual Basic!!! There is though a Head First C#, Head First JavaScript, Head First Design Patterns (Java), Head First Object-Oriented Analysis and Design (Java), even a Head First Rails and Head First SQL!  Here’s my point: some of the most influential books on software development and programming such as Design Patterns (by the GoF), Patterns of Enterprise Application Architecture (Fowler), Refactoring to Patterns (Keriesky), Implementation Patterns (Beck), Domain-Driven Design (Evans), even hardcore .NET books like CLR via C# (Richter) and the Effective C# series (Wagner), without forgetting the books from the Robert C. Martin series (Agile Principles, Patterns, and Practices; Clean Code and Working Effectively with Legacy Code) hold a vast, deep and rich knowledge of the craft of software development that VB/VB.NET developers are mostly ignorant of.  No wonder that I also tend to see more jobs offering for C# developers than VB.NET when it comes to .NET positions.  I don’t know about you, but that’s very unfortunate.  However, this paragraph was mostly about books.  What about tools and open-source projects?

When I teach the intermediate and advanced VB.NET courses, I tell the students that they should take a look at Enterprise Library from the Patterns and Practices Group at Microsoft (watch a video of it here) for it can save them time, cost and effort in common development situations.  I even tell them that it is open source, which means they have access to the code.  However, I don’t get much excitement from their part, mostly because the code is written in C#.  Code reading aside, I haven’t even heard of one VB developer simply using Enterprise Library in his projects.  The same goes for projects like nHibernate, the Castle project, NUnit, even mocking tools like Rhino.Mocks and Moq.  That’s very sad, because by not using some of these tools, VB developers tend to stay far behind common practices such as TDD and technologies like ORM tools.  What doesn’t help also, is that most of the screencasts where you see someone showing a piece of code or an utility, such as TDD with NUnit and Rhino.Mocks for example, the language is more often than not…wait for it…C#.  The only screencasts that I see a couple of developers programming in VB is in DNRtv.  Furthermore, I don’t recall ever seeing a VB example from the guys at CodeBetter.  Worse, I don’t even have one example written in VB in any of my posts!

One H U G E advantage that VB6 (or even VB.NET) developers tend to have when learning C# to program with .NET is that they can also be more comfortable in reading C# and Java books and source code (which the latter being as most important as reading books IMHO).  By doing this, for example, a VB developer having trouble understanding the implementation of a design pattern in VB, can easily learn it from another example written in C# or Java (and perhaps C++ if the VB developer understand the notion of pointers).  The last remark I said in parenthesis is important, because of all the .NET constructs, it seems to me that the one that causes much headaches to VB/VB.NET developers are delegates, which are essentially lists of method references.  It’s one of those concepts that I tend to spend more time on explaining to VB developers jumping to VB.NET, than C++ or Java developers learning C#.

Though there isn’t a simple and easy solution for VB developers in this situation, I can only encourage them to take a look at C#.  By doing that, they will also be more comfortable in exploring the world of Java, and perhaps even play around the JVM and see how it compares to .NET.  As Benjamin Franklin once said,

“An investment in knowledge always pays the best interest”, and

“The only thing more expensive than education is ignorance”.

In his article, “What VB Dev Should Know About C#”, Bill Wagner actually encourages VB developers to learn about C# (and C# developers to learn about VB) by saying that,

Our discussion also covered the need for developers to get out of their comfort zones and learn something new.  Yes, the two languages are similar in features, but there are idiomatic differences between the languages, and some tasks are significantly easier in one language than the other.  In fact, you’ll find yourself much more skilled and much more in demand if you know the best features in both languages, as well as how to build applications that rely on both languages.”

And if what I’m writing about isn’t encouraging you enough to learn a new language, then maybe President Barack Obama can persuade you to learn more than “one language”.

I personally speak three languages (Spanish, French and English) and I’m very grateful that I can speak and write in those languages as it gives me a lot of opportunity to learn and embrace foreign cultures, philosophies, relationships and literature.  On the more technical side, I’m also fluent in C++ (not as much as the other languages though), PHP, Java, C# and Visual Basic.  The same benefits apply here, as I can read code written in those languages and books using examples also written in any of those languages.   I can also more easily conduct code reviews with other developers as I’m in a better position to understand their intent, disregard the programming language that was used.

So next time you’re thinking about starting a new personal project, see to it that you write it in C# (if you’re targeting the .NET framework), or even in Java for a change.  If you struggle, don’t quit.  There are many online language conversion tools out there to translate C# code to VB and vice-versa.  The Pragmatic Programmers once advised developers that they should learn at least one new language every year.  This year, Dear VB developer, make a commitment to learn a new language (I’d recommend C#) as it will make you more valuable and employable, and also more comfortable in learning about new ideas emerging in the world of software development.

Would Your Objects Praise You?

In the book of Psalms, we can read a passage where King David thanks and praises the Lord for making the human body and soul a wonderful creation:

Oh yes, you shaped me first inside, then out;
you formed me in my mother’s womb.
I thank you, High God - you’re breathtaking!
Body and soul, I am marvelously made!
I worship in adoration - what a creation!

You know me inside and out,
you know every bone in my body;
You know exactly how I was made, bit by bit,
how I was sculpted from nothing into something.
Like an open book, you watched me grow from conception to birth
;
all the stages of my life were spread out before you,
The days of my life all prepared
before I’d even lived one day.

Psalm 139:13-16 (The Message)

Though I am not perfect, I am perfectly made.  I did not ask for either a working set of eyes or a complex and functional brain.  Never did it occur to me that my heart would be responsible for pumping my blood or that my lungs would filter the oxygen from the air that I breathe.  I am not a creator of life, but I do create a virtual kind of life, where instead of blood and oxygen there is a complex symbiosis of binary mathematics and electrical pulses.  As a software developer, I do bring life to objects that are responsible for the inner workings of my system.  I sometimes wonder whether the objects and components that we build for our software would thank and praise us in the same degree that King David praised his Creator.

Lately, there has been a popular trend going on in blogs and podcasts around object-oriented programming, notably with the SOLID principles, a composite of acronyms about key design principles introduced by Robert C. Martin.  One of the principles that I adhere stronger than the others is the Single Responsibility Principle (SRP).  According to Wikipedia’s definition,

The single responsibility principle states that every object should have a single responsibility, and that all its services should be narrowly aligned with that responsibility.  [Wikipedia].

In the words of Uncle Bob, aside from a type having a well defined responsibility, it should have one, and only one, reason to change.  Going to back to the human body, we can clearly see that our inner components are highly cohesive and loosely coupled.  For example, when I pick up a broken piece of glass from my kitchen’s floor and suddenly I cut myself on the finger of my right hand, I shouldn’t expect my right eye to go blind.  Nor do I expect the other fingers to stop working!  Of course not!  That’s because I am wonderfully made!  And so are you!  When I cut myself, my body knows how to heal itself and within days I have no scar.  Leaving the “cutting” aside, we can clearly see how the eyes, the nose, the tongue, the teeth, the nails, the hair, the skin, etc., all have a single and specific responsibility, and if one member should stop working, it can be replaced by another compatible member.  For example, we can do heart transplants, lungs transplants, etc.  Given that the human body is so much more complex than any software ever created, how come that when my printer driver stops working, the whole operating system goes down with it?  How come when a component in an application stops working, it affects other components as well?  Take, for example, a tree: it looks very simple on the outside, but inside of it, God has clearly encapsulated the inner workings of the tree.  A tree that’s been around for decades can still grow and participate in photosynthesis.  It’s incredible.  Software systems tend to be replaced every year or two.  Anyhow, I want to keep writing on the topic of single responsibility for an object.

Suppose you have the following simple Car class:

Now, what do you think about the methods (or responsibilities) of this class?  Does it violate the SRP principle?  Here’s a simple test you can do to answer these questions (if you answer ‘NO’ to any of these questions, then you know that your class doesn’t adhere to the SRP principle.  Even better: if the question doesn’t seem to make any sense to you, then it’s a ‘NO’ by default):

  • Can a car change gears by itself?
  • Can a car change a radio station by itself?
  • Can a car drive itself?
  • Can a car idle by itself?
  • Can a car park itself?
  • Can a car start itself?

image Unless you’re the lucky owner of the Knight Rider, you probably answered ‘NO’ to a few of these questions.  For every question or observation you have answered ‘NO’, you should more than likely refactor the class and move some of its responsibilities elsewhere.  But where exactly can you move these responsibilities?  Well, before we dive to some of these answers, let’s see if we can directly some of the original questions pertaining to our Car class:

  • Can a car change gears by itself? ANSWER: Sure, if it has an automatic transmission.  Otherwise, only the driver can shift gears.
  • Can a car change a radio station by itself?  ANSWER: Nope, only the driver (or the passenger) can change the radio station.
  • Can a car drive itself? ANSWER: Not unless it’s KITT!  Only a driver can drive a car.
  • Can a car idle by itself? ANSWER: Sure it can.
  • Can a car park itself? ANSWER: Nope! Only a driver can know how to park a car.
  • Can a car start itself? ANSWER: Uh, no.  Once again, only the driver can start the car.

Do you see how by answering such questions or observations you can better get through a cleaner design?  The pattern is pretty simple too: Can a [type] [action in the infinitive] itself? Though I picked a very trivial example, you could do the same test for any of your classes, e.g., an Order class, an Employee class, an Account class, a Repository<T> class, even interfaces!  Continuing with our beloved Car class, we see that it has a couple of responsibilities it cannot fulfill by itself, because either it doesn’t make sense that it should, or plainly that it isn’t logical for the class to offer those services in the first place.  From our answers, we can also see that we need another class to make all well orchestrated: a Driver class.  The driver should know how to fulfill some of these responsibilities.  How would you associate the Driver to a Car?  You can go with the Dependency Injection pattern on this one if you like, or pick another strategy.

image

So we talked about a few things here: the Bible, Knight Rider and Uncle Bob.  But more importantly in this post, we talked about some easy and simple techniques we can use to determine whether methods or properties (responsibilities) actually belong in the right type.  Unfortunately, following this technique isn’t a silver bullet for every situation!  You must still rely on your experience and wisdom to better answer that question.  If you are part of a team, that’s even better because it is those deep and insightful conversations that actually bring about a much suitable solution.  For example, what if our Car needs some reparations?  Should we create a Repair() method in the Car class or the Driver class?  Well, you can first of all use our little technique to answer this question:

  • Should a car be able to repair itself? ANSWER: Not in this world, that’s for sure!
  • Should a driver be able to repair a car? ANSWER: Well, it depends!  Maybe the driver can repair the car, and if not, maybe we should introduce a Mechanic class that knows how to repair the car.  This is when we should discuss it in front of a whiteboard.

I hope this little tip will help you to better evaluate your design.  And don’t stress too much about it if your design doesn’t follow the SRP or any of the SOLID principles.  Just be thankful that you’re wonderfully made and that you have Google at your disposal.

Avoid calling a virtual or abstract method from a constructor in C#…especially in VB!

Whenever I’m teaching our intermediate .NET development course, I mention to my students the pitfalls of calling a virtual method from a base class’ constructor.  The major drawback of calling a virtual method in such a context is that if a derived class overrides that method, the overridden method will be invoked prior to the derived class’ instance constructor.  This is especially true in C#, and as you’ll see later in this post, it’s even more dangerous to do so in Visual Basic.

The Marker class

For this demonstration, I will be using a custom Marker class that will simply output text in the console.

This is the Marker class in C# (the class is equivalent in the Visual Basic module):

class Marker
{
    public Marker(string text)
    {
        Console.WriteLine(text);
    }
}

The Base class

Let’s kick off the idea with a single C# class (no inheritance whatsoever):

class Base
{
    private static Marker staticField = new Marker("base static field");
    private Marker instanceField = new Marker("base instance field");

    static Base()
    {
        new Marker("base static ctor");
    }

    public Base()
    {
        M();
        new Marker("base instance ctor");
    }

    protected  virtual void M()
    {
        Console.WriteLine( "base M() was called" );
    }
}

Here’s the same class in Visual Basic:

Class Base

    Private Shared staticField As New Marker("base static field")
    Private instanceField As New Marker("base instance field")

    Shared Sub New()
        Dim temp As New Marker("base static ctor")
    End Sub

    Public Sub New()
        M()
        Dim temp As New Marker("base instance ctor")
    End Sub

    Protected Overridable Sub M()
        Console.WriteLine("base M() was called")
    End Sub

End Class

When we instantiate the Base class, we get the following output in C# and Visual Basic.  The main point is that the results are the same whether we instantiate the C# or Visual Basic version of the Base class.

image

image

 

Instantiating a child class of Base in C# and Visual Basic

Here’s now the entire code in C# of the Base class (same as before) and a Derived class inheriting from it:

class Base
{
    private static Marker staticField = new Marker("base static field");
    private Marker instanceField = new Marker("base instance field");

    static Base()
    {
        new Marker("base static ctor");
    }

    public Base()
    {
        M();
        new Marker("base instance ctor");
    }

    protected  virtual void M()
    {
        Console.WriteLine( "base M() was called" );
    }
}

class Derived : Base
{
    private static Marker staticField = new Marker("derived static field");
    private Marker instanceField = new Marker("derived instance field");

    static Derived()
    {
        new Marker("derived static ctor");
    }

    public Derived()
    {
        new Marker("derived instance ctor");
    }

    protected override void M()
    {
        Console.WriteLine( "derived M() was called" );
    }
}

And here are the same classes in Visual Basic:

Class Base

    Private Shared staticField As New Marker("base static field")
    Private instanceField As New Marker("base instance field")

    Shared Sub New()
        Dim temp As New Marker("base static ctor")
    End Sub

    Public Sub New()
        M()
        Dim temp As New Marker("base instance ctor")
    End Sub

    Protected Overridable Sub M()
        Console.WriteLine("base M() was called")
    End Sub

End Class

Class Derived : Inherits Base

    Private Shared staticField As New Marker("derived static field")
    Private instanceField As New Marker("derived instance field")

    Shared Sub New()
        Dim temp As New Marker("derived static ctor")
    End Sub

    Sub New()
        Dim temp As New Marker("derived instance ctor")
    End Sub

    Protected Overrides Sub M()
        Console.WriteLine("derived M() was called")
    End Sub

End Class

Here’s the output generated when instantiating the Derived class in C# and Visual Basic (This is where the fun begins!  Try to notice any difference between the C# and Visual Basic execution before continuing.) :

image

image

As you can see, the order of execution in an inheritance relationship is both different in C# and Visual Basic (regardless of whether or not a virtual/abstract method was called from either constructor).  The danger of calling a virtual or abstract method from a constructor (in C# or Visual Basic) is that the overridden method will be invoked prior to the derived class’ constructor.  If that method tries to access or modify the state of the yet-to-be-fully-constructed object, you might end up with a corrupt or invalid instance.  The worse scenario is in Visual Basic.  As you can see from the results, the overridden method gets called not only before the derived class’ constructor (as it was with the C# version), but also gets called before the class’ instance fields get initialized.  Now, that’s even more dangerous if the overridden method tries to access any of its instance fields because chances are that they will default to Nothing (null in C#) for reference types since they haven’t even been initialized yet!

Referencing a Visual Basic assembly from a C# application and instantiating the Visual Basic version of the Derived type

Here’s another potential dangerous scenario: From a C# application, you reference a Visual Basic assembly that holds the exact same code as the Base and Derived classes shown above.  You then decide to instantiate the Visual Basic version of the Derived class:

static void Main(string[] args)
{
    Console.WriteLine( "From C# Program" );
    Console.WriteLine(  );
    new VBModule.Derived();
}

Here’s the output generated from instantiating the Visual Basic version of the Derived class in the C# application:

 imageAs you can see, it is no longer having the same execution cycle as when instantiating the C# version of the Derived class from the C# code itself.

Referencing a C# assembly from a Visual Basic application and instantiating the C# version of the Derived type

This time, we’ll switch the roles and from a Visual Basic application, we’ll reference a C# assembly that holds the exact same code as the Base and Derived classes shown above.  We then decide to instantiate the C# version of the Derived class:

Sub Main()
    Console.WriteLine("From VB Program")
    Console.WriteLine()

    Dim d As New CSharp.Derived
End Sub

Here’s the output generated from instantiating the C# version of the Derived class in the Visual Basic application:

imageAs you can see, it is no longer having the same execution cycle as when instantiating the Visual Basic version of the Derived class from the Visual Basic code itself.

Conclusion

You should never be calling a virtual or abstract method from a constructor in C#, and even more in Visual Basic, because in either case a derived type will invoke an instance method prior to the object being fully constructed!  In other words, the dynamic linking edition kicks in as soon as you instantiate a class.  According to Microsoft,

When a virtual method is called, the actual type that executes the method is not selected until run time.  When a constructor calls a virtual method, it is possible that the constructor for the instance that invokes the method has not executed.  The constructor should be redesigned to eliminate the call to the virtual method.

As you saw, the execution cycle is different for both languages even with the same codebase.  It gets even more interesting when referencing either assembly (C# or Visual Basic) in either language, because you just wouldn’t know what you’ll get at the other end.  Having a tool like ReSharper can be of a greater benefit in this circumstance as it’ll catch this kind of code and notify you about it.  By default, this situation will be treated as a warning, but I’ll suggest you to treat it as an error as to make it stand out better (ReSharper->Options…->Inspection Severity):

image

The Fuhrer’s take on Scrum, Agile and CI

I hope you’re not working in this kind of organization.  Period.

The History of Microsoft on Channel9

Recently, the folks over at Channel9 have put on a couple of episodes on the history of Microsoft since its inception.  At the time of this writing, two episodes have been uploaded so far, but we can expect more to be released in the near future.  Each episode is pretty interesting as it also introduces other things that were major at that specific time, such as the unveiling of the Shugart 5.25-inch floppy disk drive for $390.  Ouch.  Anyways, since I wasn’t born in the 1970s, it’s a nice thing to see what was going in the computing industry in that period.

TweetDeck not showing up in primary monitor

I’m currently using TweetDeck v0.21b as my default Tweeter client for my Windows Vista machine.  Having a dual-monitor setup at home (laptop and an external monitor), I always move TweetDeck to the external monitor as a personal preference.  While I’m waiting in the airport for my next flight, the sudden idea to tweet that specific fact came to my mind.  Unfortunately, TweetDeck’s UI doesn’t show up when I launch the application.  I know it’s running because I can see the little black bird icon on the system tray, but it still thinks it’s suppose to show on my external monitor.  That’s not good, because I don’t normally carry my external monitor with me when I’m on the go.  Clearly this is a bug, but not one that will stop me from tweeting the fact that I’m waiting at the airport! 

So these are the steps you should follow if your TweetDeck doesn’t show up in the primary (and only) monitor because it’s thinking it should display on an external monitor:

  1. If you’re using Windows Vista, browse to the following directory: C:\Users\<username>\AppData\Roaming.  If you’re using Windows XP, browse to the following directory instead: C:\Documents and Settings\<username>\AppData.
  2. Locate the folder that begins with TweetDeckFast.  For example, the complete name of that folder on my PC is TweetDeckFast.F9107117265DB7542C1A806C8DB837742CE14C21.1.
  3. Open the Local Store folder.
  4. Edit the preferences_<username>.xml configuration file with your favorite text editor.
  5. Change the windowState XML element’s x attribute to 0.  If you don’t see the TweetDeck UI, it is because the x attribute’s value is negative (which makes sense if the external monitor was on the left side).
  6. Save your changes to that file and load TweetDeck.  You should now be able to see the UI.