Welcome!

Microsoft Cloud Authors: Nick Basinger, Kevin Benedict, Pat Romanski, Liz McMillan, Lori MacVittie

Related Topics: Microsoft Cloud

Microsoft Cloud: Article

Why Code Snippets Are Not My Cup of Tea

But how about a few good refactoring options in the Visual Studio menu

In VB 2005, with the introduction of generic types, making a type-safe container became as simple as writing a few characters. With VB 2008 the trend continues. LINQ is now an integral part of the language, to name only one improvement.

With Visual Studio, the story is more or less the same. You got an advanced editor with IntelliSense and syntax coloring, a powerful debugger, code regions, etc. With Visual Studio 2005, a refactoring tool for VB has finally arrived. I don’t mind having to download and install the Refactor! for a VB add-in myself; it is free and even more powerful than the rudimentary refactoring capabilities that are built into Visual Studio for C#.

There is one Visual Studio feature I was never very enthusiastic about. Code Snippets let you insert small sections of code inside the file you are working on. Visual Studio comes with selection of some common “snippets” but you can also write your own and add them to a collection. There is even a separate tool, called Snippet Editor, that will help you create and edit your own snippets.

There are three flavors of code snippets:

  1. Snippets that let you insert common coding constructs like conditionals and loops. These are generally only a few statements long. I think these could be useful for someone learning the language and still not having complete command of the language syntax.
  2. Snippets that help you invoke some often-used functionality that the .NET framework provides. These are generally single line statements that use “My” namespace to implement the desired functionality. Today, core API is so huge that this can be a useful alternative to searching the MSDN.
  3. Sometimes snippets are larger pieces of code, occasionally written in the form of a function. Granted, viewed as examples, these snippets can be useful. However, if these snippets are used “as is,” the Code Snippet functionality is converted to nothing more than a posh copy-paste clipboard. In this case, Code Snippets almost encourage the poor practice of code duplication.

Is there a better way to reuse code than duplicating it with the help of Code Snippets? Yes, there is and you are already aware of it. It is achieved by using structured reuse mechanisms. For example, instead of pasting a function, create a reusable library (or “dll”) and place a function inside it. As you progress, structure your code along object-oriented principles in the form of classes and class hierarchies. For the sake of illustration, let’s take a look at one snippet containing a function.

The “Compare two files” snippet is found inside the “File System – Processing Drives, Folders and Files” snippet group. After you select the snippet, the code in Listing 1 is pasted inside your file.

The simplest way to make this code part of our managed, versioned code base is to create a new dynamically linked library project, add a module, called, for example, FileComparison, and move this function to a module. The only thing left to be done is to change function visibility from Private to Public. The whole project for a single function you ask. Well, this is only a start. If you needed to compare the content of two files, you might soon need to compare their size or creation date. Your newly created project is guaranteed to grow and new functions and modules will soon be added to the project.

By making this a function placed inside a module, we have started to structure our code. However, this structuring is performed in a procedural manner. I wonder if there is a way to do this in an object-oriented style. If we apply object-oriented principles successfully, we will be able to employ more efficient, higher-order reuse mechanisms.

I think I know what some of you are thinking at this point: “To write a class, than to declare and instantiate an object, to set properties and to call a method only to compare it to files? Isn’t the compare function from a code snippet a lot easier?”

In VB, this doesn’t have to be so tedious. In VB .NET you can write constructor methods that can be employed in order to achieve more terse syntax.

Let’s give this class a try. I’ll attempt to write my code so it reads as naturally as possible. I’ll call the class Files and rename a function to “HaveSameContent”. Instead of receiving the file names, I’ll add a constructor that will receive them and initialize related System.IO.FileInfo fields of a class. I’ll modify the HaveSameContent function so it’s not receiving parameters but using the FileInfo fields of a class instead. A newly created Files class looks like Listing 2.

Now, using this class to compare two files can be rather simple. You can invoke the functionality in a single line:

If New Files(file1, file2).HaveSameContent() Then

This line also reads close to “If files file1 and file2 have the same content then” and is not significantly more verbose than invoking original function pasted as a snippet. This is all pretty good, but I’m not completely happy yet about the result.

More Stories By Danijel Arsenovski

Danijel Arsenovski is a software developer from Santiago, Chile. He works as a Product and Solutions Architect at Excelsys S.A, designing Internet banking solutions for numerous clients in the region. He started experimenting with refactoring while overhauling a huge banking system, and he hasn't lost interest in refactoring ever since. He pioneered the use of refactoring as a vehicle for a VB 6 code upgrade to VB .NET. Danijel is the author of "Professional Refactoring in Visual Basic" published by Wrox, and is a contributing author for several major publications. He holds a Microsoft Certified Solution Developer (MCSD) certification and was named Visual Basic MVP in 2005. He blogs at http://blog.vbrefactoring.com.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


IoT & Smart Cities Stories
All in Mobile is a place where we continually maximize their impact by fostering understanding, empathy, insights, creativity and joy. They believe that a truly useful and desirable mobile app doesn't need the brightest idea or the most advanced technology. A great product begins with understanding people. It's easy to think that customers will love your app, but can you justify it? They make sure your final app is something that users truly want and need. The only way to do this is by ...
Digital Transformation and Disruption, Amazon Style - What You Can Learn. Chris Kocher is a co-founder of Grey Heron, a management and strategic marketing consulting firm. He has 25+ years in both strategic and hands-on operating experience helping executives and investors build revenues and shareholder value. He has consulted with over 130 companies on innovating with new business models, product strategies and monetization. Chris has held management positions at HP and Symantec in addition to ...
DXWorldEXPO LLC announced today that Big Data Federation to Exhibit at the 22nd International CloudEXPO, colocated with DevOpsSUMMIT and DXWorldEXPO, November 12-13, 2018 in New York City. Big Data Federation, Inc. develops and applies artificial intelligence to predict financial and economic events that matter. The company uncovers patterns and precise drivers of performance and outcomes with the aid of machine-learning algorithms, big data, and fundamental analysis. Their products are deployed...
Dynatrace is an application performance management software company with products for the information technology departments and digital business owners of medium and large businesses. Building the Future of Monitoring with Artificial Intelligence. Today we can collect lots and lots of performance data. We build beautiful dashboards and even have fancy query languages to access and transform the data. Still performance data is a secret language only a couple of people understand. The more busine...
The challenges of aggregating data from consumer-oriented devices, such as wearable technologies and smart thermostats, are fairly well-understood. However, there are a new set of challenges for IoT devices that generate megabytes or gigabytes of data per second. Certainly, the infrastructure will have to change, as those volumes of data will likely overwhelm the available bandwidth for aggregating the data into a central repository. Ochandarena discusses a whole new way to think about your next...
CloudEXPO | DevOpsSUMMIT | DXWorldEXPO are the world's most influential, independent events where Cloud Computing was coined and where technology buyers and vendors meet to experience and discuss the big picture of Digital Transformation and all of the strategies, tactics, and tools they need to realize their goals. Sponsors of DXWorldEXPO | CloudEXPO benefit from unmatched branding, profile building and lead generation opportunities.
Cell networks have the advantage of long-range communications, reaching an estimated 90% of the world. But cell networks such as 2G, 3G and LTE consume lots of power and were designed for connecting people. They are not optimized for low- or battery-powered devices or for IoT applications with infrequently transmitted data. Cell IoT modules that support narrow-band IoT and 4G cell networks will enable cell connectivity, device management, and app enablement for low-power wide-area network IoT. B...
The hierarchical architecture that distributes "compute" within the network specially at the edge can enable new services by harnessing emerging technologies. But Edge-Compute comes at increased cost that needs to be managed and potentially augmented by creative architecture solutions as there will always a catching-up with the capacity demands. Processing power in smartphones has enhanced YoY and there is increasingly spare compute capacity that can be potentially pooled. Uber has successfully ...
SYS-CON Events announced today that CrowdReviews.com has been named “Media Sponsor” of SYS-CON's 22nd International Cloud Expo, which will take place on June 5–7, 2018, at the Javits Center in New York City, NY. CrowdReviews.com is a transparent online platform for determining which products and services are the best based on the opinion of the crowd. The crowd consists of Internet users that have experienced products and services first-hand and have an interest in letting other potential buye...
When talking IoT we often focus on the devices, the sensors, the hardware itself. The new smart appliances, the new smart or self-driving cars (which are amalgamations of many ‘things'). When we are looking at the world of IoT, we should take a step back, look at the big picture. What value are these devices providing. IoT is not about the devices, its about the data consumed and generated. The devices are tools, mechanisms, conduits. This paper discusses the considerations when dealing with the...